function
stringlengths 61
9.1k
| testmethod
stringlengths 42
143
| location_fixed
stringlengths 43
98
| end_buggy
int64 10
12k
| location
stringlengths 43
98
| function_name
stringlengths 4
73
| source_buggy
stringlengths 655
442k
| prompt_complete
stringlengths 433
4.3k
| end_fixed
int64 10
12k
| comment
stringlengths 0
763
| bug_id
stringlengths 1
3
| start_fixed
int64 7
12k
| location_buggy
stringlengths 43
98
| source_dir
stringclasses 5
values | prompt_chat
stringlengths 420
3.86k
| start_buggy
int64 7
12k
| classes_modified
sequence | task_id
stringlengths 64
64
| function_signature
stringlengths 22
150
| prompt_complete_without_signature
stringlengths 404
4.23k
| project
stringclasses 17
values | indent
stringclasses 4
values | source_fixed
stringlengths 655
442k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
public void 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]");
} | com.google.javascript.jscomp.PeepholeFoldConstantsTest::testFoldGetElem | test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java | 777 | test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java | testFoldGetElem | /*
* 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 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 `testFoldGetElem` for the issue `Closure-747`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-747
//
// ## Issue-Title:
// tryFoldArrayAccess does not check for side effects
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Compile the following program with simple or advanced optimization:
// console.log([console.log('hello, '), 'world!'][1]);
//
// **What is the expected output? What do you see instead?**
// The expected output would preserve side effects. It would not transform the program at all or transform it into:
//
// console.log((console.log("hello"), "world!"));
//
// Instead, the program is transformed into:
//
// console.log("world!");
//
// **What version of the product are you using? On what operating system?**
// Revision 2022. Ubuntu 12.04.
//
// **Please provide any additional information below.**
// tryFoldArrayAccess in com.google.javascript.jscomp.PeepholeFoldConstants should check whether every array element that is not going to be preserved has no side effects.
//
//
public void testFoldGetElem() {
| 777 | 23 | 763 | test/com/google/javascript/jscomp/PeepholeFoldConstantsTest.java | test | ```markdown
## Issue-ID: Closure-747
## Issue-Title:
tryFoldArrayAccess does not check for side effects
## Issue-Description:
**What steps will reproduce the problem?**
1. Compile the following program with simple or advanced optimization:
console.log([console.log('hello, '), 'world!'][1]);
**What is the expected output? What do you see instead?**
The expected output would preserve side effects. It would not transform the program at all or transform it into:
console.log((console.log("hello"), "world!"));
Instead, the program is transformed into:
console.log("world!");
**What version of the product are you using? On what operating system?**
Revision 2022. Ubuntu 12.04.
**Please provide any additional information below.**
tryFoldArrayAccess in com.google.javascript.jscomp.PeepholeFoldConstants should check whether every array element that is not going to be preserved has no side effects.
```
You are a professional Java test case writer, please create a test case named `testFoldGetElem` for the issue `Closure-747`, utilizing the provided issue report information and the following function signature.
```java
public void testFoldGetElem() {
```
| 763 | [
"com.google.javascript.jscomp.PeepholeFoldConstants"
] | 343ac16e223b07e426722e91998072bbd3b6a5b657039a63b7af7ab746dd7b1e | public void testFoldGetElem() | // You are a professional Java test case writer, please create a test case named `testFoldGetElem` for the issue `Closure-747`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-747
//
// ## Issue-Title:
// tryFoldArrayAccess does not check for side effects
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Compile the following program with simple or advanced optimization:
// console.log([console.log('hello, '), 'world!'][1]);
//
// **What is the expected output? What do you see instead?**
// The expected output would preserve side effects. It would not transform the program at all or transform it into:
//
// console.log((console.log("hello"), "world!"));
//
// Instead, the program is transformed into:
//
// console.log("world!");
//
// **What version of the product are you using? On what operating system?**
// Revision 2022. Ubuntu 12.04.
//
// **Please provide any additional information below.**
// tryFoldArrayAccess in com.google.javascript.jscomp.PeepholeFoldConstants should check whether every array element that is not going to be preserved has no side effects.
//
//
| 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 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);
}
} |
||
public void testElementDOM() {
doTestElement(DocumentContainer.MODEL_DOM);
} | org.apache.commons.jxpath.ri.model.ExternalXMLNamespaceTest::testElementDOM | src/test/org/apache/commons/jxpath/ri/model/ExternalXMLNamespaceTest.java | 70 | src/test/org/apache/commons/jxpath/ri/model/ExternalXMLNamespaceTest.java | testElementDOM | /*
* 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.model;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.xml.DocumentContainer;
/**
* Test externally registered XML namespaces; JXPATH-97.
*
* @author Matt Benson
* @version $Revision$ $Date$
*/
public class ExternalXMLNamespaceTest extends JXPathTestCase {
protected JXPathContext context;
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public ExternalXMLNamespaceTest(String name) {
super(name);
}
protected DocumentContainer createDocumentContainer(String model) {
DocumentContainer result = new DocumentContainer(JXPathTestCase.class
.getResource("ExternalNS.xml"), model);
//this setting only works for DOM, so no JDOM tests :|
result.setNamespaceAware(false);
return result;
}
protected void doTest(String xpath, String model, String expected) {
JXPathContext context = JXPathContext
.newContext(createDocumentContainer(model));
context.registerNamespace("A", "foo");
context.registerNamespace("B", "bar");
assertXPathValue(context, xpath, expected);
}
protected void doTestAttribute(String model) {
doTest("/ElementA/@A:myAttr", model, "Mytype");
}
protected void doTestElement(String model) {
doTest("/ElementA/B:ElementB", model, "MY VALUE");
}
public void testAttributeDOM() {
doTestAttribute(DocumentContainer.MODEL_DOM);
}
public void testElementDOM() {
doTestElement(DocumentContainer.MODEL_DOM);
}
} | // You are a professional Java test case writer, please create a test case named `testElementDOM` for the issue `JxPath-JXPATH-97`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-97
//
// ## Issue-Title:
// Incomplete handling of undefined namespaces
//
// ## Issue-Description:
//
// Mcduffey, Joe <jdmcduf@nsa.gov>
//
//
// Can someone tell me how to register namespaces so that attributes with namespaces does not cause the exception
//
//
// org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
//
// unknown namespace prefix: xsi
//
//
// For example the following
//
// <ElementA A:myAttr="Mytype">
//
// <B:ElementB>MY VALUE</B:ElementB>
//
// </ElementA>
//
//
// Would result in the following exception:
//
// org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
//
// unknown namespace prefix: A
//
//
// FYI: In this example there was a namespace decaration in the file and I also manually called the
//
// registerNamespace(A,"/http...");
//
// registerNamespace(B,"/http...");
//
//
// There was no problem encountered for elements. Only attributes. Can someone help? Thanks.
//
//
//
//
//
public void testElementDOM() {
| 70 | 12 | 68 | src/test/org/apache/commons/jxpath/ri/model/ExternalXMLNamespaceTest.java | src/test | ```markdown
## Issue-ID: JxPath-JXPATH-97
## Issue-Title:
Incomplete handling of undefined namespaces
## Issue-Description:
Mcduffey, Joe <jdmcduf@nsa.gov>
Can someone tell me how to register namespaces so that attributes with namespaces does not cause the exception
org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
unknown namespace prefix: xsi
For example the following
<ElementA A:myAttr="Mytype">
<B:ElementB>MY VALUE</B:ElementB>
</ElementA>
Would result in the following exception:
org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
unknown namespace prefix: A
FYI: In this example there was a namespace decaration in the file and I also manually called the
registerNamespace(A,"/http...");
registerNamespace(B,"/http...");
There was no problem encountered for elements. Only attributes. Can someone help? Thanks.
```
You are a professional Java test case writer, please create a test case named `testElementDOM` for the issue `JxPath-JXPATH-97`, utilizing the provided issue report information and the following function signature.
```java
public void testElementDOM() {
```
| 68 | [
"org.apache.commons.jxpath.ri.model.dom.DOMNodePointer"
] | 35678f23c16ad7ab65076aa632a00229f7bc3ae9698c0266186fd8bffefc7857 | public void testElementDOM() | // You are a professional Java test case writer, please create a test case named `testElementDOM` for the issue `JxPath-JXPATH-97`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-97
//
// ## Issue-Title:
// Incomplete handling of undefined namespaces
//
// ## Issue-Description:
//
// Mcduffey, Joe <jdmcduf@nsa.gov>
//
//
// Can someone tell me how to register namespaces so that attributes with namespaces does not cause the exception
//
//
// org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
//
// unknown namespace prefix: xsi
//
//
// For example the following
//
// <ElementA A:myAttr="Mytype">
//
// <B:ElementB>MY VALUE</B:ElementB>
//
// </ElementA>
//
//
// Would result in the following exception:
//
// org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
//
// unknown namespace prefix: A
//
//
// FYI: In this example there was a namespace decaration in the file and I also manually called the
//
// registerNamespace(A,"/http...");
//
// registerNamespace(B,"/http...");
//
//
// There was no problem encountered for elements. Only attributes. Can someone help? Thanks.
//
//
//
//
//
| 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.model;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.xml.DocumentContainer;
/**
* Test externally registered XML namespaces; JXPATH-97.
*
* @author Matt Benson
* @version $Revision$ $Date$
*/
public class ExternalXMLNamespaceTest extends JXPathTestCase {
protected JXPathContext context;
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public ExternalXMLNamespaceTest(String name) {
super(name);
}
protected DocumentContainer createDocumentContainer(String model) {
DocumentContainer result = new DocumentContainer(JXPathTestCase.class
.getResource("ExternalNS.xml"), model);
//this setting only works for DOM, so no JDOM tests :|
result.setNamespaceAware(false);
return result;
}
protected void doTest(String xpath, String model, String expected) {
JXPathContext context = JXPathContext
.newContext(createDocumentContainer(model));
context.registerNamespace("A", "foo");
context.registerNamespace("B", "bar");
assertXPathValue(context, xpath, expected);
}
protected void doTestAttribute(String model) {
doTest("/ElementA/@A:myAttr", model, "Mytype");
}
protected void doTestElement(String model) {
doTest("/ElementA/B:ElementB", model, "MY VALUE");
}
public void testAttributeDOM() {
doTestAttribute(DocumentContainer.MODEL_DOM);
}
public void testElementDOM() {
doTestElement(DocumentContainer.MODEL_DOM);
}
} |
||
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 x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c");
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)");
} | com.google.javascript.jscomp.InlineObjectLiteralsTest::testObject10 | test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java | 206 | test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java | testObject10 | /*
* 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 x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c");
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 a; a = {x:1, y:2}; f(a.x, a.y2);");
}
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 a; while (1) { f(a.x, a.y); a = {x:1, y:1};}");
}
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");
}
public void testIssue724() {
testSameLocal(
"var getType; getType = {};" +
"return functionToCheck && " +
" getType.toString.apply(functionToCheck) === " +
" '[object Function]';");
}
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 `testObject10` for the issue `Closure-724`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-724
//
// ## Issue-Title:
// closure compiler screws up a perfectly valid isFunction() implementation
//
// ## Issue-Description:
// hi, this function does not get compiled correctly via google closure compiler
//
// isFunction = function(functionToCheck) {
// var getType;
// getType = {}; //just an object
// return functionToCheck && getType.toString.apply(functionToCheck) === '[object Function]';
// };
//
// gets compiled into
//
// isFunction = function(a) {
// return a && "[object Function]" === (void 0).apply(a)
// };
//
// to make it work, we have to use an array instead of an object (even though we just want to call the object toString method)
//
// isFunction = function(functionToCheck) {
// var getType;
// getType = []; //not it's an array
// return functionToCheck && getType.toString.apply(functionToCheck) === '[object Function]';
// };
//
// gets compiled into
//
// isFunction = function(a) {
// var b;
// b = [];
// return a && "[object Function]" === b.toString.apply(a)
// };
//
// and it does what it should do.
//
// i wasted an hour to find that bug. bugs me. great tool otherwise.
//
//
public void testObject10() {
| 206 | 29 | 166 | test/com/google/javascript/jscomp/InlineObjectLiteralsTest.java | test | ```markdown
## Issue-ID: Closure-724
## Issue-Title:
closure compiler screws up a perfectly valid isFunction() implementation
## Issue-Description:
hi, this function does not get compiled correctly via google closure compiler
isFunction = function(functionToCheck) {
var getType;
getType = {}; //just an object
return functionToCheck && getType.toString.apply(functionToCheck) === '[object Function]';
};
gets compiled into
isFunction = function(a) {
return a && "[object Function]" === (void 0).apply(a)
};
to make it work, we have to use an array instead of an object (even though we just want to call the object toString method)
isFunction = function(functionToCheck) {
var getType;
getType = []; //not it's an array
return functionToCheck && getType.toString.apply(functionToCheck) === '[object Function]';
};
gets compiled into
isFunction = function(a) {
var b;
b = [];
return a && "[object Function]" === b.toString.apply(a)
};
and it does what it should do.
i wasted an hour to find that bug. bugs me. great tool otherwise.
```
You are a professional Java test case writer, please create a test case named `testObject10` for the issue `Closure-724`, utilizing the provided issue report information and the following function signature.
```java
public void testObject10() {
```
| 166 | [
"com.google.javascript.jscomp.InlineObjectLiterals"
] | 369f05c14d87b86ddf808b76b727301c03541ae5e9df81d53e2bd80affcb1617 | public void testObject10() | // You are a professional Java test case writer, please create a test case named `testObject10` for the issue `Closure-724`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-724
//
// ## Issue-Title:
// closure compiler screws up a perfectly valid isFunction() implementation
//
// ## Issue-Description:
// hi, this function does not get compiled correctly via google closure compiler
//
// isFunction = function(functionToCheck) {
// var getType;
// getType = {}; //just an object
// return functionToCheck && getType.toString.apply(functionToCheck) === '[object Function]';
// };
//
// gets compiled into
//
// isFunction = function(a) {
// return a && "[object Function]" === (void 0).apply(a)
// };
//
// to make it work, we have to use an array instead of an object (even though we just want to call the object toString method)
//
// isFunction = function(functionToCheck) {
// var getType;
// getType = []; //not it's an array
// return functionToCheck && getType.toString.apply(functionToCheck) === '[object Function]';
// };
//
// gets compiled into
//
// isFunction = function(a) {
// var b;
// b = [];
// return a && "[object Function]" === b.toString.apply(a)
// };
//
// and it does what it should do.
//
// i wasted an hour to find that bug. bugs me. great tool otherwise.
//
//
| 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 x = {}; var b = f(); x = {a:a, b:b}; if(x.a) g(x.b) + x.c");
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 a; a = {x:1, y:2}; f(a.x, a.y2);");
}
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 a; while (1) { f(a.x, a.y); a = {x:1, y:1};}");
}
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");
}
public void testIssue724() {
testSameLocal(
"var getType; getType = {};" +
"return functionToCheck && " +
" getType.toString.apply(functionToCheck) === " +
" '[object Function]';");
}
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 testUnrecognizedOption2() throws Exception
{
String[] args = new String[] { "-z", "-abtoast", "foo", "bar" };
try
{
parser.parse(options, args);
fail("UnrecognizedOptionException wasn't thrown");
}
catch (UnrecognizedOptionException e)
{
assertEquals("-z", e.getOption());
}
} | org.apache.commons.cli.PosixParserTest::testUnrecognizedOption2 | src/test/org/apache/commons/cli/PosixParserTest.java | 115 | src/test/org/apache/commons/cli/PosixParserTest.java | testUnrecognizedOption2 | /**
* 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 testUnrecognizedOption2() throws Exception
{
String[] args = new String[] { "-z", "-abtoast", "foo", "bar" };
try
{
parser.parse(options, args);
fail("UnrecognizedOptionException wasn't thrown");
}
catch (UnrecognizedOptionException e)
{
assertEquals("-z", 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 testStop2() throws Exception
{
String[] args = new String[]{"-z",
"-a",
"-btoast"};
CommandLine cl = parser.parse(options, args, true);
assertFalse("Confirm -a is not set", cl.hasOption("a"));
assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
}
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 `testUnrecognizedOption2` for the issue `Cli-CLI-164`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-164
//
// ## Issue-Title:
// PosixParser ignores unrecognized tokens starting with '-'
//
// ## Issue-Description:
//
// PosixParser doesn't handle properly unrecognized tokens starting with '-' when stopAtNonOption is enabled, the token is simply ignored.
//
//
// For example, if the option 'a' is defined, the following command line:
//
//
//
//
// ```
// -z -a foo
// ```
//
//
// is interpreted as:
//
//
//
//
// ```
// -a foo
// ```
//
//
//
//
//
public void testUnrecognizedOption2() throws Exception {
| 115 | 19 | 102 | src/test/org/apache/commons/cli/PosixParserTest.java | src/test | ```markdown
## Issue-ID: Cli-CLI-164
## Issue-Title:
PosixParser ignores unrecognized tokens starting with '-'
## Issue-Description:
PosixParser doesn't handle properly unrecognized tokens starting with '-' when stopAtNonOption is enabled, the token is simply ignored.
For example, if the option 'a' is defined, the following command line:
```
-z -a foo
```
is interpreted as:
```
-a foo
```
```
You are a professional Java test case writer, please create a test case named `testUnrecognizedOption2` for the issue `Cli-CLI-164`, utilizing the provided issue report information and the following function signature.
```java
public void testUnrecognizedOption2() throws Exception {
```
| 102 | [
"org.apache.commons.cli.PosixParser"
] | 36f7b5642e5611f9d87d5d4d8d6db66c25d6df7a513600bbef6d2734b7d0a66c | public void testUnrecognizedOption2() throws Exception
| // You are a professional Java test case writer, please create a test case named `testUnrecognizedOption2` for the issue `Cli-CLI-164`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-164
//
// ## Issue-Title:
// PosixParser ignores unrecognized tokens starting with '-'
//
// ## Issue-Description:
//
// PosixParser doesn't handle properly unrecognized tokens starting with '-' when stopAtNonOption is enabled, the token is simply ignored.
//
//
// For example, if the option 'a' is defined, the following command line:
//
//
//
//
// ```
// -z -a foo
// ```
//
//
// is interpreted as:
//
//
//
//
// ```
// -a foo
// ```
//
//
//
//
//
| 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 testUnrecognizedOption2() throws Exception
{
String[] args = new String[] { "-z", "-abtoast", "foo", "bar" };
try
{
parser.parse(options, args);
fail("UnrecognizedOptionException wasn't thrown");
}
catch (UnrecognizedOptionException e)
{
assertEquals("-z", 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 testStop2() throws Exception
{
String[] args = new String[]{"-z",
"-a",
"-btoast"};
CommandLine cl = parser.parse(options, args, true);
assertFalse("Confirm -a is not set", cl.hasOption("a"));
assertTrue("Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
}
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 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());
} | org.joda.time.TestDateTimeZoneCutover::test_DateTime_constructor_Moscow_Autumn | src/test/java/org/joda/time/TestDateTimeZoneCutover.java | 922 | src/test/java/org/joda/time/TestDateTimeZoneCutover.java | test_DateTime_constructor_Moscow_Autumn | /*
* 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());
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
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 `test_DateTime_constructor_Moscow_Autumn` for the issue `Time-90`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-90
//
// ## Issue-Title:
// #90 DateTimeZone.getOffsetFromLocal error during DST transition
//
//
//
//
//
// ## Issue-Description:
// This may be a failure of my understanding, but the comments in DateTimeZone.getOffsetFromLocal lead me to believe that if an ambiguous local time is given, the offset corresponding to the later of the two possible UTC instants will be returned - i.e. the greater offset.
//
//
// This doesn't appear to tally with my experience. In fall 2009, America/Los\_Angeles changed from -7 to -8 at 2am wall time on November 11. Thus 2am became 1am - so 1:30am is ambiguous. I would therefore expect that constructing a DateTime for November 11th, 1:30am would give an instant corresponding with the later value (i.e. 9:30am UTC). This appears not to be the case:
//
//
// import org.joda.time.DateTime;
//
// import org.joda.time.DateTimeZone;
//
//
// public class TzTest {
//
// public static void main(String[] args) throws Exception {
//
// DateTimeZone zone = DateTimeZone.forID("America/Los\_Angeles");
//
// DateTime when1 = new DateTime(2009, 11, 1, 0, 30, 0, 0, zone);
//
// DateTime when2 = new DateTime(2009, 11, 1, 1, 30, 0, 0, zone);
//
// DateTime when3 = new DateTime(2009, 11, 1, 2, 30, 0, 0, zone);
//
// System.out.println(when1);
//
// System.out.println(when2);
//
// System.out.println(when3);
//
// }
//
// }
//
//
// Results:
//
//
// 2009-11-01T00:30:00.000-07:00 // Correct
//
// 2009-11-01T01:30:00.000-07:00 // Should be -08:00
//
// 2009-11-01T02:30:00.000-08:00 // Correct
//
//
//
//
public void test_DateTime_constructor_Moscow_Autumn() {
| 922 | 25 | 919 | src/test/java/org/joda/time/TestDateTimeZoneCutover.java | src/test/java | ```markdown
## Issue-ID: Time-90
## Issue-Title:
#90 DateTimeZone.getOffsetFromLocal error during DST transition
## Issue-Description:
This may be a failure of my understanding, but the comments in DateTimeZone.getOffsetFromLocal lead me to believe that if an ambiguous local time is given, the offset corresponding to the later of the two possible UTC instants will be returned - i.e. the greater offset.
This doesn't appear to tally with my experience. In fall 2009, America/Los\_Angeles changed from -7 to -8 at 2am wall time on November 11. Thus 2am became 1am - so 1:30am is ambiguous. I would therefore expect that constructing a DateTime for November 11th, 1:30am would give an instant corresponding with the later value (i.e. 9:30am UTC). This appears not to be the case:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class TzTest {
public static void main(String[] args) throws Exception {
DateTimeZone zone = DateTimeZone.forID("America/Los\_Angeles");
DateTime when1 = new DateTime(2009, 11, 1, 0, 30, 0, 0, zone);
DateTime when2 = new DateTime(2009, 11, 1, 1, 30, 0, 0, zone);
DateTime when3 = new DateTime(2009, 11, 1, 2, 30, 0, 0, zone);
System.out.println(when1);
System.out.println(when2);
System.out.println(when3);
}
}
Results:
2009-11-01T00:30:00.000-07:00 // Correct
2009-11-01T01:30:00.000-07:00 // Should be -08:00
2009-11-01T02:30:00.000-08:00 // Correct
```
You are a professional Java test case writer, please create a test case named `test_DateTime_constructor_Moscow_Autumn` for the issue `Time-90`, utilizing the provided issue report information and the following function signature.
```java
public void test_DateTime_constructor_Moscow_Autumn() {
```
| 919 | [
"org.joda.time.DateTimeZone"
] | 372a56e701836df75a3510517d16145dc52cedf9e6c680eb5ddbc12f5a3aa003 | public void test_DateTime_constructor_Moscow_Autumn() | // You are a professional Java test case writer, please create a test case named `test_DateTime_constructor_Moscow_Autumn` for the issue `Time-90`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-90
//
// ## Issue-Title:
// #90 DateTimeZone.getOffsetFromLocal error during DST transition
//
//
//
//
//
// ## Issue-Description:
// This may be a failure of my understanding, but the comments in DateTimeZone.getOffsetFromLocal lead me to believe that if an ambiguous local time is given, the offset corresponding to the later of the two possible UTC instants will be returned - i.e. the greater offset.
//
//
// This doesn't appear to tally with my experience. In fall 2009, America/Los\_Angeles changed from -7 to -8 at 2am wall time on November 11. Thus 2am became 1am - so 1:30am is ambiguous. I would therefore expect that constructing a DateTime for November 11th, 1:30am would give an instant corresponding with the later value (i.e. 9:30am UTC). This appears not to be the case:
//
//
// import org.joda.time.DateTime;
//
// import org.joda.time.DateTimeZone;
//
//
// public class TzTest {
//
// public static void main(String[] args) throws Exception {
//
// DateTimeZone zone = DateTimeZone.forID("America/Los\_Angeles");
//
// DateTime when1 = new DateTime(2009, 11, 1, 0, 30, 0, 0, zone);
//
// DateTime when2 = new DateTime(2009, 11, 1, 1, 30, 0, 0, zone);
//
// DateTime when3 = new DateTime(2009, 11, 1, 2, 30, 0, 0, zone);
//
// System.out.println(when1);
//
// System.out.println(when2);
//
// System.out.println(when3);
//
// }
//
// }
//
//
// Results:
//
//
// 2009-11-01T00:30:00.000-07:00 // Correct
//
// 2009-11-01T01:30:00.000-07:00 // Should be -08:00
//
// 2009-11-01T02:30:00.000-08:00 // Correct
//
//
//
//
| 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());
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
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 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'");
} | com.google.javascript.jscomp.FoldConstantsTest::testStringJoinAdd | test/com/google/javascript/jscomp/FoldConstantsTest.java | 657 | test/com/google/javascript/jscomp/FoldConstantsTest.java | testStringJoinAdd | /*
* 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;
import com.google.javascript.rhino.Node;
public class FoldConstantsTest extends CompilerTestCase {
// TODO(user): Remove this when we no longer need to do string comparison.
private FoldConstantsTest(boolean compareAsTree) {
super("", compareAsTree);
}
public FoldConstantsTest() {
super();
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
return new CompilerPass() {
public void process(Node externs, Node js) {
NodeTraversal.traverse(compiler, js, new FoldConstants(compiler));
}
};
}
@Override
protected int getNumRepetitions() {
// Reduce this to 2 if we get better expression evaluators.
return 2;
}
void foldSame(String js) {
testSame(js);
}
void fold(String js, String expected) {
test(js, expected);
}
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.
void assertResultString(String js, String expected) {
FoldConstantsTest scTest = new FoldConstantsTest(false);
scTest.test(js, expected);
}
public void testFoldBlock() {
fold("{{foo()}}", "foo()");
fold("{foo();{}}", "foo()");
fold("{{foo()}{}}", "foo()");
fold("{{foo()}{bar()}}", "foo();bar()");
fold("{if(false)foo(); {bar()}}", "bar()");
fold("{if(false)if(false)if(false)foo(); {bar()}}", "bar()");
fold("{'hi'}", "");
fold("{x==3}", "");
fold("{ (function(){x++}) }", "");
fold("function(){return;}", "function(){return;}");
fold("function(){return 3;}", "function(){return 3}");
fold("function(){if(x)return; x=3; return; }",
"function(){if(x)return; x=3; return; }");
fold("{x=3;;;y=2;;;}", "x=3;y=2");
// Cases to test for empty block.
fold("while(x()){x}", "while(x());");
fold("while(x()){x()}", "while(x())x()");
fold("for(x=0;x<100;x++){x}", "for(x=0;x<100;x++);");
fold("for(x in y){x}", "for(x in y);");
}
/** Check that removing blocks with 1 child works */
public void testFoldOneChildBlocks() {
fold("function(){if(x)a();x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){a()}x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){return 3}}",
"function(){if(x)return 3}");
fold("function(){if(x){a()}}",
"function(){x&&a()}");
fold("function(){if(x){throw 1}}", "function(){if(x)throw 1;}");
// Try it out with functions
fold("function(){if(x){foo()}}", "function(){x&&foo()}");
fold("function(){if(x){foo()}else{bar()}}",
"function(){x?foo():bar()}");
// Try it out with properties and methods
fold("function(){if(x){a.b=1}}", "function(){if(x)a.b=1}");
fold("function(){if(x){a.b*=1}}", "function(){if(x)a.b*=1}");
fold("function(){if(x){a.b+=1}}", "function(){if(x)a.b+=1}");
fold("function(){if(x){++a.b}}", "function(){x&&++a.b}");
fold("function(){if(x){a.foo()}}", "function(){x&&a.foo()}");
// Try it out with throw/catch/finally [which should not change]
fold("function(){try{foo()}catch(e){bar(e)}finally{baz()}}",
"function(){try{foo()}catch(e){bar(e)}finally{baz()}}");
// Try it out with switch statements
fold("function(){switch(x){case 1:break}}",
"function(){switch(x){case 1:break}}");
fold("function(){switch(x){default:{break}}}",
"function(){switch(x){default:break}}");
fold("function(){switch(x){default:{break}}}",
"function(){switch(x){default:break}}");
fold("function(){switch(x){default:x;case 1:return 2}}",
"function(){switch(x){default:case 1:return 2}}");
// Do while loops stay in a block if that's where they started
fold("function(){if(e1){do foo();while(e2)}else foo2()}",
"function(){if(e1){do foo();while(e2)}else foo2()}");
// Test an obscure case with do and while
fold("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
// Play with nested IFs
fold("function(){if(x){if(y)foo()}}",
"function(){x&&y&&foo()}");
fold("function(){if(x){if(y)foo();else bar()}}",
"function(){if(x)y?foo():bar()}");
fold("function(){if(x){if(y)foo()}else bar()}",
"function(){if(x)y&&foo();else bar()}");
fold("function(){if(x){if(y)foo();else bar()}else{baz()}}",
"function(){if(x)y?foo():bar();else baz()}");
fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
"if(e1)while(e2)e3&&foo();else bar()");
fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
"if(e1)with(e2)e3&&foo();else bar()");
fold("if(x){if(y){var x;}}", "if(x)if(y)var x");
fold("if(x){ if(y){var x;}else{var z;} }",
"if(x)if(y)var x;else var z");
// NOTE - technically we can remove the blocks since both the parent
// and child have elses. But we don't since it causes ambiguities in
// some cases where not all descendent ifs having elses
fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
"if(x)if(y)var x;else var z;else var w");
fold("if (x) {var x;}else { if (y) { var y;} }",
"if(x)var x;else if(y)var y");
// Here's some of the ambiguous cases
fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
"if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
fold("function(){foo()}", "function(){foo()}");
fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
fold("try{foo()}catch(ex){bar()}finally{baz()}",
"try{foo()}catch(ex){bar()}finally{baz()}");
// ensure that block folding does not break hook ifs
fold("if(x){if(true){foo();foo()}else{bar();bar()}}",
"if(x){foo();foo()}");
fold("if(x){if(false){foo();foo()}else{bar();bar()}}",
"if(x){bar();bar()}");
// Cases where the then clause has no side effects.
fold("if(x()){}", "x()");
fold("if(x()){} else {x()}", "x()||x()");
fold("if(x){}", ""); // Even the condition has no side effect.
fold("if(a()){A()} else if (b()) {} else {C()}",
"if(a())A();else b()||C()");
fold("if(a()){} else if (b()) {} else {C()}",
"a()||b()||C()");
fold("if(a()){A()} else if (b()) {} else if (c()) {} else{D()}",
"if(a())A();else b()||c()||D()");
fold("if(a()){} else if (b()) {} else if (c()) {} else{D()}",
"a()||b()||c()||D()");
fold("if(a()){A()} else if (b()) {} else if (c()) {} else{}",
"if(a())A();else b()||c()");
// Verify that non-global scope works.
fold("function foo(){if(x()){}}", "function foo(){x()}");
}
public void testFoldOneChildBlocksStringCompare() {
// The expected parse tree has a BLOCK structure around the true branch.
assertResultString("if(x){if(y){var x;}}else{var z;}",
"if(x){if(y)var x}else var z");
}
/** Test a particularly hairy edge case. */
public void testNecessaryDanglingElse() {
// The extra block is added by CodeGenerator. The logic to avoid ambiguous
// else clauses used to be in FoldConstants, so the test is here for
// legacy reasons.
assertResultString(
"if(x)if(y){y();z()}else;else x()", "if(x){if(y){y();z()}}else x()");
}
/** Try to remove spurious blocks with multiple children */
public void testFoldBlocksWithManyChildren() {
fold("function f() { if (false) {} }", "function f(){}");
fold("function f() { { if (false) {} if (true) {} {} } }",
"function f(){}");
fold("{var x; var y; var z; function f() { { var a; { var b; } } } }",
"var x;var y;var z;function f(){var a;var b}");
}
/** Try to minimize returns */
public void testFoldReturns() {
fold("function(){if(x)return 1;else return 2}",
"function(){return x?1:2}");
fold("function(){if(x)return 1+x;else return 2-x}",
"function(){return x?1+x:2-x}");
fold("function(){if(x)return y += 1;else return y += 2}",
"function(){return x?(y+=1):(y+=2)}");
// don't touch cases where either side doesn't return a value
foldSame("function(){if(x)return;else return 2-x}");
foldSame("function(){if(x)return x;else return}");
// if-then-else duplicate statement removal handles this case:
fold("function(){if(x)return;else return}",
"function(){return}");
}
/** Try to minimize assignments */
public void testFoldAssignments() {
fold("function(){if(x)y=3;else y=4;}", "function(){y=x?3:4}");
fold("function(){if(x)y=1+a;else y=2+a;}", "function(){y=x?1+a:2+a}");
// and operation assignments
fold("function(){if(x)y+=1;else y+=2;}", "function(){y+=x?1:2}");
fold("function(){if(x)y-=1;else y-=2;}", "function(){y-=x?1:2}");
fold("function(){if(x)y%=1;else y%=2;}", "function(){y%=x?1:2}");
fold("function(){if(x)y|=1;else y|=2;}", "function(){y|=x?1:2}");
// sanity check, don't fold if the 2 ops don't match
foldSame("function(){if(x)y-=1;else y+=2}");
// sanity check, don't fold if the 2 LHS don't match
foldSame("function(){if(x)y-=1;else z-=1}");
// sanity check, don't fold if there are potential effects
foldSame("function(){if(x)y().a=3;else y().a=4}");
}
public void testBug1059649() {
// ensure that folding blocks with a single var node doesn't explode
fold("if(x){var y=3;}var z=5", "if(x)var y=3;var z=5");
// With normalization, we no longer have this case.
foldSame("if(x){var y=3;}else{var y=4;}var z=5");
fold("while(x){var y=3;}var z=5", "while(x)var y=3;var z=5");
fold("for(var i=0;i<10;i++){var y=3;}var z=5",
"for(var i=0;i<10;i++)var y=3;var z=5");
fold("for(var i in x){var y=3;}var z=5",
"for(var i in x)var y=3;var z=5");
fold("do{var y=3;}while(x);var z=5", "do var y=3;while(x);var z=5");
}
public void testUndefinedComparison() {
fold("if (0 == 0){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined == undefined){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined == null){ x = 1; } else { x = 2; }", "x=1");
// fold("if (undefined == NaN){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == 0){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == 1){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == 'hi'){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == true){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == false){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined === undefined){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined === null){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined === void 0){ x = 1; } else { x = 2; }", "x=1");
// foldSame("if (undefined === void foo()){ x = 1; } else { x = 2; }");
foldSame("x = (undefined == this) ? 1 : 2;");
foldSame("x = (undefined == x) ? 1 : 2;");
fold("if (undefined != undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined != null){ x = 1; } else { x = 2; }", "x=2");
// fold("if (undefined != NaN){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != 0){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != 1){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != 'hi'){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != true){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != false){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined !== undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined !== null){ x = 1; } else { x = 2; }", "x=1");
foldSame("x = (undefined != this) ? 1 : 2;");
foldSame("x = (undefined != x) ? 1 : 2;");
fold("if (undefined < undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined > undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined >= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined <= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (0 < undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (true > undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if ('hi' >= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (null <= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined < 0){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined > true){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined >= 'hi'){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined <= null){ x = 1; } else { x = 2; }", "x=2");
fold("if (null == undefined){ x = 1; } else { x = 2; }", "x=1");
// fold("if (NaN == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (0 == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (1 == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if ('hi' == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (true == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (false == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (null === undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (void 0 === undefined){ x = 1; } else { x = 2; }", "x=1");
// foldSame("if (void foo() === undefined){ x = 1; } else { x = 2; }");
foldSame("x = (this == undefined) ? 1 : 2;");
foldSame("x = (x == undefined) ? 1 : 2;");
}
public void testHookIf() {
fold("if (1){ x=1; } else { x = 2;}", "x=1");
fold("if (false){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (null){ x = 1; } else { x = 2; }", "x=2");
fold("if (void 0){ x = 1; } else { x = 2; }", "x=2");
// foldSame("if (void foo()){ x = 1; } else { x = 2; }");
fold("if (false){ x = 1; } else if (true) { x = 3; } else { x = 2; }",
"x=3");
fold("if (false){ x = 1; } else if (cond) { x = 2; } else { x = 3; }",
"x=cond?2:3");
fold("var x = (true) ? 1 : 0", "var x=1");
fold("var y = (true) ? ((false) ? 12 : (cond ? 1 : 2)) : 13",
"var y=cond?1:2");
fold("if (x){ x = 1; } else if (false) { x = 3; }", "if(x)x=1");
fold("x?void 0:y()", "x||y()");
fold("!x?void 0:y()", "x&&y()");
foldSame("var z=x?void 0:y()");
foldSame("z=x?void 0:y()");
foldSame("z*=x?void 0:y()");
fold("x?y():void 0", "x&&y()");
foldSame("var z=x?y():void 0");
foldSame("(w?x:void 0).y=z");
foldSame("(w?x:void 0).y+=z");
}
public void testRemoveDuplicateStatements() {
fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
"x=(a) ? 1 : 2; x++");
fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
" else { x = 2; x++; y += 1; z = pi; }",
"x=(a) ? 1 : 2; x++; y += 1; z = pi;");
fold("function z() {" +
"if (a) { foo(); return true } else { goo(); return true }" +
"}",
"function z() {(a) ? foo() : goo(); return true}");
fold("function z() {if (a) { foo(); x = true; return true " +
"} else { goo(); x = true; return true }}",
"function z() {(a) ? foo() : goo(); x = true; return true}");
fold("function z() {if (a) { return true }" +
"else if (b) { return true }" +
"else { return true }}",
"function z() {return true;}");
fold("function z() {if (a()) { return true }" +
"else if (b()) { return true }" +
"else { return true }}",
"function z() {if (!a()) { b() } return true;}");
fold("function z() {" +
" if (a) { bar(); foo(); return true }" +
" else { bar(); goo(); return true }" +
"}",
"function z() {" +
" if (a) { bar(); foo(); }" +
" else { bar(); goo(); }" +
" return true;" +
"}");
}
public void testNotCond() {
fold("function(){if(!x)foo()}", "function(){x||foo()}");
fold("function(){if(!x)b=1}", "function(){x||(b=1)}");
fold("if(!x)z=1;else if(y)z=2", "if(x){if(y)z=2}else z=1");
foldSame("function(){if(!(x=1))a.b=1}");
}
public void testAndParenthesesCount() {
foldSame("function(){if(x||y)a.foo()}");
}
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",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("a=~-0x100000000", "a=~-0x100000000",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("a=~.5", "~.5", FoldConstants.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");
fold("if(x && true) z()", "x&&z()");
fold("if(x && false) z()", "");
fold("if(x || 3) z()", "z()");
fold("if(x || false) z()", "x&&z()");
fold("if(x==y && false) z()", "");
// This would be foldable, but it isn't detected, because 'if' isn't
// the parent of 'x || 3'. Cf. FoldConstants.tryFoldAndOr().
fold("if(y() || x || 3) z()", "if(y()||x||1)z()");
// 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");
// TODO(user): fold("foo()&&false&&z()", "foo()");
fold("if(foo() || true) z()", "if(foo()||1)z()");
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().
fold("x = foo() && true || bar()", "x = foo()&&true||bar()");
fold("foo() && true || bar()", "foo()&&1||bar()");
}
public void testFoldLogicalOpStringCompare() {
// side-effects
// There is two way to parse two &&'s and both are correct.
assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
}
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");
assertResultString("-1 | 0", "1");
}
public void testFoldBitShifts() {
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 >> 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 = " + 0x7fffffff);
fold("3000000000 << 1", "3000000000<<1",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("1 << 32", "1<<32",
FoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("1 << -1", "1<<32",
FoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("3000000000 >> 1", "3000000000>>1",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("1 >> 32", "1>>32",
FoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("1.5 << 0", "1.5<<0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 << .5", "1.5<<0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1.5 >>> 0", "1.5>>>0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 >>> .5", "1.5>>>0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1.5 >> 0", "1.5>>0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 >> .5", "1.5>>0", FoldConstants.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", "", FoldConstants.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", "1");
fold("1 == 2", "0");
fold("'abc' == 'def'", "0");
fold("'abc' == 'abc'", "1");
fold("\"\" == ''", "1");
fold("foo() == bar()", "foo()==bar()");
fold("1 != 0", "1");
fold("'abc' != 'def'", "1");
fold("'a' != 'a'", "0");
fold("1 < 20", "1");
fold("3 < 3", "0");
fold("10 > 1.0", "1");
fold("10 > 10.25", "0");
fold("x == x", "x==x");
fold("x < x", "0");
fold("x > x", "0");
fold("1 <= 1", "1");
fold("1 <= 0", "0");
fold("0 >= 0", "1");
fold("-1 >= 9", "0");
fold("true == true", "1");
fold("true == true", "1");
fold("false == null", "0");
fold("false == true", "0");
fold("true == null", "0");
}
public void testFoldNot() {
fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
// Because !(x<NaN) != x>=NaN don't fold < and > cases.
foldSame("while(!(x>y)){a=b;}");
foldSame("while(!(x>=y)){a=b;}");
foldSame("while(!(x<y)){a=b;}");
foldSame("while(!(x<=y)){a=b;}");
foldSame("while(!(x<=NaN)){a=b;}");
}
public void testFoldGetElem() {
fold("x = [10, 20][0]", "x = 10");
fold("x = [10, 20][1]", "x = 20");
fold("x = [10, 20][0.5]", "", FoldConstants.INVALID_GETELEM_INDEX_ERROR);
fold("x = [10, 20][-1]", "", FoldConstants.INDEX_OUT_OF_BOUNDS_ERROR);
fold("x = [10, 20][2]", "", FoldConstants.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 testFoldRegExpConstructor() {
// Cannot fold
// Too few arguments
fold("x = new RegExp", "x = new RegExp");
// Empty regexp should not fold to // since that is a line comment in js
fold("x = new RegExp(\"\")", "x = new RegExp(\"\")");
fold("x = new RegExp(\"\", \"i\")", "x = new RegExp(\"\",\"i\")");
// Bogus flags should not fold
fold("x = new RegExp(\"foobar\", \"bogus\")",
"x = new RegExp(\"foobar\",\"bogus\")",
FoldConstants.INVALID_REGULAR_EXPRESSION_FLAGS);
// Don't fold if the flags contain 'g'
fold("x = new RegExp(\"foobar\", \"g\")",
"x = new RegExp(\"foobar\",\"g\")");
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = new RegExp(\"foobar\",\"ig\")");
// Can Fold
fold("x = new RegExp(\"foobar\")", "x = /foobar/");
fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
// Make sure that escaping works
fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
// Don't fold things that crash older versions of Safari and that don't work
// as regex literals on recent versions of Safari
fold("x = new RegExp(\"\\u2028\")", "x = new RegExp(\"\\u2028\")");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
// Don't fold really long regexp literals, because Opera 9.2's
// regexp parser will explode.
String longRegexp = "";
for (int i = 0; i < 200; i++) longRegexp += "x";
foldSame("x = new RegExp(\"" + longRegexp + "\")");
}
public void testFoldRegExpConstructorStringCompare() {
// Might have something to do with the internal representation of \n and how
// it is used in node comparison.
assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i");
}
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 []", "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 testFoldLiteralConstructors() {
// Can fold
fold("x = new Array", "x = []");
fold("x = new Array()", "x = []");
fold("x = new Object", "x = ({})");
fold("x = new Object()", "x = ({})");
// Cannot fold, there are arguments
fold("x = new Array(7)", "x = new Array(7)");
// Cannot fold, the constructor being used is actually a local function
fold("x = " +
"(function(){function Object(){this.x=4};return new Object();})();",
"x = (function(){function Object(){this.x=4}return new Object})()");
}
public void testVarLifting() {
fold("if(true)var a", "var a");
fold("if(false)var a", "var a");
fold("if(true);else var a;", "var a");
fold("if(false) foo();else var a;", "var a");
fold("if(true)var a;else;", "var a");
fold("if(false)var a;else;", "var a");
fold("if(false)var a,b;", "var b; var a");
fold("if(false){var a;var a;}", "var a");
fold("if(false)var a=function(){var b};", "var a");
fold("if(a)if(false)var a;else var b;", "var a;if(a)var b");
}
public void testContainsUnicodeEscape() throws Exception {
assertTrue(!FoldConstants.containsUnicodeEscape(""));
assertTrue(!FoldConstants.containsUnicodeEscape("foo"));
assertTrue( FoldConstants.containsUnicodeEscape("\u2028"));
assertTrue( FoldConstants.containsUnicodeEscape("\\u2028"));
assertTrue( FoldConstants.containsUnicodeEscape("foo\\u2028"));
assertTrue(!FoldConstants.containsUnicodeEscape("foo\\\\u2028"));
assertTrue( FoldConstants.containsUnicodeEscape("foo\\\\u2028bar\\u2028"));
}
public void testBug1438784() throws Exception {
fold("for(var i=0;i<10;i++)if(x)x.y;", "for(var i=0;i<10;i++);");
}
public void testFoldUselessWhile() {
fold("while(false) { foo() }", "");
fold("while(!true) { foo() }", "");
fold("while(void 0) { foo() }", "");
fold("while(undefined) { foo() }", "");
fold("while(!false) foo() ", "while(1) foo()");
fold("while(true) foo() ", "while(1) foo() ");
fold("while(!void 0) foo()", "while(1) foo()");
fold("while(false) { var a = 0; }", "var a");
// Make sure it plays nice with minimizing
fold("while(false) { foo(); continue }", "");
// Make sure proper empty nodes are inserted.
fold("if(foo())while(false){foo()}else bar()", "foo()||bar()");
}
public void testFoldUselessFor() {
fold("for(;false;) { foo() }", "");
fold("for(;!true;) { foo() }", "");
fold("for(;void 0;) { foo() }", "");
fold("for(;undefined;) { foo() }", "");
fold("for(;!false;) foo() ", "for(;;) foo()");
fold("for(;true;) foo() ", "for(;;) foo() ");
fold("for(;1;) foo()", "for(;;) foo()");
foldSame("for(;;) foo()");
fold("for(;!void 0;) foo()", "for(;;) foo()");
fold("for(;false;) { var a = 0; }", "var a");
// Make sure it plays nice with minimizing
fold("for(;false;) { foo(); continue }", "");
// Make sure proper empty nodes are inserted.
fold("if(foo())for(;false;){foo()}else bar()", "foo()||bar()");
}
public void testFoldUselessDo() {
fold("do { foo() } while(false);", "foo()");
fold("do { foo() } while(!true);", "foo()");
fold("do { foo() } while(void 0);", "foo()");
fold("do { foo() } while(undefined);", "foo()");
fold("do { foo() } while(!false);", "do { foo() } while(1);");
fold("do { foo() } while(true);", "do { foo() } while(1);");
fold("do { foo() } while(!void 0);", "do { foo() } while(1);");
fold("do { var a = 0; } while(false);", "var a=0");
// Can't fold with break or continues.
foldSame("do { foo(); continue; } while(0)");
foldSame("do { foo(); break; } while(0)");
// Make sure proper empty nodes are inserted.
fold("if(foo())do {foo()} while(false) else bar()", "foo()?foo():bar()");
}
public void testMinimizeCondition() {
// This test uses constant folding logic, so is only here for completeness.
fold("while(!!true) foo()", "while(1) foo()");
// These test tryMinimizeCondition
fold("while(!!x) foo()", "while(x) foo()");
fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
fold("while(x||!!y) foo()", "while(x||y) foo()");
fold("while(!(!!x&&y)) foo()", "while(!(x&&y)) foo()");
}
public void testMinimizeCondition_example1() {
// Based on a real failing code sample.
fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
}
public void testMinimizeWhileConstantCondition() {
fold("while(true) foo()", "while(1) foo()");
fold("while(!false) foo()", "while(1) foo()");
fold("while(202) foo()", "while(1) foo()");
fold("while(Infinity) foo()", "while(1) foo()");
fold("while('text') foo()", "while(1) foo()");
fold("while([]) foo()", "while(1) foo()");
fold("while({}) foo()", "while(1) foo()");
fold("while(/./) foo()", "while(1) foo()");
fold("while(0) foo()", "");
fold("while(0.0) foo()", "");
fold("while(NaN) foo()", "");
fold("while(null) foo()", "");
fold("while(undefined) foo()", "");
fold("while('') foo()", "");
}
public void testMinimizeExpr() {
fold("!!true", "0");
fold("!!x", "x");
fold("!(!x&&!y)", "!x&&!y");
fold("x||!!y", "x||y");
fold("!(!!x&&y)", "x&&y");
}
public void testBug1509085() {
new FoldConstantsTest() {
@Override
protected int getNumRepetitions() {
return 1;
}
}.fold("x ? x() : void 0", "if(x) x();");
}
public void testFoldInstanceOf() {
// Non object types are never instances of anything.
fold("64 instanceof Object", "0");
fold("64 instanceof Number", "0");
fold("'' instanceof Object", "0");
fold("'' instanceof String", "0");
fold("true instanceof Object", "0");
fold("true instanceof Boolean", "0");
fold("false instanceof Object", "0");
fold("null instanceof Object", "0");
fold("undefined instanceof Object", "0");
fold("NaN instanceof Object", "0");
fold("Infinity instanceof Object", "0");
// Array and object literals are known to be objects.
fold("[] instanceof Object", "1");
fold("({}) instanceof Object", "1");
// 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");
}
public void testFoldConditionalVarDeclaration() {
fold("if(x) var y=1;else y=2", "var y=x?1:2");
fold("if(x) y=1;else var y=2", "var y=x?1:2");
foldSame("if(x) var y = 1; z = 2");
foldSame("if(x) y = 1; var z = 2");
foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
foldSame("if(x) var y = 1; else {y = 2; print(y)}");
}
public void testFoldReturnResult() {
foldSame("function f(){return false;}");
foldSame("function f(){return null;}");
fold("function f(){return void 0;}",
"function f(){return}");
foldSame("function f(){return void foo();}");
fold("function f(){return undefined;}",
"function f(){return}");
fold("function(){if(a()){return undefined;}}",
"function(){if(a()){return}}");
}
public void testBugIssue3() {
foldSame("function foo() {" +
" if(sections.length != 1) children[i] = 0;" +
" else var selectedid = children[i]" +
"}");
}
public void testBugIssue43() {
foldSame("function foo() {" +
" if (a) { var b = 1; } else { a.b = 1; }" +
"}");
}
} | // You are a professional Java test case writer, please create a test case named `testStringJoinAdd` for the issue `Closure-106`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-106
//
// ## Issue-Title:
// Array Join Munged Incorrectly
//
// ## Issue-Description:
// $.fn.hasClass = function(selector) {
// return ( this.length > 0 ?
// !( ( ['', this[0].className, ''].join(' ') ).indexOf( ['', selector,
// ''].join(' ') ) == -1 )
// : false );
// };
//
// munges into
//
// $.fn.hasClass=function(a){return this.length>0?
// (""+this[0].className).indexOf(""+a)!=-1:false};
//
// which is not identical. Looks like there might be an issue with join and ' '.
//
//
public void testStringJoinAdd() {
| 657 | 105 | 622 | test/com/google/javascript/jscomp/FoldConstantsTest.java | test | ```markdown
## Issue-ID: Closure-106
## Issue-Title:
Array Join Munged Incorrectly
## Issue-Description:
$.fn.hasClass = function(selector) {
return ( this.length > 0 ?
!( ( ['', this[0].className, ''].join(' ') ).indexOf( ['', selector,
''].join(' ') ) == -1 )
: false );
};
munges into
$.fn.hasClass=function(a){return this.length>0?
(""+this[0].className).indexOf(""+a)!=-1:false};
which is not identical. Looks like there might be an issue with join and ' '.
```
You are a professional Java test case writer, please create a test case named `testStringJoinAdd` for the issue `Closure-106`, utilizing the provided issue report information and the following function signature.
```java
public void testStringJoinAdd() {
```
| 622 | [
"com.google.javascript.jscomp.FoldConstants"
] | 377ff6ff7fdede670d67d34842cf6055a6a03d0edb57a0b94e31340f9a332b36 | public void testStringJoinAdd() | // You are a professional Java test case writer, please create a test case named `testStringJoinAdd` for the issue `Closure-106`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-106
//
// ## Issue-Title:
// Array Join Munged Incorrectly
//
// ## Issue-Description:
// $.fn.hasClass = function(selector) {
// return ( this.length > 0 ?
// !( ( ['', this[0].className, ''].join(' ') ).indexOf( ['', selector,
// ''].join(' ') ) == -1 )
// : false );
// };
//
// munges into
//
// $.fn.hasClass=function(a){return this.length>0?
// (""+this[0].className).indexOf(""+a)!=-1:false};
//
// which is not identical. Looks like there might be an issue with join and ' '.
//
//
| 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;
import com.google.javascript.rhino.Node;
public class FoldConstantsTest extends CompilerTestCase {
// TODO(user): Remove this when we no longer need to do string comparison.
private FoldConstantsTest(boolean compareAsTree) {
super("", compareAsTree);
}
public FoldConstantsTest() {
super();
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
return new CompilerPass() {
public void process(Node externs, Node js) {
NodeTraversal.traverse(compiler, js, new FoldConstants(compiler));
}
};
}
@Override
protected int getNumRepetitions() {
// Reduce this to 2 if we get better expression evaluators.
return 2;
}
void foldSame(String js) {
testSame(js);
}
void fold(String js, String expected) {
test(js, expected);
}
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.
void assertResultString(String js, String expected) {
FoldConstantsTest scTest = new FoldConstantsTest(false);
scTest.test(js, expected);
}
public void testFoldBlock() {
fold("{{foo()}}", "foo()");
fold("{foo();{}}", "foo()");
fold("{{foo()}{}}", "foo()");
fold("{{foo()}{bar()}}", "foo();bar()");
fold("{if(false)foo(); {bar()}}", "bar()");
fold("{if(false)if(false)if(false)foo(); {bar()}}", "bar()");
fold("{'hi'}", "");
fold("{x==3}", "");
fold("{ (function(){x++}) }", "");
fold("function(){return;}", "function(){return;}");
fold("function(){return 3;}", "function(){return 3}");
fold("function(){if(x)return; x=3; return; }",
"function(){if(x)return; x=3; return; }");
fold("{x=3;;;y=2;;;}", "x=3;y=2");
// Cases to test for empty block.
fold("while(x()){x}", "while(x());");
fold("while(x()){x()}", "while(x())x()");
fold("for(x=0;x<100;x++){x}", "for(x=0;x<100;x++);");
fold("for(x in y){x}", "for(x in y);");
}
/** Check that removing blocks with 1 child works */
public void testFoldOneChildBlocks() {
fold("function(){if(x)a();x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){a()}x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){return 3}}",
"function(){if(x)return 3}");
fold("function(){if(x){a()}}",
"function(){x&&a()}");
fold("function(){if(x){throw 1}}", "function(){if(x)throw 1;}");
// Try it out with functions
fold("function(){if(x){foo()}}", "function(){x&&foo()}");
fold("function(){if(x){foo()}else{bar()}}",
"function(){x?foo():bar()}");
// Try it out with properties and methods
fold("function(){if(x){a.b=1}}", "function(){if(x)a.b=1}");
fold("function(){if(x){a.b*=1}}", "function(){if(x)a.b*=1}");
fold("function(){if(x){a.b+=1}}", "function(){if(x)a.b+=1}");
fold("function(){if(x){++a.b}}", "function(){x&&++a.b}");
fold("function(){if(x){a.foo()}}", "function(){x&&a.foo()}");
// Try it out with throw/catch/finally [which should not change]
fold("function(){try{foo()}catch(e){bar(e)}finally{baz()}}",
"function(){try{foo()}catch(e){bar(e)}finally{baz()}}");
// Try it out with switch statements
fold("function(){switch(x){case 1:break}}",
"function(){switch(x){case 1:break}}");
fold("function(){switch(x){default:{break}}}",
"function(){switch(x){default:break}}");
fold("function(){switch(x){default:{break}}}",
"function(){switch(x){default:break}}");
fold("function(){switch(x){default:x;case 1:return 2}}",
"function(){switch(x){default:case 1:return 2}}");
// Do while loops stay in a block if that's where they started
fold("function(){if(e1){do foo();while(e2)}else foo2()}",
"function(){if(e1){do foo();while(e2)}else foo2()}");
// Test an obscure case with do and while
fold("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
// Play with nested IFs
fold("function(){if(x){if(y)foo()}}",
"function(){x&&y&&foo()}");
fold("function(){if(x){if(y)foo();else bar()}}",
"function(){if(x)y?foo():bar()}");
fold("function(){if(x){if(y)foo()}else bar()}",
"function(){if(x)y&&foo();else bar()}");
fold("function(){if(x){if(y)foo();else bar()}else{baz()}}",
"function(){if(x)y?foo():bar();else baz()}");
fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
"if(e1)while(e2)e3&&foo();else bar()");
fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
"if(e1)with(e2)e3&&foo();else bar()");
fold("if(x){if(y){var x;}}", "if(x)if(y)var x");
fold("if(x){ if(y){var x;}else{var z;} }",
"if(x)if(y)var x;else var z");
// NOTE - technically we can remove the blocks since both the parent
// and child have elses. But we don't since it causes ambiguities in
// some cases where not all descendent ifs having elses
fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
"if(x)if(y)var x;else var z;else var w");
fold("if (x) {var x;}else { if (y) { var y;} }",
"if(x)var x;else if(y)var y");
// Here's some of the ambiguous cases
fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
"if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
fold("function(){foo()}", "function(){foo()}");
fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
fold("try{foo()}catch(ex){bar()}finally{baz()}",
"try{foo()}catch(ex){bar()}finally{baz()}");
// ensure that block folding does not break hook ifs
fold("if(x){if(true){foo();foo()}else{bar();bar()}}",
"if(x){foo();foo()}");
fold("if(x){if(false){foo();foo()}else{bar();bar()}}",
"if(x){bar();bar()}");
// Cases where the then clause has no side effects.
fold("if(x()){}", "x()");
fold("if(x()){} else {x()}", "x()||x()");
fold("if(x){}", ""); // Even the condition has no side effect.
fold("if(a()){A()} else if (b()) {} else {C()}",
"if(a())A();else b()||C()");
fold("if(a()){} else if (b()) {} else {C()}",
"a()||b()||C()");
fold("if(a()){A()} else if (b()) {} else if (c()) {} else{D()}",
"if(a())A();else b()||c()||D()");
fold("if(a()){} else if (b()) {} else if (c()) {} else{D()}",
"a()||b()||c()||D()");
fold("if(a()){A()} else if (b()) {} else if (c()) {} else{}",
"if(a())A();else b()||c()");
// Verify that non-global scope works.
fold("function foo(){if(x()){}}", "function foo(){x()}");
}
public void testFoldOneChildBlocksStringCompare() {
// The expected parse tree has a BLOCK structure around the true branch.
assertResultString("if(x){if(y){var x;}}else{var z;}",
"if(x){if(y)var x}else var z");
}
/** Test a particularly hairy edge case. */
public void testNecessaryDanglingElse() {
// The extra block is added by CodeGenerator. The logic to avoid ambiguous
// else clauses used to be in FoldConstants, so the test is here for
// legacy reasons.
assertResultString(
"if(x)if(y){y();z()}else;else x()", "if(x){if(y){y();z()}}else x()");
}
/** Try to remove spurious blocks with multiple children */
public void testFoldBlocksWithManyChildren() {
fold("function f() { if (false) {} }", "function f(){}");
fold("function f() { { if (false) {} if (true) {} {} } }",
"function f(){}");
fold("{var x; var y; var z; function f() { { var a; { var b; } } } }",
"var x;var y;var z;function f(){var a;var b}");
}
/** Try to minimize returns */
public void testFoldReturns() {
fold("function(){if(x)return 1;else return 2}",
"function(){return x?1:2}");
fold("function(){if(x)return 1+x;else return 2-x}",
"function(){return x?1+x:2-x}");
fold("function(){if(x)return y += 1;else return y += 2}",
"function(){return x?(y+=1):(y+=2)}");
// don't touch cases where either side doesn't return a value
foldSame("function(){if(x)return;else return 2-x}");
foldSame("function(){if(x)return x;else return}");
// if-then-else duplicate statement removal handles this case:
fold("function(){if(x)return;else return}",
"function(){return}");
}
/** Try to minimize assignments */
public void testFoldAssignments() {
fold("function(){if(x)y=3;else y=4;}", "function(){y=x?3:4}");
fold("function(){if(x)y=1+a;else y=2+a;}", "function(){y=x?1+a:2+a}");
// and operation assignments
fold("function(){if(x)y+=1;else y+=2;}", "function(){y+=x?1:2}");
fold("function(){if(x)y-=1;else y-=2;}", "function(){y-=x?1:2}");
fold("function(){if(x)y%=1;else y%=2;}", "function(){y%=x?1:2}");
fold("function(){if(x)y|=1;else y|=2;}", "function(){y|=x?1:2}");
// sanity check, don't fold if the 2 ops don't match
foldSame("function(){if(x)y-=1;else y+=2}");
// sanity check, don't fold if the 2 LHS don't match
foldSame("function(){if(x)y-=1;else z-=1}");
// sanity check, don't fold if there are potential effects
foldSame("function(){if(x)y().a=3;else y().a=4}");
}
public void testBug1059649() {
// ensure that folding blocks with a single var node doesn't explode
fold("if(x){var y=3;}var z=5", "if(x)var y=3;var z=5");
// With normalization, we no longer have this case.
foldSame("if(x){var y=3;}else{var y=4;}var z=5");
fold("while(x){var y=3;}var z=5", "while(x)var y=3;var z=5");
fold("for(var i=0;i<10;i++){var y=3;}var z=5",
"for(var i=0;i<10;i++)var y=3;var z=5");
fold("for(var i in x){var y=3;}var z=5",
"for(var i in x)var y=3;var z=5");
fold("do{var y=3;}while(x);var z=5", "do var y=3;while(x);var z=5");
}
public void testUndefinedComparison() {
fold("if (0 == 0){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined == undefined){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined == null){ x = 1; } else { x = 2; }", "x=1");
// fold("if (undefined == NaN){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == 0){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == 1){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == 'hi'){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == true){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined == false){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined === undefined){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined === null){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined === void 0){ x = 1; } else { x = 2; }", "x=1");
// foldSame("if (undefined === void foo()){ x = 1; } else { x = 2; }");
foldSame("x = (undefined == this) ? 1 : 2;");
foldSame("x = (undefined == x) ? 1 : 2;");
fold("if (undefined != undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined != null){ x = 1; } else { x = 2; }", "x=2");
// fold("if (undefined != NaN){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != 0){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != 1){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != 'hi'){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != true){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined != false){ x = 1; } else { x = 2; }", "x=1");
fold("if (undefined !== undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined !== null){ x = 1; } else { x = 2; }", "x=1");
foldSame("x = (undefined != this) ? 1 : 2;");
foldSame("x = (undefined != x) ? 1 : 2;");
fold("if (undefined < undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined > undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined >= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined <= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (0 < undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (true > undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if ('hi' >= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (null <= undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined < 0){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined > true){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined >= 'hi'){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined <= null){ x = 1; } else { x = 2; }", "x=2");
fold("if (null == undefined){ x = 1; } else { x = 2; }", "x=1");
// fold("if (NaN == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (0 == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (1 == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if ('hi' == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (true == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (false == undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (null === undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (void 0 === undefined){ x = 1; } else { x = 2; }", "x=1");
// foldSame("if (void foo() === undefined){ x = 1; } else { x = 2; }");
foldSame("x = (this == undefined) ? 1 : 2;");
foldSame("x = (x == undefined) ? 1 : 2;");
}
public void testHookIf() {
fold("if (1){ x=1; } else { x = 2;}", "x=1");
fold("if (false){ x = 1; } else { x = 2; }", "x=2");
fold("if (undefined){ x = 1; } else { x = 2; }", "x=2");
fold("if (null){ x = 1; } else { x = 2; }", "x=2");
fold("if (void 0){ x = 1; } else { x = 2; }", "x=2");
// foldSame("if (void foo()){ x = 1; } else { x = 2; }");
fold("if (false){ x = 1; } else if (true) { x = 3; } else { x = 2; }",
"x=3");
fold("if (false){ x = 1; } else if (cond) { x = 2; } else { x = 3; }",
"x=cond?2:3");
fold("var x = (true) ? 1 : 0", "var x=1");
fold("var y = (true) ? ((false) ? 12 : (cond ? 1 : 2)) : 13",
"var y=cond?1:2");
fold("if (x){ x = 1; } else if (false) { x = 3; }", "if(x)x=1");
fold("x?void 0:y()", "x||y()");
fold("!x?void 0:y()", "x&&y()");
foldSame("var z=x?void 0:y()");
foldSame("z=x?void 0:y()");
foldSame("z*=x?void 0:y()");
fold("x?y():void 0", "x&&y()");
foldSame("var z=x?y():void 0");
foldSame("(w?x:void 0).y=z");
foldSame("(w?x:void 0).y+=z");
}
public void testRemoveDuplicateStatements() {
fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
"x=(a) ? 1 : 2; x++");
fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
" else { x = 2; x++; y += 1; z = pi; }",
"x=(a) ? 1 : 2; x++; y += 1; z = pi;");
fold("function z() {" +
"if (a) { foo(); return true } else { goo(); return true }" +
"}",
"function z() {(a) ? foo() : goo(); return true}");
fold("function z() {if (a) { foo(); x = true; return true " +
"} else { goo(); x = true; return true }}",
"function z() {(a) ? foo() : goo(); x = true; return true}");
fold("function z() {if (a) { return true }" +
"else if (b) { return true }" +
"else { return true }}",
"function z() {return true;}");
fold("function z() {if (a()) { return true }" +
"else if (b()) { return true }" +
"else { return true }}",
"function z() {if (!a()) { b() } return true;}");
fold("function z() {" +
" if (a) { bar(); foo(); return true }" +
" else { bar(); goo(); return true }" +
"}",
"function z() {" +
" if (a) { bar(); foo(); }" +
" else { bar(); goo(); }" +
" return true;" +
"}");
}
public void testNotCond() {
fold("function(){if(!x)foo()}", "function(){x||foo()}");
fold("function(){if(!x)b=1}", "function(){x||(b=1)}");
fold("if(!x)z=1;else if(y)z=2", "if(x){if(y)z=2}else z=1");
foldSame("function(){if(!(x=1))a.b=1}");
}
public void testAndParenthesesCount() {
foldSame("function(){if(x||y)a.foo()}");
}
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",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("a=~-0x100000000", "a=~-0x100000000",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("a=~.5", "~.5", FoldConstants.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");
fold("if(x && true) z()", "x&&z()");
fold("if(x && false) z()", "");
fold("if(x || 3) z()", "z()");
fold("if(x || false) z()", "x&&z()");
fold("if(x==y && false) z()", "");
// This would be foldable, but it isn't detected, because 'if' isn't
// the parent of 'x || 3'. Cf. FoldConstants.tryFoldAndOr().
fold("if(y() || x || 3) z()", "if(y()||x||1)z()");
// 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");
// TODO(user): fold("foo()&&false&&z()", "foo()");
fold("if(foo() || true) z()", "if(foo()||1)z()");
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().
fold("x = foo() && true || bar()", "x = foo()&&true||bar()");
fold("foo() && true || bar()", "foo()&&1||bar()");
}
public void testFoldLogicalOpStringCompare() {
// side-effects
// There is two way to parse two &&'s and both are correct.
assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
}
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");
assertResultString("-1 | 0", "1");
}
public void testFoldBitShifts() {
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 >> 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 = " + 0x7fffffff);
fold("3000000000 << 1", "3000000000<<1",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("1 << 32", "1<<32",
FoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("1 << -1", "1<<32",
FoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("3000000000 >> 1", "3000000000>>1",
FoldConstants.BITWISE_OPERAND_OUT_OF_RANGE);
fold("1 >> 32", "1>>32",
FoldConstants.SHIFT_AMOUNT_OUT_OF_BOUNDS);
fold("1.5 << 0", "1.5<<0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 << .5", "1.5<<0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1.5 >>> 0", "1.5>>>0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 >>> .5", "1.5>>>0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1.5 >> 0", "1.5>>0", FoldConstants.FRACTIONAL_BITWISE_OPERAND);
fold("1 >> .5", "1.5>>0", FoldConstants.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", "", FoldConstants.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", "1");
fold("1 == 2", "0");
fold("'abc' == 'def'", "0");
fold("'abc' == 'abc'", "1");
fold("\"\" == ''", "1");
fold("foo() == bar()", "foo()==bar()");
fold("1 != 0", "1");
fold("'abc' != 'def'", "1");
fold("'a' != 'a'", "0");
fold("1 < 20", "1");
fold("3 < 3", "0");
fold("10 > 1.0", "1");
fold("10 > 10.25", "0");
fold("x == x", "x==x");
fold("x < x", "0");
fold("x > x", "0");
fold("1 <= 1", "1");
fold("1 <= 0", "0");
fold("0 >= 0", "1");
fold("-1 >= 9", "0");
fold("true == true", "1");
fold("true == true", "1");
fold("false == null", "0");
fold("false == true", "0");
fold("true == null", "0");
}
public void testFoldNot() {
fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
// Because !(x<NaN) != x>=NaN don't fold < and > cases.
foldSame("while(!(x>y)){a=b;}");
foldSame("while(!(x>=y)){a=b;}");
foldSame("while(!(x<y)){a=b;}");
foldSame("while(!(x<=y)){a=b;}");
foldSame("while(!(x<=NaN)){a=b;}");
}
public void testFoldGetElem() {
fold("x = [10, 20][0]", "x = 10");
fold("x = [10, 20][1]", "x = 20");
fold("x = [10, 20][0.5]", "", FoldConstants.INVALID_GETELEM_INDEX_ERROR);
fold("x = [10, 20][-1]", "", FoldConstants.INDEX_OUT_OF_BOUNDS_ERROR);
fold("x = [10, 20][2]", "", FoldConstants.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 testFoldRegExpConstructor() {
// Cannot fold
// Too few arguments
fold("x = new RegExp", "x = new RegExp");
// Empty regexp should not fold to // since that is a line comment in js
fold("x = new RegExp(\"\")", "x = new RegExp(\"\")");
fold("x = new RegExp(\"\", \"i\")", "x = new RegExp(\"\",\"i\")");
// Bogus flags should not fold
fold("x = new RegExp(\"foobar\", \"bogus\")",
"x = new RegExp(\"foobar\",\"bogus\")",
FoldConstants.INVALID_REGULAR_EXPRESSION_FLAGS);
// Don't fold if the flags contain 'g'
fold("x = new RegExp(\"foobar\", \"g\")",
"x = new RegExp(\"foobar\",\"g\")");
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = new RegExp(\"foobar\",\"ig\")");
// Can Fold
fold("x = new RegExp(\"foobar\")", "x = /foobar/");
fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
// Make sure that escaping works
fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
// Don't fold things that crash older versions of Safari and that don't work
// as regex literals on recent versions of Safari
fold("x = new RegExp(\"\\u2028\")", "x = new RegExp(\"\\u2028\")");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
// Don't fold really long regexp literals, because Opera 9.2's
// regexp parser will explode.
String longRegexp = "";
for (int i = 0; i < 200; i++) longRegexp += "x";
foldSame("x = new RegExp(\"" + longRegexp + "\")");
}
public void testFoldRegExpConstructorStringCompare() {
// Might have something to do with the internal representation of \n and how
// it is used in node comparison.
assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i");
}
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 []", "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 testFoldLiteralConstructors() {
// Can fold
fold("x = new Array", "x = []");
fold("x = new Array()", "x = []");
fold("x = new Object", "x = ({})");
fold("x = new Object()", "x = ({})");
// Cannot fold, there are arguments
fold("x = new Array(7)", "x = new Array(7)");
// Cannot fold, the constructor being used is actually a local function
fold("x = " +
"(function(){function Object(){this.x=4};return new Object();})();",
"x = (function(){function Object(){this.x=4}return new Object})()");
}
public void testVarLifting() {
fold("if(true)var a", "var a");
fold("if(false)var a", "var a");
fold("if(true);else var a;", "var a");
fold("if(false) foo();else var a;", "var a");
fold("if(true)var a;else;", "var a");
fold("if(false)var a;else;", "var a");
fold("if(false)var a,b;", "var b; var a");
fold("if(false){var a;var a;}", "var a");
fold("if(false)var a=function(){var b};", "var a");
fold("if(a)if(false)var a;else var b;", "var a;if(a)var b");
}
public void testContainsUnicodeEscape() throws Exception {
assertTrue(!FoldConstants.containsUnicodeEscape(""));
assertTrue(!FoldConstants.containsUnicodeEscape("foo"));
assertTrue( FoldConstants.containsUnicodeEscape("\u2028"));
assertTrue( FoldConstants.containsUnicodeEscape("\\u2028"));
assertTrue( FoldConstants.containsUnicodeEscape("foo\\u2028"));
assertTrue(!FoldConstants.containsUnicodeEscape("foo\\\\u2028"));
assertTrue( FoldConstants.containsUnicodeEscape("foo\\\\u2028bar\\u2028"));
}
public void testBug1438784() throws Exception {
fold("for(var i=0;i<10;i++)if(x)x.y;", "for(var i=0;i<10;i++);");
}
public void testFoldUselessWhile() {
fold("while(false) { foo() }", "");
fold("while(!true) { foo() }", "");
fold("while(void 0) { foo() }", "");
fold("while(undefined) { foo() }", "");
fold("while(!false) foo() ", "while(1) foo()");
fold("while(true) foo() ", "while(1) foo() ");
fold("while(!void 0) foo()", "while(1) foo()");
fold("while(false) { var a = 0; }", "var a");
// Make sure it plays nice with minimizing
fold("while(false) { foo(); continue }", "");
// Make sure proper empty nodes are inserted.
fold("if(foo())while(false){foo()}else bar()", "foo()||bar()");
}
public void testFoldUselessFor() {
fold("for(;false;) { foo() }", "");
fold("for(;!true;) { foo() }", "");
fold("for(;void 0;) { foo() }", "");
fold("for(;undefined;) { foo() }", "");
fold("for(;!false;) foo() ", "for(;;) foo()");
fold("for(;true;) foo() ", "for(;;) foo() ");
fold("for(;1;) foo()", "for(;;) foo()");
foldSame("for(;;) foo()");
fold("for(;!void 0;) foo()", "for(;;) foo()");
fold("for(;false;) { var a = 0; }", "var a");
// Make sure it plays nice with minimizing
fold("for(;false;) { foo(); continue }", "");
// Make sure proper empty nodes are inserted.
fold("if(foo())for(;false;){foo()}else bar()", "foo()||bar()");
}
public void testFoldUselessDo() {
fold("do { foo() } while(false);", "foo()");
fold("do { foo() } while(!true);", "foo()");
fold("do { foo() } while(void 0);", "foo()");
fold("do { foo() } while(undefined);", "foo()");
fold("do { foo() } while(!false);", "do { foo() } while(1);");
fold("do { foo() } while(true);", "do { foo() } while(1);");
fold("do { foo() } while(!void 0);", "do { foo() } while(1);");
fold("do { var a = 0; } while(false);", "var a=0");
// Can't fold with break or continues.
foldSame("do { foo(); continue; } while(0)");
foldSame("do { foo(); break; } while(0)");
// Make sure proper empty nodes are inserted.
fold("if(foo())do {foo()} while(false) else bar()", "foo()?foo():bar()");
}
public void testMinimizeCondition() {
// This test uses constant folding logic, so is only here for completeness.
fold("while(!!true) foo()", "while(1) foo()");
// These test tryMinimizeCondition
fold("while(!!x) foo()", "while(x) foo()");
fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
fold("while(x||!!y) foo()", "while(x||y) foo()");
fold("while(!(!!x&&y)) foo()", "while(!(x&&y)) foo()");
}
public void testMinimizeCondition_example1() {
// Based on a real failing code sample.
fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
}
public void testMinimizeWhileConstantCondition() {
fold("while(true) foo()", "while(1) foo()");
fold("while(!false) foo()", "while(1) foo()");
fold("while(202) foo()", "while(1) foo()");
fold("while(Infinity) foo()", "while(1) foo()");
fold("while('text') foo()", "while(1) foo()");
fold("while([]) foo()", "while(1) foo()");
fold("while({}) foo()", "while(1) foo()");
fold("while(/./) foo()", "while(1) foo()");
fold("while(0) foo()", "");
fold("while(0.0) foo()", "");
fold("while(NaN) foo()", "");
fold("while(null) foo()", "");
fold("while(undefined) foo()", "");
fold("while('') foo()", "");
}
public void testMinimizeExpr() {
fold("!!true", "0");
fold("!!x", "x");
fold("!(!x&&!y)", "!x&&!y");
fold("x||!!y", "x||y");
fold("!(!!x&&y)", "x&&y");
}
public void testBug1509085() {
new FoldConstantsTest() {
@Override
protected int getNumRepetitions() {
return 1;
}
}.fold("x ? x() : void 0", "if(x) x();");
}
public void testFoldInstanceOf() {
// Non object types are never instances of anything.
fold("64 instanceof Object", "0");
fold("64 instanceof Number", "0");
fold("'' instanceof Object", "0");
fold("'' instanceof String", "0");
fold("true instanceof Object", "0");
fold("true instanceof Boolean", "0");
fold("false instanceof Object", "0");
fold("null instanceof Object", "0");
fold("undefined instanceof Object", "0");
fold("NaN instanceof Object", "0");
fold("Infinity instanceof Object", "0");
// Array and object literals are known to be objects.
fold("[] instanceof Object", "1");
fold("({}) instanceof Object", "1");
// 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");
}
public void testFoldConditionalVarDeclaration() {
fold("if(x) var y=1;else y=2", "var y=x?1:2");
fold("if(x) y=1;else var y=2", "var y=x?1:2");
foldSame("if(x) var y = 1; z = 2");
foldSame("if(x) y = 1; var z = 2");
foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
foldSame("if(x) var y = 1; else {y = 2; print(y)}");
}
public void testFoldReturnResult() {
foldSame("function f(){return false;}");
foldSame("function f(){return null;}");
fold("function f(){return void 0;}",
"function f(){return}");
foldSame("function f(){return void foo();}");
fold("function f(){return undefined;}",
"function f(){return}");
fold("function(){if(a()){return undefined;}}",
"function(){if(a()){return}}");
}
public void testBugIssue3() {
foldSame("function foo() {" +
" if(sections.length != 1) children[i] = 0;" +
" else var selectedid = children[i]" +
"}");
}
public void testBugIssue43() {
foldSame("function foo() {" +
" if (a) { var b = 1; } else { a.b = 1; }" +
"}");
}
} |
||
public void testRenderWrappedTextWordCut()
{
int width = 7;
int padding = 0;
String text = "Thisisatest.";
String expected = "Thisisa" + EOL +
"test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("cut and wrap", expected, sb.toString());
} | org.apache.commons.cli.HelpFormatterTest::testRenderWrappedTextWordCut | src/test/java/org/apache/commons/cli/HelpFormatterTest.java | 69 | src/test/java/org/apache/commons/cli/HelpFormatterTest.java | testRenderWrappedTextWordCut | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.cli;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Comparator;
import junit.framework.TestCase;
/**
* Test case for the HelpFormatter class
*
* @author Slawek Zachcial
* @author John Keyes ( john at integralsource.com )
* @author brianegge
*/
public class HelpFormatterTest extends TestCase
{
private static final String EOL = System.getProperty("line.separator");
public void testFindWrapPos() throws Exception
{
HelpFormatter hf = new HelpFormatter();
String text = "This is a test.";
// text width should be max 8; the wrap position is 7
assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0));
// starting from 8 must give -1 - the wrap pos is after end
assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8));
// words longer than the width are cut
text = "aaaa aa";
assertEquals("wrap position 3", 3, hf.findWrapPos(text, 3, 0));
// last word length is equal to the width
text = "aaaaaa aaaaaa";
assertEquals("wrap position 4", 6, hf.findWrapPos(text, 6, 0));
assertEquals("wrap position 4", -1, hf.findWrapPos(text, 6, 7));
}
public void testRenderWrappedTextWordCut()
{
int width = 7;
int padding = 0;
String text = "Thisisatest.";
String expected = "Thisisa" + EOL +
"test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("cut and wrap", expected, sb.toString());
}
public void testRenderWrappedTextSingleLine()
{
// single line text
int width = 12;
int padding = 0;
String text = "This is a test.";
String expected = "This is a" + EOL +
"test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("single line text", expected, sb.toString());
}
public void testRenderWrappedTextSingleLinePadded()
{
// single line padded text
int width = 12;
int padding = 4;
String text = "This is a test.";
String expected = "This is a" + EOL +
" test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("single line padded text", expected, sb.toString());
}
public void testRenderWrappedTextSingleLinePadded2()
{
// single line padded text 2
int width = 53;
int padding = 24;
String text = " -p,--period <PERIOD> PERIOD is time duration of form " +
"DATE[-DATE] where DATE has form YYYY[MM[DD]]";
String expected = " -p,--period <PERIOD> PERIOD is time duration of" + EOL +
" form DATE[-DATE] where DATE" + EOL +
" has form YYYY[MM[DD]]";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("single line padded text 2", expected, sb.toString());
}
public void testRenderWrappedTextMultiLine()
{
// multi line text
int width = 16;
int padding = 0;
String text = "aaaa aaaa aaaa" + EOL +
"aaaaaa" + EOL +
"aaaaa";
String expected = text;
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("multi line text", expected, sb.toString());
}
public void testRenderWrappedTextMultiLinePadded()
{
// multi-line padded text
int width = 16;
int padding = 4;
String text = "aaaa aaaa aaaa" + EOL +
"aaaaaa" + EOL +
"aaaaa";
String expected = "aaaa aaaa aaaa" + EOL +
" aaaaaa" + EOL +
" aaaaa";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("multi-line padded text", expected, sb.toString());
}
public void testPrintOptions() throws Exception
{
StringBuffer sb = new StringBuffer();
HelpFormatter hf = new HelpFormatter();
final int leftPad = 1;
final int descPad = 3;
final String lpad = hf.createPadding(leftPad);
final String dpad = hf.createPadding(descPad);
Options options = null;
String expected = null;
options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa";
hf.renderOptions(sb, 60, options, leftPad, descPad);
assertEquals("simple non-wrapped option", expected, sb.toString());
int nextLineTabStop = leftPad + descPad + "-a".length();
expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + EOL +
hf.createPadding(nextLineTabStop) + "aaaa aaaa";
sb.setLength(0);
hf.renderOptions(sb, nextLineTabStop + 17, options, leftPad, descPad);
assertEquals("simple wrapped option", expected, sb.toString());
options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd");
expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
sb.setLength(0);
hf.renderOptions(sb, 60, options, leftPad, descPad);
assertEquals("long non-wrapped option", expected, sb.toString());
nextLineTabStop = leftPad + descPad + "-a,--aaa".length();
expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL +
hf.createPadding(nextLineTabStop) + "dddd dddd";
sb.setLength(0);
hf.renderOptions(sb, 25, options, leftPad, descPad);
assertEquals("long wrapped option", expected, sb.toString());
options = new Options().
addOption("a", "aaa", false, "dddd dddd dddd dddd").
addOption("b", false, "feeee eeee eeee eeee");
expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL +
hf.createPadding(nextLineTabStop) + "dddd dddd" + EOL +
lpad + "-b " + dpad + "feeee eeee" + EOL +
hf.createPadding(nextLineTabStop) + "eeee eeee";
sb.setLength(0);
hf.renderOptions(sb, 25, options, leftPad, descPad);
assertEquals("multiple wrapped options", expected, sb.toString());
}
public void testPrintHelpWithEmptySyntax()
{
HelpFormatter formatter = new HelpFormatter();
try
{
formatter.printHelp(null, new Options());
fail("null command line syntax should be rejected");
}
catch (IllegalArgumentException e)
{
// expected
}
try
{
formatter.printHelp("", new Options());
fail("empty command line syntax should be rejected");
}
catch (IllegalArgumentException e)
{
// expected
}
}
public void testAutomaticUsage() throws Exception
{
HelpFormatter hf = new HelpFormatter();
Options options = null;
String expected = "usage: app [-a]";
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
hf.printUsage(pw, 60, "app", options);
pw.flush();
assertEquals("simple auto usage", expected, out.toString().trim());
out.reset();
expected = "usage: app [-a] [-b]";
options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa")
.addOption("b", false, "bbb");
hf.printUsage(pw, 60, "app", options);
pw.flush();
assertEquals("simple auto usage", expected, out.toString().trim());
out.reset();
}
// This test ensures the options are properly sorted
// See https://issues.apache.org/jira/browse/CLI-131
public void testPrintUsage()
{
Option optionA = new Option("a", "first");
Option optionB = new Option("b", "second");
Option optionC = new Option("c", "third");
Options opts = new Options();
opts.addOption(optionA);
opts.addOption(optionB);
opts.addOption(optionC);
HelpFormatter helpFormatter = new HelpFormatter();
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(bytesOut);
helpFormatter.printUsage(printWriter, 80, "app", opts);
printWriter.close();
assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString());
}
// uses the test for CLI-131 to implement CLI-155
public void testPrintSortedUsage()
{
Options opts = new Options();
opts.addOption(new Option("a", "first"));
opts.addOption(new Option("b", "second"));
opts.addOption(new Option("c", "third"));
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.setOptionComparator(new Comparator()
{
public int compare(Object o1, Object o2)
{
// reverses the fuctionality of the default comparator
Option opt1 = (Option) o1;
Option opt2 = (Option) o2;
return opt2.getKey().compareToIgnoreCase(opt1.getKey());
}
});
StringWriter out = new StringWriter();
helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString());
}
public void testPrintSortedUsageWithNullComparator()
{
Options opts = new Options();
opts.addOption(new Option("a", "first"));
opts.addOption(new Option("b", "second"));
opts.addOption(new Option("c", "third"));
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.setOptionComparator(null);
StringWriter out = new StringWriter();
helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
assertEquals("usage: app [-a] [-b] [-c]" + EOL, out.toString());
}
public void testPrintOptionGroupUsage()
{
OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create("a"));
group.addOption(OptionBuilder.create("b"));
group.addOption(OptionBuilder.create("c"));
Options options = new Options();
options.addOptionGroup(group);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app [-a | -b | -c]" + EOL, out.toString());
}
public void testPrintRequiredOptionGroupUsage()
{
OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create("a"));
group.addOption(OptionBuilder.create("b"));
group.addOption(OptionBuilder.create("c"));
group.setRequired(true);
Options options = new Options();
options.addOptionGroup(group);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app -a | -b | -c" + EOL, out.toString());
}
public void testPrintOptionWithEmptyArgNameUsage()
{
Option option = new Option("f", true, null);
option.setArgName("");
option.setRequired(true);
Options options = new Options();
options.addOption(option);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app -f" + EOL, out.toString());
}
public void testDefaultArgName()
{
Option option = OptionBuilder.hasArg().isRequired().create("f");
Options options = new Options();
options.addOption(option);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.setArgName("argument");
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app -f <argument>" + EOL, out.toString());
}
public void testRtrim()
{
HelpFormatter formatter = new HelpFormatter();
assertEquals(null, formatter.rtrim(null));
assertEquals("", formatter.rtrim(""));
assertEquals(" foo", formatter.rtrim(" foo "));
}
public void testAccessors()
{
HelpFormatter formatter = new HelpFormatter();
formatter.setArgName("argname");
assertEquals("arg name", "argname", formatter.getArgName());
formatter.setDescPadding(3);
assertEquals("desc padding", 3, formatter.getDescPadding());
formatter.setLeftPadding(7);
assertEquals("left padding", 7, formatter.getLeftPadding());
formatter.setLongOptPrefix("~~");
assertEquals("long opt prefix", "~~", formatter.getLongOptPrefix());
formatter.setNewLine("\n");
assertEquals("new line", "\n", formatter.getNewLine());
formatter.setOptPrefix("~");
assertEquals("opt prefix", "~", formatter.getOptPrefix());
formatter.setSyntaxPrefix("-> ");
assertEquals("syntax prefix", "-> ", formatter.getSyntaxPrefix());
formatter.setWidth(80);
assertEquals("width", 80, formatter.getWidth());
}
public void testHeaderStartingWithLineSeparator()
{
// related to Bugzilla #21215
Options options = new Options();
HelpFormatter formatter = new HelpFormatter();
String header = EOL + "Header";
String footer = "Footer";
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true);
assertEquals(
"usage: foobar" + EOL +
"" + EOL +
"Header" + EOL +
"" + EOL +
"Footer" + EOL
, out.toString());
}
public void testOptionWithoutShortFormat()
{
// related to Bugzilla #19383 (CLI-67)
Options options = new Options();
options.addOption(new Option("a", "aaa", false, "aaaaaaa"));
options.addOption(new Option(null, "bbb", false, "bbbbbbb"));
options.addOption(new Option("c", null, false, "ccccccc"));
HelpFormatter formatter = new HelpFormatter();
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "foobar", "", options, 2, 2, "", true);
assertEquals(
"usage: foobar [-a] [--bbb] [-c]" + EOL +
" -a,--aaa aaaaaaa" + EOL +
" --bbb bbbbbbb" + EOL +
" -c ccccccc" + EOL
, out.toString());
}
public void testOptionWithoutShortFormat2()
{
// related to Bugzilla #27635 (CLI-26)
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("config")
.hasArg()
.withValueSeparator()
.withDescription("Use the specified configuration file")
.create();
Options mOptions = new Options();
mOptions.addOption(help);
mOptions.addOption(version);
mOptions.addOption(newRun);
mOptions.addOption(trackerRun);
mOptions.addOption(timeLimit);
mOptions.addOption(age);
mOptions.addOption(server);
mOptions.addOption(numResults);
mOptions.addOption(configFile);
HelpFormatter formatter = new HelpFormatter();
final String EOL = System.getProperty("line.separator");
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out),80,"commandline","header",mOptions,2,2,"footer",true);
assertEquals(
"usage: commandline [-a <arg>] [--config <arg>] [-h] [-l <arg>] [-n] [-r <arg>]" + EOL +
" [-s <arg>] [-t] [-v]" + EOL +
"header"+EOL+
" -a,--age <arg> Age (in days) of cache item before being recomputed"+EOL+
" --config <arg> Use the specified configuration file"+EOL+
" -h,--help print this message"+EOL+
" -l,--limit <arg> Set time limit for execution, in mintues"+EOL+
" -n,--new Create NLT cache entries only for new items"+EOL+
" -r,--results <arg> Number of results per item"+EOL+
" -s,--server <arg> The NLT server address"+EOL+
" -t,--tracker Create NLT cache entries only for tracker items"+EOL+
" -v,--version print version information"+EOL+
"footer"+EOL
,out.toString());
}
public void testHelpWithLongOptSeparator() throws Exception
{
Options options = new Options();
options.addOption( "f", true, "the file" );
options.addOption(OptionBuilder.withLongOpt("size").withDescription("the size").hasArg().withArgName("SIZE").create('s'));
options.addOption(OptionBuilder.withLongOpt("age").withDescription("the age").hasArg().create());
HelpFormatter formatter = new HelpFormatter();
assertEquals(HelpFormatter.DEFAULT_LONG_OPT_SEPARATOR, formatter.getLongOptSeparator());
formatter.setLongOptSeparator("=");
assertEquals("=", formatter.getLongOptSeparator());
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "create", "header", options, 2, 2, "footer");
assertEquals(
"usage: create" + EOL +
"header" + EOL +
" --age=<arg> the age" + EOL +
" -f <arg> the file" + EOL +
" -s,--size=<SIZE> the size" + EOL +
"footer" + EOL,
out.toString());
}
public void testUsageWithLongOptSeparator() throws Exception
{
Options options = new Options();
options.addOption( "f", true, "the file" );
options.addOption(OptionBuilder.withLongOpt("size").withDescription("the size").hasArg().withArgName("SIZE").create('s'));
options.addOption(OptionBuilder.withLongOpt("age").withDescription("the age").hasArg().create());
HelpFormatter formatter = new HelpFormatter();
formatter.setLongOptSeparator("=");
StringWriter out = new StringWriter();
formatter.printUsage(new PrintWriter(out), 80, "create", options);
assertEquals("usage: create [--age=<arg>] [-f <arg>] [-s <SIZE>]", out.toString().trim());
}
} | // You are a professional Java test case writer, please create a test case named `testRenderWrappedTextWordCut` for the issue `Cli-CLI-193`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-193
//
// ## Issue-Title:
// StringIndexOutOfBoundsException in HelpFormatter.findWrapPos
//
// ## Issue-Description:
//
// In the last while loop in HelpFormatter.findWrapPos, it can pass text.length() to text.charAt(int), which throws a StringIndexOutOfBoundsException. The first expression in that while loop condition should use a <, not a <=.
//
//
// This is on line 908 in r779646:
//
// <http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli/HelpFormatter.java?revision=779646&view=markup>
//
//
//
//
//
public void testRenderWrappedTextWordCut() {
| 69 | 32 | 58 | src/test/java/org/apache/commons/cli/HelpFormatterTest.java | src/test/java | ```markdown
## Issue-ID: Cli-CLI-193
## Issue-Title:
StringIndexOutOfBoundsException in HelpFormatter.findWrapPos
## Issue-Description:
In the last while loop in HelpFormatter.findWrapPos, it can pass text.length() to text.charAt(int), which throws a StringIndexOutOfBoundsException. The first expression in that while loop condition should use a <, not a <=.
This is on line 908 in r779646:
<http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli/HelpFormatter.java?revision=779646&view=markup>
```
You are a professional Java test case writer, please create a test case named `testRenderWrappedTextWordCut` for the issue `Cli-CLI-193`, utilizing the provided issue report information and the following function signature.
```java
public void testRenderWrappedTextWordCut() {
```
| 58 | [
"org.apache.commons.cli.HelpFormatter"
] | 3846b5e1e91bd5ad76de716498563b17ad200e4b6efaeb4c6ee355e1a41ec427 | public void testRenderWrappedTextWordCut()
| // You are a professional Java test case writer, please create a test case named `testRenderWrappedTextWordCut` for the issue `Cli-CLI-193`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-193
//
// ## Issue-Title:
// StringIndexOutOfBoundsException in HelpFormatter.findWrapPos
//
// ## Issue-Description:
//
// In the last while loop in HelpFormatter.findWrapPos, it can pass text.length() to text.charAt(int), which throws a StringIndexOutOfBoundsException. The first expression in that while loop condition should use a <, not a <=.
//
//
// This is on line 908 in r779646:
//
// <http://svn.apache.org/viewvc/commons/proper/cli/trunk/src/java/org/apache/commons/cli/HelpFormatter.java?revision=779646&view=markup>
//
//
//
//
//
| Cli | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.cli;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Comparator;
import junit.framework.TestCase;
/**
* Test case for the HelpFormatter class
*
* @author Slawek Zachcial
* @author John Keyes ( john at integralsource.com )
* @author brianegge
*/
public class HelpFormatterTest extends TestCase
{
private static final String EOL = System.getProperty("line.separator");
public void testFindWrapPos() throws Exception
{
HelpFormatter hf = new HelpFormatter();
String text = "This is a test.";
// text width should be max 8; the wrap position is 7
assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0));
// starting from 8 must give -1 - the wrap pos is after end
assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8));
// words longer than the width are cut
text = "aaaa aa";
assertEquals("wrap position 3", 3, hf.findWrapPos(text, 3, 0));
// last word length is equal to the width
text = "aaaaaa aaaaaa";
assertEquals("wrap position 4", 6, hf.findWrapPos(text, 6, 0));
assertEquals("wrap position 4", -1, hf.findWrapPos(text, 6, 7));
}
public void testRenderWrappedTextWordCut()
{
int width = 7;
int padding = 0;
String text = "Thisisatest.";
String expected = "Thisisa" + EOL +
"test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("cut and wrap", expected, sb.toString());
}
public void testRenderWrappedTextSingleLine()
{
// single line text
int width = 12;
int padding = 0;
String text = "This is a test.";
String expected = "This is a" + EOL +
"test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("single line text", expected, sb.toString());
}
public void testRenderWrappedTextSingleLinePadded()
{
// single line padded text
int width = 12;
int padding = 4;
String text = "This is a test.";
String expected = "This is a" + EOL +
" test.";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("single line padded text", expected, sb.toString());
}
public void testRenderWrappedTextSingleLinePadded2()
{
// single line padded text 2
int width = 53;
int padding = 24;
String text = " -p,--period <PERIOD> PERIOD is time duration of form " +
"DATE[-DATE] where DATE has form YYYY[MM[DD]]";
String expected = " -p,--period <PERIOD> PERIOD is time duration of" + EOL +
" form DATE[-DATE] where DATE" + EOL +
" has form YYYY[MM[DD]]";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("single line padded text 2", expected, sb.toString());
}
public void testRenderWrappedTextMultiLine()
{
// multi line text
int width = 16;
int padding = 0;
String text = "aaaa aaaa aaaa" + EOL +
"aaaaaa" + EOL +
"aaaaa";
String expected = text;
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("multi line text", expected, sb.toString());
}
public void testRenderWrappedTextMultiLinePadded()
{
// multi-line padded text
int width = 16;
int padding = 4;
String text = "aaaa aaaa aaaa" + EOL +
"aaaaaa" + EOL +
"aaaaa";
String expected = "aaaa aaaa aaaa" + EOL +
" aaaaaa" + EOL +
" aaaaa";
StringBuffer sb = new StringBuffer();
new HelpFormatter().renderWrappedText(sb, width, padding, text);
assertEquals("multi-line padded text", expected, sb.toString());
}
public void testPrintOptions() throws Exception
{
StringBuffer sb = new StringBuffer();
HelpFormatter hf = new HelpFormatter();
final int leftPad = 1;
final int descPad = 3;
final String lpad = hf.createPadding(leftPad);
final String dpad = hf.createPadding(descPad);
Options options = null;
String expected = null;
options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa";
hf.renderOptions(sb, 60, options, leftPad, descPad);
assertEquals("simple non-wrapped option", expected, sb.toString());
int nextLineTabStop = leftPad + descPad + "-a".length();
expected = lpad + "-a" + dpad + "aaaa aaaa aaaa" + EOL +
hf.createPadding(nextLineTabStop) + "aaaa aaaa";
sb.setLength(0);
hf.renderOptions(sb, nextLineTabStop + 17, options, leftPad, descPad);
assertEquals("simple wrapped option", expected, sb.toString());
options = new Options().addOption("a", "aaa", false, "dddd dddd dddd dddd");
expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
sb.setLength(0);
hf.renderOptions(sb, 60, options, leftPad, descPad);
assertEquals("long non-wrapped option", expected, sb.toString());
nextLineTabStop = leftPad + descPad + "-a,--aaa".length();
expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL +
hf.createPadding(nextLineTabStop) + "dddd dddd";
sb.setLength(0);
hf.renderOptions(sb, 25, options, leftPad, descPad);
assertEquals("long wrapped option", expected, sb.toString());
options = new Options().
addOption("a", "aaa", false, "dddd dddd dddd dddd").
addOption("b", false, "feeee eeee eeee eeee");
expected = lpad + "-a,--aaa" + dpad + "dddd dddd" + EOL +
hf.createPadding(nextLineTabStop) + "dddd dddd" + EOL +
lpad + "-b " + dpad + "feeee eeee" + EOL +
hf.createPadding(nextLineTabStop) + "eeee eeee";
sb.setLength(0);
hf.renderOptions(sb, 25, options, leftPad, descPad);
assertEquals("multiple wrapped options", expected, sb.toString());
}
public void testPrintHelpWithEmptySyntax()
{
HelpFormatter formatter = new HelpFormatter();
try
{
formatter.printHelp(null, new Options());
fail("null command line syntax should be rejected");
}
catch (IllegalArgumentException e)
{
// expected
}
try
{
formatter.printHelp("", new Options());
fail("empty command line syntax should be rejected");
}
catch (IllegalArgumentException e)
{
// expected
}
}
public void testAutomaticUsage() throws Exception
{
HelpFormatter hf = new HelpFormatter();
Options options = null;
String expected = "usage: app [-a]";
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa");
hf.printUsage(pw, 60, "app", options);
pw.flush();
assertEquals("simple auto usage", expected, out.toString().trim());
out.reset();
expected = "usage: app [-a] [-b]";
options = new Options().addOption("a", false, "aaaa aaaa aaaa aaaa aaaa")
.addOption("b", false, "bbb");
hf.printUsage(pw, 60, "app", options);
pw.flush();
assertEquals("simple auto usage", expected, out.toString().trim());
out.reset();
}
// This test ensures the options are properly sorted
// See https://issues.apache.org/jira/browse/CLI-131
public void testPrintUsage()
{
Option optionA = new Option("a", "first");
Option optionB = new Option("b", "second");
Option optionC = new Option("c", "third");
Options opts = new Options();
opts.addOption(optionA);
opts.addOption(optionB);
opts.addOption(optionC);
HelpFormatter helpFormatter = new HelpFormatter();
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(bytesOut);
helpFormatter.printUsage(printWriter, 80, "app", opts);
printWriter.close();
assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString());
}
// uses the test for CLI-131 to implement CLI-155
public void testPrintSortedUsage()
{
Options opts = new Options();
opts.addOption(new Option("a", "first"));
opts.addOption(new Option("b", "second"));
opts.addOption(new Option("c", "third"));
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.setOptionComparator(new Comparator()
{
public int compare(Object o1, Object o2)
{
// reverses the fuctionality of the default comparator
Option opt1 = (Option) o1;
Option opt2 = (Option) o2;
return opt2.getKey().compareToIgnoreCase(opt1.getKey());
}
});
StringWriter out = new StringWriter();
helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
assertEquals("usage: app [-c] [-b] [-a]" + EOL, out.toString());
}
public void testPrintSortedUsageWithNullComparator()
{
Options opts = new Options();
opts.addOption(new Option("a", "first"));
opts.addOption(new Option("b", "second"));
opts.addOption(new Option("c", "third"));
HelpFormatter helpFormatter = new HelpFormatter();
helpFormatter.setOptionComparator(null);
StringWriter out = new StringWriter();
helpFormatter.printUsage(new PrintWriter(out), 80, "app", opts);
assertEquals("usage: app [-a] [-b] [-c]" + EOL, out.toString());
}
public void testPrintOptionGroupUsage()
{
OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create("a"));
group.addOption(OptionBuilder.create("b"));
group.addOption(OptionBuilder.create("c"));
Options options = new Options();
options.addOptionGroup(group);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app [-a | -b | -c]" + EOL, out.toString());
}
public void testPrintRequiredOptionGroupUsage()
{
OptionGroup group = new OptionGroup();
group.addOption(OptionBuilder.create("a"));
group.addOption(OptionBuilder.create("b"));
group.addOption(OptionBuilder.create("c"));
group.setRequired(true);
Options options = new Options();
options.addOptionGroup(group);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app -a | -b | -c" + EOL, out.toString());
}
public void testPrintOptionWithEmptyArgNameUsage()
{
Option option = new Option("f", true, null);
option.setArgName("");
option.setRequired(true);
Options options = new Options();
options.addOption(option);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app -f" + EOL, out.toString());
}
public void testDefaultArgName()
{
Option option = OptionBuilder.hasArg().isRequired().create("f");
Options options = new Options();
options.addOption(option);
StringWriter out = new StringWriter();
HelpFormatter formatter = new HelpFormatter();
formatter.setArgName("argument");
formatter.printUsage(new PrintWriter(out), 80, "app", options);
assertEquals("usage: app -f <argument>" + EOL, out.toString());
}
public void testRtrim()
{
HelpFormatter formatter = new HelpFormatter();
assertEquals(null, formatter.rtrim(null));
assertEquals("", formatter.rtrim(""));
assertEquals(" foo", formatter.rtrim(" foo "));
}
public void testAccessors()
{
HelpFormatter formatter = new HelpFormatter();
formatter.setArgName("argname");
assertEquals("arg name", "argname", formatter.getArgName());
formatter.setDescPadding(3);
assertEquals("desc padding", 3, formatter.getDescPadding());
formatter.setLeftPadding(7);
assertEquals("left padding", 7, formatter.getLeftPadding());
formatter.setLongOptPrefix("~~");
assertEquals("long opt prefix", "~~", formatter.getLongOptPrefix());
formatter.setNewLine("\n");
assertEquals("new line", "\n", formatter.getNewLine());
formatter.setOptPrefix("~");
assertEquals("opt prefix", "~", formatter.getOptPrefix());
formatter.setSyntaxPrefix("-> ");
assertEquals("syntax prefix", "-> ", formatter.getSyntaxPrefix());
formatter.setWidth(80);
assertEquals("width", 80, formatter.getWidth());
}
public void testHeaderStartingWithLineSeparator()
{
// related to Bugzilla #21215
Options options = new Options();
HelpFormatter formatter = new HelpFormatter();
String header = EOL + "Header";
String footer = "Footer";
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "foobar", header, options, 2, 2, footer, true);
assertEquals(
"usage: foobar" + EOL +
"" + EOL +
"Header" + EOL +
"" + EOL +
"Footer" + EOL
, out.toString());
}
public void testOptionWithoutShortFormat()
{
// related to Bugzilla #19383 (CLI-67)
Options options = new Options();
options.addOption(new Option("a", "aaa", false, "aaaaaaa"));
options.addOption(new Option(null, "bbb", false, "bbbbbbb"));
options.addOption(new Option("c", null, false, "ccccccc"));
HelpFormatter formatter = new HelpFormatter();
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "foobar", "", options, 2, 2, "", true);
assertEquals(
"usage: foobar [-a] [--bbb] [-c]" + EOL +
" -a,--aaa aaaaaaa" + EOL +
" --bbb bbbbbbb" + EOL +
" -c ccccccc" + EOL
, out.toString());
}
public void testOptionWithoutShortFormat2()
{
// related to Bugzilla #27635 (CLI-26)
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("config")
.hasArg()
.withValueSeparator()
.withDescription("Use the specified configuration file")
.create();
Options mOptions = new Options();
mOptions.addOption(help);
mOptions.addOption(version);
mOptions.addOption(newRun);
mOptions.addOption(trackerRun);
mOptions.addOption(timeLimit);
mOptions.addOption(age);
mOptions.addOption(server);
mOptions.addOption(numResults);
mOptions.addOption(configFile);
HelpFormatter formatter = new HelpFormatter();
final String EOL = System.getProperty("line.separator");
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out),80,"commandline","header",mOptions,2,2,"footer",true);
assertEquals(
"usage: commandline [-a <arg>] [--config <arg>] [-h] [-l <arg>] [-n] [-r <arg>]" + EOL +
" [-s <arg>] [-t] [-v]" + EOL +
"header"+EOL+
" -a,--age <arg> Age (in days) of cache item before being recomputed"+EOL+
" --config <arg> Use the specified configuration file"+EOL+
" -h,--help print this message"+EOL+
" -l,--limit <arg> Set time limit for execution, in mintues"+EOL+
" -n,--new Create NLT cache entries only for new items"+EOL+
" -r,--results <arg> Number of results per item"+EOL+
" -s,--server <arg> The NLT server address"+EOL+
" -t,--tracker Create NLT cache entries only for tracker items"+EOL+
" -v,--version print version information"+EOL+
"footer"+EOL
,out.toString());
}
public void testHelpWithLongOptSeparator() throws Exception
{
Options options = new Options();
options.addOption( "f", true, "the file" );
options.addOption(OptionBuilder.withLongOpt("size").withDescription("the size").hasArg().withArgName("SIZE").create('s'));
options.addOption(OptionBuilder.withLongOpt("age").withDescription("the age").hasArg().create());
HelpFormatter formatter = new HelpFormatter();
assertEquals(HelpFormatter.DEFAULT_LONG_OPT_SEPARATOR, formatter.getLongOptSeparator());
formatter.setLongOptSeparator("=");
assertEquals("=", formatter.getLongOptSeparator());
StringWriter out = new StringWriter();
formatter.printHelp(new PrintWriter(out), 80, "create", "header", options, 2, 2, "footer");
assertEquals(
"usage: create" + EOL +
"header" + EOL +
" --age=<arg> the age" + EOL +
" -f <arg> the file" + EOL +
" -s,--size=<SIZE> the size" + EOL +
"footer" + EOL,
out.toString());
}
public void testUsageWithLongOptSeparator() throws Exception
{
Options options = new Options();
options.addOption( "f", true, "the file" );
options.addOption(OptionBuilder.withLongOpt("size").withDescription("the size").hasArg().withArgName("SIZE").create('s'));
options.addOption(OptionBuilder.withLongOpt("age").withDescription("the age").hasArg().create());
HelpFormatter formatter = new HelpFormatter();
formatter.setLongOptSeparator("=");
StringWriter out = new StringWriter();
formatter.printUsage(new PrintWriter(out), 80, "create", options);
assertEquals("usage: create [--age=<arg>] [-f <arg>] [-s <SIZE>]", out.toString().trim());
}
} |
||
public void testShortWithEqual() throws Exception
{
String[] args = new String[] { "-f=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
} | org.apache.commons.cli.GnuParserTest::testShortWithEqual | src/test/org/apache/commons/cli/GnuParserTest.java | 209 | src/test/org/apache/commons/cli/GnuParserTest.java | testShortWithEqual | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.cli;
import junit.framework.TestCase;
public class GnuParserTest extends TestCase
{
private Options options;
private Parser parser;
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 GnuParser( );
}
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 size of extra args", cl.getArgList().size() == 2);
}
public void testExtraOption() throws Exception
{
String[] args = new String[] { "-a", "-d", "-b", "toast",
"foo", "bar" };
boolean caught = false;
try
{
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() == 3);
}
catch (UnrecognizedOptionException e)
{
caught = true;
}
assertTrue( "Confirm UnrecognizedOptionException caught", caught );
}
public void testMissingArg() throws Exception
{
String[] args = new String[] { "-b" };
boolean caught = false;
try
{
parser.parse(options, args);
}
catch (MissingArgumentException e)
{
caught = true;
}
assertTrue( "Confirm MissingArgumentException caught", caught );
}
public void testStop() throws Exception
{
String[] args = new String[] { "-c",
"foober",
"-b",
"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);
}
public void testMultiple() throws Exception
{
String[] args = new String[] { "-c",
"foobar",
"-b",
"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 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("-"));
}
public void testNegativeArgument() throws Exception
{
String[] args = new String[] { "-a", "-1"} ;
Options options = new Options();
options.addOption(OptionBuilder.hasArg().create("a"));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("-1", cl.getOptionValue("a"));
}
public void testShortWithEqual() throws Exception
{
String[] args = new String[] { "-f=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
public void testShortWithoutEqual() throws Exception
{
String[] args = new String[] { "-fbar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
public void testLongWithEqual() throws Exception
{
String[] args = new String[] { "--foo=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
public void testLongWithEqualSingleDash() throws Exception
{
String[] args = new String[] { "-foo=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
} | // You are a professional Java test case writer, please create a test case named `testShortWithEqual` 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 testShortWithEqual() throws Exception {
| 209 | 12 | 198 | src/test/org/apache/commons/cli/GnuParserTest.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 `testShortWithEqual` for the issue `Cli-cli-1`, utilizing the provided issue report information and the following function signature.
```java
public void testShortWithEqual() throws Exception {
```
| 198 | [
"org.apache.commons.cli.GnuParser"
] | 39ca7080b581dc9130f1b142e3a8ffcf0ff7ee2b575c3df2b5c7b3aaa13c9fe8 | public void testShortWithEqual() throws Exception
| // You are a professional Java test case writer, please create a test case named `testShortWithEqual` 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 junit.framework.TestCase;
public class GnuParserTest extends TestCase
{
private Options options;
private Parser parser;
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 GnuParser( );
}
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 size of extra args", cl.getArgList().size() == 2);
}
public void testExtraOption() throws Exception
{
String[] args = new String[] { "-a", "-d", "-b", "toast",
"foo", "bar" };
boolean caught = false;
try
{
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() == 3);
}
catch (UnrecognizedOptionException e)
{
caught = true;
}
assertTrue( "Confirm UnrecognizedOptionException caught", caught );
}
public void testMissingArg() throws Exception
{
String[] args = new String[] { "-b" };
boolean caught = false;
try
{
parser.parse(options, args);
}
catch (MissingArgumentException e)
{
caught = true;
}
assertTrue( "Confirm MissingArgumentException caught", caught );
}
public void testStop() throws Exception
{
String[] args = new String[] { "-c",
"foober",
"-b",
"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);
}
public void testMultiple() throws Exception
{
String[] args = new String[] { "-c",
"foobar",
"-b",
"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 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("-"));
}
public void testNegativeArgument() throws Exception
{
String[] args = new String[] { "-a", "-1"} ;
Options options = new Options();
options.addOption(OptionBuilder.hasArg().create("a"));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("-1", cl.getOptionValue("a"));
}
public void testShortWithEqual() throws Exception
{
String[] args = new String[] { "-f=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
public void testShortWithoutEqual() throws Exception
{
String[] args = new String[] { "-fbar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
public void testLongWithEqual() throws Exception
{
String[] args = new String[] { "--foo=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
public void testLongWithEqualSingleDash() throws Exception
{
String[] args = new String[] { "-foo=bar" };
Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("foo").hasArg().create('f'));
Parser parser = new GnuParser();
CommandLine cl = parser.parse(options, args);
assertEquals("bar", cl.getOptionValue("foo"));
}
} |
||
public void testUnicode() {
assertPrint("var x ='\\x0f';", "var x=\"\\u000f\"");
assertPrint("var x ='\\x68';", "var x=\"h\"");
assertPrint("var x ='\\x7f';", "var x=\"\\u007f\"");
} | com.google.javascript.jscomp.CodePrinterTest::testUnicode | test/com/google/javascript/jscomp/CodePrinterTest.java | 1,215 | test/com/google/javascript/jscomp/CodePrinterTest.java | testUnicode | /*
* Copyright 2004 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import junit.framework.TestCase;
public class CodePrinterTest extends TestCase {
static Node parse(String js) {
return parse(js, false);
}
static Node parse(String js, boolean checkTypes) {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
// Allow getters and setters.
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
compiler.initOptions(options);
Node n = compiler.parseTestCode(js);
if (checkTypes) {
DefaultPassConfig passConfig = new DefaultPassConfig(null);
CompilerPass typeResolver = passConfig.resolveTypes.create(compiler);
Node externs = new Node(Token.SCRIPT);
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 testTypeAnnotationsMember() {
assertTypeAnnotations("var a = {};"
+ "/** @constructor */ a.Foo = function(){}"
+ "/** @param {string} foo\n"
+ " * @return {number} */\n"
+ "a.Foo.prototype.foo = function(foo) { return 3; };"
+ "/** @type {string|undefined} */"
+ "a.Foo.prototype.bar = '';",
"var a = {};\n"
+ "/**\n * @return {undefined}\n * @constructor\n */\n"
+ "a.Foo = function() {\n};\n"
+ "/**\n"
+ " * @param {string} foo\n"
+ " * @return {number}\n"
+ " */\n"
+ "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n"
+ "/** @type {string} */\n"
+ "a.Foo.prototype.bar = \"\";\n");
}
public void testTypeAnnotationsImplements() {
assertTypeAnnotations("var a = {};"
+ "/** @constructor */ a.Foo = function(){};\n"
+ "/** @interface */ a.I = function(){};\n"
+ "/** @interface */ a.I2 = function(){};\n"
+ "/** @constructor \n @extends {a.Foo}\n"
+ " * @implements {a.I} \n @implements {a.I2}\n"
+ "*/ a.Bar = function(){}",
"var a = {};\n"
+ "/**\n * @return {undefined}\n * @constructor\n */\n"
+ "a.Foo = function() {\n};\n"
+ "/**\n * @interface\n */\n"
+ "a.I = function() {\n};\n"
+ "/**\n * @interface\n */\n"
+ "a.I2 = function() {\n};\n"
+ "/**\n * @return {undefined}\n * @extends {a.Foo}\n"
+ " * @implements {a.I}\n"
+ " * @implements {a.I2}\n * @constructor\n */\n"
+ "a.Bar = function() {\n};\n");
}
public void testTypeAnnotationsDispatcher1() {
assertTypeAnnotations(
"var a = {};\n" +
"/** \n" +
" * @constructor \n" +
" * @javadispatch \n" +
" */\n" +
"a.Foo = function(){}",
"var a = {};\n" +
"/**\n" +
" * @return {undefined}\n" +
" * @constructor\n" +
" * @javadispatch\n" +
" */\n" +
"a.Foo = function() {\n" +
"};\n");
}
public void testTypeAnnotationsDispatcher2() {
assertTypeAnnotations(
"var a = {};\n" +
"/** \n" +
" * @constructor \n" +
" */\n" +
"a.Foo = function(){}\n" +
"/**\n" +
" * @javadispatch\n" +
" */\n" +
"a.Foo.prototype.foo = function() {};",
"var a = {};\n" +
"/**\n" +
" * @return {undefined}\n" +
" * @constructor\n" +
" */\n" +
"a.Foo = function() {\n" +
"};\n" +
"/**\n" +
" * @return {undefined}\n" +
" * @javadispatch\n" +
" */\n" +
"a.Foo.prototype.foo = function() {\n" +
"};\n");
}
public void testU2UFunctionTypeAnnotation() {
assertTypeAnnotations(
"/** @type {!Function} */ var x = function() {}",
"/**\n * @constructor\n */\nvar x = function() {\n};\n");
}
public void testEmitUnknownParamTypesAsAllType() {
assertTypeAnnotations(
"var a = function(x) {}",
"/**\n" +
" * @param {*} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\n};\n");
}
public void testOptionalTypesAnnotation() {
assertTypeAnnotations(
"/**\n" +
" * @param {string=} x \n" +
" */\n" +
"var a = function(x) {}",
"/**\n" +
" * @param {string=} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\n};\n");
}
public void testVariableArgumentsTypesAnnotation() {
assertTypeAnnotations(
"/**\n" +
" * @param {...string} x \n" +
" */\n" +
"var a = function(x) {}",
"/**\n" +
" * @param {...string} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\n};\n");
}
public void testTempConstructor() {
assertTypeAnnotations(
"var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" +
" /**\n * @constructor\n */\nfunction t2() {}\n" +
" t1.prototype = t2.prototype}",
"/**\n * @return {undefined}\n */\nvar x = function() {\n" +
" /**\n * @return {undefined}\n * @constructor\n */\n" +
"function t1() {\n }\n" +
" /**\n * @return {undefined}\n * @constructor\n */\n" +
"function t2() {\n }\n" +
" t1.prototype = t2.prototype\n};\n"
);
}
private void assertPrettyPrint(String js, String expected) {
assertEquals(expected,
parsePrint(js, true, false,
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD));
}
private void assertTypeAnnotations(String js, String expected) {
assertEquals(expected,
parsePrint(js, true, false,
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true));
}
public void testSubtraction() {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode("x - -4");
assertEquals(0, compiler.getErrorCount());
assertEquals(
"x- -4",
new CodePrinter.Builder(n).setLineLengthThreshold(
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build());
}
public void testFunctionWithCall() {
assertPrint(
"var user = new function() {"
+ "alert(\"foo\")}",
"var user=new function(){"
+ "alert(\"foo\")}");
assertPrint(
"var user = new function() {"
+ "this.name = \"foo\";"
+ "this.local = function(){alert(this.name)};}",
"var user=new function(){"
+ "this.name=\"foo\";"
+ "this.local=function(){alert(this.name)}}");
}
public void testLineLength() {
// list
assertLineLength("var aba,bcb,cdc",
"var aba,bcb," +
"\ncdc");
// operators, and two breaks
assertLineLength(
"\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"",
"\"foo\"+\"bar,baz,bomb\"+" +
"\n\"whee\"+\";long-string\"+" +
"\n\"aaa\"");
// assignment
assertLineLength("var abazaba=1234",
"var abazaba=" +
"\n1234");
// statements
assertLineLength("var abab=1;var bab=2",
"var abab=1;" +
"\nvar bab=2");
// don't break regexes
assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a",
"var a=/some[reg](ex),with.*we?rd|chars/i;" +
"\nvar b=a");
// don't break strings
assertLineLength("var a=\"foo,{bar};baz\";var b=a",
"var a=\"foo,{bar};baz\";" +
"\nvar b=a");
// don't break before post inc/dec
assertLineLength("var a=\"a\";a++;var b=\"bbb\";",
"var a=\"a\";a++;\n" +
"var b=\"bbb\"");
}
private void assertLineLength(String js, String expected) {
assertEquals(expected,
parsePrint(js, false, true, 10));
}
public void testParsePrintParse() {
testReparse("3;");
testReparse("var a = b;");
testReparse("var x, y, z;");
testReparse("try { foo() } catch(e) { bar() }");
testReparse("try { foo() } catch(e) { bar() } finally { stuff() }");
testReparse("try { foo() } finally { stuff() }");
testReparse("throw 'me'");
testReparse("function foo(a) { return a + 4; }");
testReparse("function foo() { return; }");
testReparse("var a = function(a, b) { foo(); return a + b; }");
testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];");
testReparse("v = (5, 6, 7, 8)");
testReparse("d = 34.0; x = 0; y = .3; z = -22");
testReparse("d = -x; t = !x + ~y;");
testReparse("'hi'; /* just a test */ stuff(a,b) \n" +
" foo(); // and another \n" +
" bar();");
testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;");
testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5");
testReparse("a = (2 + 3) * 4;");
testReparse("a = 1 + (2 + 3) + 4;");
testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());");
testReparse("a = b | c || d ^ e " +
"&& f & !g != h << i <= j < k >>> l > m * n % !o");
testReparse("a == b; a != b; a === b; a == b == a;" +
" (a == b) == a; a == (b == a);");
testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;");
testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }");
testReparse("for (var i in a) b += i;");
testReparse("for (var i = 0; i < 10; i++){ b /= 2;" +
" if (b == 2)break;else continue;}");
testReparse("for (x = 0; x < 10; x++) a /= 2;");
testReparse("for (;;) a++;");
testReparse("while(true) { blah(); }while(true) blah();");
testReparse("do stuff(); while(a>b);");
testReparse("[0, null, , true, false, this];");
testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');");
testReparse("new Foo; new Bar(a, b,c);");
testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;");
testReparse("delete foo['bar']; delete foo;");
testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };");
testReparse("switch(a) { case 2: case 3: stuff(); break;" +
"case 4: morestuff(); break; default: done();}");
testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;");
testReparse("a.v = b.v; x['foo'] = y['zoo'];");
testReparse("'test' in x; 3 in x; a in x;");
testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'");
testReparse("x.__proto__;");
}
private void testReparse(String code) {
Compiler compiler = new Compiler();
Node parse1 = parse(code);
Node parse2 = parse(new CodePrinter.Builder(parse1).build());
String explanation = parse1.checkTreeEquals(parse2);
assertNull("\nExpected: " + compiler.toSource(parse1) +
"\nResult: " + compiler.toSource(parse2) +
"\n" + explanation, explanation);
}
public void testDoLoopIECompatiblity() {
// Do loops within IFs cause syntax errors in IE6 and IE7.
assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}",
"function f(){if(e1){do foo();while(e2)}else foo()}");
assertPrint("function f(){if(e1)do foo();while(e2)else foo()}",
"function f(){if(e1){do foo();while(e2)}else foo()}");
assertPrint("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
assertPrint("if(x)do{foo()}while(y);else bar()",
"if(x){do foo();while(y)}else bar()");
assertPrint("if(x){do{foo()}while(y)}",
"if(x){do foo();while(y)}");
assertPrint("if(x)do{foo()}while(y);",
"if(x){do foo();while(y)}");
assertPrint("if(x)A:do{foo()}while(y);",
"if(x){A:do foo();while(y)}");
assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);",
"var i=0;a:do{b:do{i++;break b}while(0)}while(0)");
}
public void testFunctionSafariCompatiblity() {
// Functions within IFs cause syntax errors on Safari.
assertPrint("function f(){if(e1){function goo(){return true}}else foo()}",
"function f(){if(e1){function goo(){return true}}else foo()}");
assertPrint("function f(){if(e1)function goo(){return true}else foo()}",
"function f(){if(e1){function goo(){return true}}else foo()}");
assertPrint("if(e1){function goo(){return true}}",
"if(e1){function goo(){return true}}");
assertPrint("if(e1)function goo(){return true}",
"if(e1){function goo(){return true}}");
assertPrint("if(e1)A:function goo(){return true}",
"if(e1){A:function goo(){return true}}");
}
public void testExponents() {
assertPrintNumber("1", 1);
assertPrintNumber("10", 10);
assertPrintNumber("100", 100);
assertPrintNumber("1E3", 1000);
assertPrintNumber("1E4", 10000);
assertPrintNumber("1E5", 100000);
assertPrintNumber("-1", -1);
assertPrintNumber("-10", -10);
assertPrintNumber("-100", -100);
assertPrintNumber("-1E3", -1000);
assertPrintNumber("-12341234E4", -123412340000L);
assertPrintNumber("1E18", 1000000000000000000L);
assertPrintNumber("1E5", 100000.0);
assertPrintNumber("100000.1", 100000.1);
assertPrintNumber("1.0E-6", 0.000001);
}
// Make sure to test as both a String and a Node, because
// negative numbers do not parse consistently from strings.
private void assertPrintNumber(String expected, double number) {
assertPrint(String.valueOf(number), expected);
assertPrintNode(expected, Node.newNumber(number));
}
private void assertPrintNumber(String expected, int number) {
assertPrint(String.valueOf(number), expected);
assertPrintNode(expected, Node.newNumber(number));
}
public void testDirectEval() {
assertPrint("eval('1');", "eval(\"1\")");
}
public void testIndirectEval() {
Node n = parse("eval('1');");
assertPrintNode("eval(\"1\")", n);
n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp(
Node.DIRECT_EVAL, false);
assertPrintNode("(0,eval)(\"1\")", n);
}
public void testFreeCall1() {
assertPrint("foo(a);", "foo(a)");
assertPrint("x.foo(a);", "x.foo(a)");
}
public void testFreeCall2() {
Node n = parse("foo(a);");
assertPrintNode("foo(a)", n);
Node call = n.getFirstChild().getFirstChild();
assertTrue(call.getType() == Token.CALL);
call.putBooleanProp(Node.FREE_CALL, true);
assertPrintNode("foo(a)", n);
}
public void testFreeCall3() {
Node n = parse("x.foo(a);");
assertPrintNode("x.foo(a)", n);
Node call = n.getFirstChild().getFirstChild();
assertTrue(call.getType() == Token.CALL);
call.putBooleanProp(Node.FREE_CALL, true);
assertPrintNode("(0,x.foo)(a)", n);
}
public void testPrintScript() {
// Verify that SCRIPT nodes not marked as synthetic are printed as
// blocks.
Node ast = new Node(Token.SCRIPT,
new Node(Token.EXPR_RESULT, Node.newString("f")),
new Node(Token.EXPR_RESULT, Node.newString("g")));
String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build();
assertEquals("\"f\";\n\"g\";\n", result);
}
public void testObjectLit() {
assertPrint("({x:1})", "({x:1})");
assertPrint("var x=({x:1})", "var x={x:1}");
assertPrint("var x={'x':1}", "var x={\"x\":1}");
assertPrint("var x={1:1}", "var x={1:1}");
}
public void 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 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=\"\\0\"");
assertPrint("var x ='\\x00';", "var x=\"\\0\"");
assertPrint("var x ='\\u0000';", "var x=\"\\0\"");
}
public void testUnicode() {
assertPrint("var x ='\\x0f';", "var x=\"\\u000f\"");
assertPrint("var x ='\\x68';", "var x=\"h\"");
assertPrint("var x ='\\x7f';", "var x=\"\\u007f\"");
}
} | // You are a professional Java test case writer, please create a test case named `testUnicode` for the issue `Closure-416`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-416
//
// ## Issue-Title:
// Codepoint U+007f appears raw in output
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Open http://closure-compiler.appspot.com/home in your browser
// 2. Enter the source code: alert('\x7f')
// 3. Hit the "Compile" button.
//
// What is the expected output?
// alert("\x7f")
//
// What do you see instead?
// alert("");
//
//
// **What version of the product are you using? On what operating system?**
// The version live on 11 April 2011.
//
// **Please provide any additional information below.**
// Codepoint U+007f is a delete control character and is the only non-printable ASCII codepoint that is not <= U+0020. http://www.fileformat.info/info/unicode/char/7f/index.htm
//
// It should probably not appear raw in emitted source code because, it can confuse encoders.
//
//
public void testUnicode() {
| 1,215 | 73 | 1,211 | test/com/google/javascript/jscomp/CodePrinterTest.java | test | ```markdown
## Issue-ID: Closure-416
## Issue-Title:
Codepoint U+007f appears raw in output
## Issue-Description:
**What steps will reproduce the problem?**
1. Open http://closure-compiler.appspot.com/home in your browser
2. Enter the source code: alert('\x7f')
3. Hit the "Compile" button.
What is the expected output?
alert("\x7f")
What do you see instead?
alert("");
**What version of the product are you using? On what operating system?**
The version live on 11 April 2011.
**Please provide any additional information below.**
Codepoint U+007f is a delete control character and is the only non-printable ASCII codepoint that is not <= U+0020. http://www.fileformat.info/info/unicode/char/7f/index.htm
It should probably not appear raw in emitted source code because, it can confuse encoders.
```
You are a professional Java test case writer, please create a test case named `testUnicode` for the issue `Closure-416`, utilizing the provided issue report information and the following function signature.
```java
public void testUnicode() {
```
| 1,211 | [
"com.google.javascript.jscomp.CodeGenerator"
] | 39ebfb0ede79f775cca0498108f5c6a3021b3ed07b8d88c541f4d86441f1b7b3 | public void testUnicode() | // You are a professional Java test case writer, please create a test case named `testUnicode` for the issue `Closure-416`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-416
//
// ## Issue-Title:
// Codepoint U+007f appears raw in output
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Open http://closure-compiler.appspot.com/home in your browser
// 2. Enter the source code: alert('\x7f')
// 3. Hit the "Compile" button.
//
// What is the expected output?
// alert("\x7f")
//
// What do you see instead?
// alert("");
//
//
// **What version of the product are you using? On what operating system?**
// The version live on 11 April 2011.
//
// **Please provide any additional information below.**
// Codepoint U+007f is a delete control character and is the only non-printable ASCII codepoint that is not <= U+0020. http://www.fileformat.info/info/unicode/char/7f/index.htm
//
// It should probably not appear raw in emitted source code because, it can confuse encoders.
//
//
| Closure | /*
* Copyright 2004 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import junit.framework.TestCase;
public class CodePrinterTest extends TestCase {
static Node parse(String js) {
return parse(js, false);
}
static Node parse(String js, boolean checkTypes) {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
// Allow getters and setters.
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
compiler.initOptions(options);
Node n = compiler.parseTestCode(js);
if (checkTypes) {
DefaultPassConfig passConfig = new DefaultPassConfig(null);
CompilerPass typeResolver = passConfig.resolveTypes.create(compiler);
Node externs = new Node(Token.SCRIPT);
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 testTypeAnnotationsMember() {
assertTypeAnnotations("var a = {};"
+ "/** @constructor */ a.Foo = function(){}"
+ "/** @param {string} foo\n"
+ " * @return {number} */\n"
+ "a.Foo.prototype.foo = function(foo) { return 3; };"
+ "/** @type {string|undefined} */"
+ "a.Foo.prototype.bar = '';",
"var a = {};\n"
+ "/**\n * @return {undefined}\n * @constructor\n */\n"
+ "a.Foo = function() {\n};\n"
+ "/**\n"
+ " * @param {string} foo\n"
+ " * @return {number}\n"
+ " */\n"
+ "a.Foo.prototype.foo = function(foo) {\n return 3\n};\n"
+ "/** @type {string} */\n"
+ "a.Foo.prototype.bar = \"\";\n");
}
public void testTypeAnnotationsImplements() {
assertTypeAnnotations("var a = {};"
+ "/** @constructor */ a.Foo = function(){};\n"
+ "/** @interface */ a.I = function(){};\n"
+ "/** @interface */ a.I2 = function(){};\n"
+ "/** @constructor \n @extends {a.Foo}\n"
+ " * @implements {a.I} \n @implements {a.I2}\n"
+ "*/ a.Bar = function(){}",
"var a = {};\n"
+ "/**\n * @return {undefined}\n * @constructor\n */\n"
+ "a.Foo = function() {\n};\n"
+ "/**\n * @interface\n */\n"
+ "a.I = function() {\n};\n"
+ "/**\n * @interface\n */\n"
+ "a.I2 = function() {\n};\n"
+ "/**\n * @return {undefined}\n * @extends {a.Foo}\n"
+ " * @implements {a.I}\n"
+ " * @implements {a.I2}\n * @constructor\n */\n"
+ "a.Bar = function() {\n};\n");
}
public void testTypeAnnotationsDispatcher1() {
assertTypeAnnotations(
"var a = {};\n" +
"/** \n" +
" * @constructor \n" +
" * @javadispatch \n" +
" */\n" +
"a.Foo = function(){}",
"var a = {};\n" +
"/**\n" +
" * @return {undefined}\n" +
" * @constructor\n" +
" * @javadispatch\n" +
" */\n" +
"a.Foo = function() {\n" +
"};\n");
}
public void testTypeAnnotationsDispatcher2() {
assertTypeAnnotations(
"var a = {};\n" +
"/** \n" +
" * @constructor \n" +
" */\n" +
"a.Foo = function(){}\n" +
"/**\n" +
" * @javadispatch\n" +
" */\n" +
"a.Foo.prototype.foo = function() {};",
"var a = {};\n" +
"/**\n" +
" * @return {undefined}\n" +
" * @constructor\n" +
" */\n" +
"a.Foo = function() {\n" +
"};\n" +
"/**\n" +
" * @return {undefined}\n" +
" * @javadispatch\n" +
" */\n" +
"a.Foo.prototype.foo = function() {\n" +
"};\n");
}
public void testU2UFunctionTypeAnnotation() {
assertTypeAnnotations(
"/** @type {!Function} */ var x = function() {}",
"/**\n * @constructor\n */\nvar x = function() {\n};\n");
}
public void testEmitUnknownParamTypesAsAllType() {
assertTypeAnnotations(
"var a = function(x) {}",
"/**\n" +
" * @param {*} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\n};\n");
}
public void testOptionalTypesAnnotation() {
assertTypeAnnotations(
"/**\n" +
" * @param {string=} x \n" +
" */\n" +
"var a = function(x) {}",
"/**\n" +
" * @param {string=} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\n};\n");
}
public void testVariableArgumentsTypesAnnotation() {
assertTypeAnnotations(
"/**\n" +
" * @param {...string} x \n" +
" */\n" +
"var a = function(x) {}",
"/**\n" +
" * @param {...string} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\n};\n");
}
public void testTempConstructor() {
assertTypeAnnotations(
"var x = function() {\n/**\n * @constructor\n */\nfunction t1() {}\n" +
" /**\n * @constructor\n */\nfunction t2() {}\n" +
" t1.prototype = t2.prototype}",
"/**\n * @return {undefined}\n */\nvar x = function() {\n" +
" /**\n * @return {undefined}\n * @constructor\n */\n" +
"function t1() {\n }\n" +
" /**\n * @return {undefined}\n * @constructor\n */\n" +
"function t2() {\n }\n" +
" t1.prototype = t2.prototype\n};\n"
);
}
private void assertPrettyPrint(String js, String expected) {
assertEquals(expected,
parsePrint(js, true, false,
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD));
}
private void assertTypeAnnotations(String js, String expected) {
assertEquals(expected,
parsePrint(js, true, false,
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD, true));
}
public void testSubtraction() {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode("x - -4");
assertEquals(0, compiler.getErrorCount());
assertEquals(
"x- -4",
new CodePrinter.Builder(n).setLineLengthThreshold(
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build());
}
public void testFunctionWithCall() {
assertPrint(
"var user = new function() {"
+ "alert(\"foo\")}",
"var user=new function(){"
+ "alert(\"foo\")}");
assertPrint(
"var user = new function() {"
+ "this.name = \"foo\";"
+ "this.local = function(){alert(this.name)};}",
"var user=new function(){"
+ "this.name=\"foo\";"
+ "this.local=function(){alert(this.name)}}");
}
public void testLineLength() {
// list
assertLineLength("var aba,bcb,cdc",
"var aba,bcb," +
"\ncdc");
// operators, and two breaks
assertLineLength(
"\"foo\"+\"bar,baz,bomb\"+\"whee\"+\";long-string\"\n+\"aaa\"",
"\"foo\"+\"bar,baz,bomb\"+" +
"\n\"whee\"+\";long-string\"+" +
"\n\"aaa\"");
// assignment
assertLineLength("var abazaba=1234",
"var abazaba=" +
"\n1234");
// statements
assertLineLength("var abab=1;var bab=2",
"var abab=1;" +
"\nvar bab=2");
// don't break regexes
assertLineLength("var a=/some[reg](ex),with.*we?rd|chars/i;var b=a",
"var a=/some[reg](ex),with.*we?rd|chars/i;" +
"\nvar b=a");
// don't break strings
assertLineLength("var a=\"foo,{bar};baz\";var b=a",
"var a=\"foo,{bar};baz\";" +
"\nvar b=a");
// don't break before post inc/dec
assertLineLength("var a=\"a\";a++;var b=\"bbb\";",
"var a=\"a\";a++;\n" +
"var b=\"bbb\"");
}
private void assertLineLength(String js, String expected) {
assertEquals(expected,
parsePrint(js, false, true, 10));
}
public void testParsePrintParse() {
testReparse("3;");
testReparse("var a = b;");
testReparse("var x, y, z;");
testReparse("try { foo() } catch(e) { bar() }");
testReparse("try { foo() } catch(e) { bar() } finally { stuff() }");
testReparse("try { foo() } finally { stuff() }");
testReparse("throw 'me'");
testReparse("function foo(a) { return a + 4; }");
testReparse("function foo() { return; }");
testReparse("var a = function(a, b) { foo(); return a + b; }");
testReparse("b = [3, 4, 'paul', \"Buchhe it\",,5];");
testReparse("v = (5, 6, 7, 8)");
testReparse("d = 34.0; x = 0; y = .3; z = -22");
testReparse("d = -x; t = !x + ~y;");
testReparse("'hi'; /* just a test */ stuff(a,b) \n" +
" foo(); // and another \n" +
" bar();");
testReparse("a = b++ + ++c; a = b++-++c; a = - --b; a = - ++b;");
testReparse("a++; b= a++; b = ++a; b = a--; b = --a; a+=2; b-=5");
testReparse("a = (2 + 3) * 4;");
testReparse("a = 1 + (2 + 3) + 4;");
testReparse("x = a ? b : c; x = a ? (b,3,5) : (foo(),bar());");
testReparse("a = b | c || d ^ e " +
"&& f & !g != h << i <= j < k >>> l > m * n % !o");
testReparse("a == b; a != b; a === b; a == b == a;" +
" (a == b) == a; a == (b == a);");
testReparse("if (a > b) a = b; if (b < 3) a = 3; else c = 4;");
testReparse("if (a == b) { a++; } if (a == 0) { a++; } else { a --; }");
testReparse("for (var i in a) b += i;");
testReparse("for (var i = 0; i < 10; i++){ b /= 2;" +
" if (b == 2)break;else continue;}");
testReparse("for (x = 0; x < 10; x++) a /= 2;");
testReparse("for (;;) a++;");
testReparse("while(true) { blah(); }while(true) blah();");
testReparse("do stuff(); while(a>b);");
testReparse("[0, null, , true, false, this];");
testReparse("s.replace(/absc/, 'X').replace(/ab/gi, 'Y');");
testReparse("new Foo; new Bar(a, b,c);");
testReparse("with(foo()) { x = z; y = t; } with(bar()) a = z;");
testReparse("delete foo['bar']; delete foo;");
testReparse("var x = { 'a':'paul', 1:'3', 2:(3,4) };");
testReparse("switch(a) { case 2: case 3: stuff(); break;" +
"case 4: morestuff(); break; default: done();}");
testReparse("x = foo['bar'] + foo['my stuff'] + foo[bar] + f.stuff;");
testReparse("a.v = b.v; x['foo'] = y['zoo'];");
testReparse("'test' in x; 3 in x; a in x;");
testReparse("'foo\"bar' + \"foo'c\" + 'stuff\\n and \\\\more'");
testReparse("x.__proto__;");
}
private void testReparse(String code) {
Compiler compiler = new Compiler();
Node parse1 = parse(code);
Node parse2 = parse(new CodePrinter.Builder(parse1).build());
String explanation = parse1.checkTreeEquals(parse2);
assertNull("\nExpected: " + compiler.toSource(parse1) +
"\nResult: " + compiler.toSource(parse2) +
"\n" + explanation, explanation);
}
public void testDoLoopIECompatiblity() {
// Do loops within IFs cause syntax errors in IE6 and IE7.
assertPrint("function f(){if(e1){do foo();while(e2)}else foo()}",
"function f(){if(e1){do foo();while(e2)}else foo()}");
assertPrint("function f(){if(e1)do foo();while(e2)else foo()}",
"function f(){if(e1){do foo();while(e2)}else foo()}");
assertPrint("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
assertPrint("if(x)do{foo()}while(y);else bar()",
"if(x){do foo();while(y)}else bar()");
assertPrint("if(x){do{foo()}while(y)}",
"if(x){do foo();while(y)}");
assertPrint("if(x)do{foo()}while(y);",
"if(x){do foo();while(y)}");
assertPrint("if(x)A:do{foo()}while(y);",
"if(x){A:do foo();while(y)}");
assertPrint("var i = 0;a: do{b: do{i++;break b;} while(0);} while(0);",
"var i=0;a:do{b:do{i++;break b}while(0)}while(0)");
}
public void testFunctionSafariCompatiblity() {
// Functions within IFs cause syntax errors on Safari.
assertPrint("function f(){if(e1){function goo(){return true}}else foo()}",
"function f(){if(e1){function goo(){return true}}else foo()}");
assertPrint("function f(){if(e1)function goo(){return true}else foo()}",
"function f(){if(e1){function goo(){return true}}else foo()}");
assertPrint("if(e1){function goo(){return true}}",
"if(e1){function goo(){return true}}");
assertPrint("if(e1)function goo(){return true}",
"if(e1){function goo(){return true}}");
assertPrint("if(e1)A:function goo(){return true}",
"if(e1){A:function goo(){return true}}");
}
public void testExponents() {
assertPrintNumber("1", 1);
assertPrintNumber("10", 10);
assertPrintNumber("100", 100);
assertPrintNumber("1E3", 1000);
assertPrintNumber("1E4", 10000);
assertPrintNumber("1E5", 100000);
assertPrintNumber("-1", -1);
assertPrintNumber("-10", -10);
assertPrintNumber("-100", -100);
assertPrintNumber("-1E3", -1000);
assertPrintNumber("-12341234E4", -123412340000L);
assertPrintNumber("1E18", 1000000000000000000L);
assertPrintNumber("1E5", 100000.0);
assertPrintNumber("100000.1", 100000.1);
assertPrintNumber("1.0E-6", 0.000001);
}
// Make sure to test as both a String and a Node, because
// negative numbers do not parse consistently from strings.
private void assertPrintNumber(String expected, double number) {
assertPrint(String.valueOf(number), expected);
assertPrintNode(expected, Node.newNumber(number));
}
private void assertPrintNumber(String expected, int number) {
assertPrint(String.valueOf(number), expected);
assertPrintNode(expected, Node.newNumber(number));
}
public void testDirectEval() {
assertPrint("eval('1');", "eval(\"1\")");
}
public void testIndirectEval() {
Node n = parse("eval('1');");
assertPrintNode("eval(\"1\")", n);
n.getFirstChild().getFirstChild().getFirstChild().putBooleanProp(
Node.DIRECT_EVAL, false);
assertPrintNode("(0,eval)(\"1\")", n);
}
public void testFreeCall1() {
assertPrint("foo(a);", "foo(a)");
assertPrint("x.foo(a);", "x.foo(a)");
}
public void testFreeCall2() {
Node n = parse("foo(a);");
assertPrintNode("foo(a)", n);
Node call = n.getFirstChild().getFirstChild();
assertTrue(call.getType() == Token.CALL);
call.putBooleanProp(Node.FREE_CALL, true);
assertPrintNode("foo(a)", n);
}
public void testFreeCall3() {
Node n = parse("x.foo(a);");
assertPrintNode("x.foo(a)", n);
Node call = n.getFirstChild().getFirstChild();
assertTrue(call.getType() == Token.CALL);
call.putBooleanProp(Node.FREE_CALL, true);
assertPrintNode("(0,x.foo)(a)", n);
}
public void testPrintScript() {
// Verify that SCRIPT nodes not marked as synthetic are printed as
// blocks.
Node ast = new Node(Token.SCRIPT,
new Node(Token.EXPR_RESULT, Node.newString("f")),
new Node(Token.EXPR_RESULT, Node.newString("g")));
String result = new CodePrinter.Builder(ast).setPrettyPrint(true).build();
assertEquals("\"f\";\n\"g\";\n", result);
}
public void testObjectLit() {
assertPrint("({x:1})", "({x:1})");
assertPrint("var x=({x:1})", "var x={x:1}");
assertPrint("var x={'x':1}", "var x={\"x\":1}");
assertPrint("var x={1:1}", "var x={1:1}");
}
public void 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 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=\"\\0\"");
assertPrint("var x ='\\x00';", "var x=\"\\0\"");
assertPrint("var x ='\\u0000';", "var x=\"\\0\"");
}
public void testUnicode() {
assertPrint("var x ='\\x0f';", "var x=\"\\u000f\"");
assertPrint("var x ='\\x68';", "var x=\"h\"");
assertPrint("var x ='\\x7f';", "var x=\"\\u007f\"");
}
} |
||
@Test
public void polynomial() throws DerivativeException, IntegratorException {
TestProblem6 pb = new TestProblem6();
double range = Math.abs(pb.getFinalTime() - pb.getInitialTime());
for (int nSteps = 1; nSteps < 7; ++nSteps) {
AdamsMoultonIntegrator integ =
new AdamsMoultonIntegrator(nSteps, 1.0e-6 * range, 0.1 * range, 1.0e-9, 1.0e-9);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
if (nSteps < 4) {
assertTrue(integ.getEvaluations() > 140);
} else {
assertTrue(integ.getEvaluations() < 90);
}
}
} | org.apache.commons.math.ode.nonstiff.AdamsMoultonIntegratorTest::polynomial | src/test/java/org/apache/commons/math/ode/nonstiff/AdamsMoultonIntegratorTest.java | 153 | src/test/java/org/apache/commons/math/ode/nonstiff/AdamsMoultonIntegratorTest.java | polynomial | /*
* 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.ode.nonstiff;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.math.ode.DerivativeException;
import org.apache.commons.math.ode.FirstOrderIntegrator;
import org.apache.commons.math.ode.IntegratorException;
import org.apache.commons.math.ode.TestProblem1;
import org.apache.commons.math.ode.TestProblem5;
import org.apache.commons.math.ode.TestProblem6;
import org.apache.commons.math.ode.TestProblemHandler;
import org.junit.Test;
public class AdamsMoultonIntegratorTest {
@Test(expected=IntegratorException.class)
public void dimensionCheck() throws DerivativeException, IntegratorException {
TestProblem1 pb = new TestProblem1();
FirstOrderIntegrator integ =
new AdamsMoultonIntegrator(2, 0.0, 1.0, 1.0e-10, 1.0e-10);
integ.integrate(pb,
0.0, new double[pb.getDimension()+10],
1.0, new double[pb.getDimension()+10]);
}
@Test(expected=IntegratorException.class)
public void testMinStep() throws DerivativeException, IntegratorException {
TestProblem1 pb = new TestProblem1();
double minStep = 0.1 * (pb.getFinalTime() - pb.getInitialTime());
double maxStep = pb.getFinalTime() - pb.getInitialTime();
double[] vecAbsoluteTolerance = { 1.0e-15, 1.0e-16 };
double[] vecRelativeTolerance = { 1.0e-15, 1.0e-16 };
FirstOrderIntegrator integ = new AdamsMoultonIntegrator(4, minStep, maxStep,
vecAbsoluteTolerance,
vecRelativeTolerance);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb,
pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
}
@Test
public void testIncreasingTolerance()
throws DerivativeException, IntegratorException {
int previousCalls = Integer.MAX_VALUE;
for (int i = -12; i < -2; ++i) {
TestProblem1 pb = new TestProblem1();
double minStep = 0;
double maxStep = pb.getFinalTime() - pb.getInitialTime();
double scalAbsoluteTolerance = Math.pow(10.0, i);
double scalRelativeTolerance = 0.01 * scalAbsoluteTolerance;
FirstOrderIntegrator integ = new AdamsMoultonIntegrator(4, minStep, maxStep,
scalAbsoluteTolerance,
scalRelativeTolerance);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb,
pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
// the 0.15 and 3.0 factors are only valid for this test
// and has been obtained from trial and error
// there is no general relation between local and global errors
assertTrue(handler.getMaximalValueError() > (0.15 * scalAbsoluteTolerance));
assertTrue(handler.getMaximalValueError() < (3.0 * scalAbsoluteTolerance));
assertEquals(0, handler.getMaximalTimeError(), 1.0e-16);
int calls = pb.getCalls();
assertEquals(integ.getEvaluations(), calls);
assertTrue(calls <= previousCalls);
previousCalls = calls;
}
}
@Test(expected = DerivativeException.class)
public void exceedMaxEvaluations() throws DerivativeException, IntegratorException {
TestProblem1 pb = new TestProblem1();
double range = pb.getFinalTime() - pb.getInitialTime();
AdamsMoultonIntegrator integ = new AdamsMoultonIntegrator(2, 0, range, 1.0e-12, 1.0e-12);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.setMaxEvaluations(650);
integ.integrate(pb,
pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
}
@Test
public void backward() throws DerivativeException, IntegratorException {
TestProblem5 pb = new TestProblem5();
double range = Math.abs(pb.getFinalTime() - pb.getInitialTime());
FirstOrderIntegrator integ = new AdamsMoultonIntegrator(4, 0, range, 1.0e-12, 1.0e-12);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
assertTrue(handler.getLastError() < 1.0e-9);
assertTrue(handler.getMaximalValueError() < 1.0e-9);
assertEquals(0, handler.getMaximalTimeError(), 1.0e-16);
assertEquals("Adams-Moulton", integ.getName());
}
@Test
public void polynomial() throws DerivativeException, IntegratorException {
TestProblem6 pb = new TestProblem6();
double range = Math.abs(pb.getFinalTime() - pb.getInitialTime());
for (int nSteps = 1; nSteps < 7; ++nSteps) {
AdamsMoultonIntegrator integ =
new AdamsMoultonIntegrator(nSteps, 1.0e-6 * range, 0.1 * range, 1.0e-9, 1.0e-9);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
if (nSteps < 4) {
assertTrue(integ.getEvaluations() > 140);
} else {
assertTrue(integ.getEvaluations() < 90);
}
}
}
} | // You are a professional Java test case writer, please create a test case named `polynomial` for the issue `Math-MATH-338`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-338
//
// ## Issue-Title:
// Wrong parameter for first step size guess for Embedded Runge Kutta methods
//
// ## Issue-Description:
//
// In a space application using DOP853 i detected what seems to be a bad parameter in the call to the method initializeStep of class AdaptiveStepsizeIntegrator.
//
//
// Here, DormandPrince853Integrator is a subclass for EmbeddedRungeKuttaIntegrator which perform the call to initializeStep at the beginning of its method integrate(...)
//
//
// The problem comes from the array "scale" that is used as a parameter in the call off initializeStep(..)
//
//
// Following the theory described by Hairer in his book "Solving Ordinary Differential Equations 1 : Nonstiff Problems", the scaling should be :
//
//
// sci = Atol i + |y0i| \* Rtoli
//
//
// Whereas EmbeddedRungeKuttaIntegrator uses : sci = Atoli
//
//
// Note that the Gragg-Bulirsch-Stoer integrator uses the good implementation "sci = Atol i + |y0i| \* Rtoli " when he performs the call to the same method initializeStep(..)
//
//
// In the method initializeStep, the error leads to a wrong step size h used to perform an Euler step. Most of the time it is unvisible for the user.
//
// But in my space application the Euler step with this wrong step size h (much bigger than it should be) makes an exception occur (my satellite hits the ground...)
//
//
// To fix the bug, one should use the same algorithm as in the rescale method in GraggBulirschStoerIntegrator
//
// For exemple :
//
//
// final double[] scale= new double[y0.length];;
//
//
// if (vecAbsoluteTolerance == null) {
//
// for (int i = 0; i < scale.length; ++i)
//
//
// {
// final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));
// scale[i] = scalAbsoluteTolerance + scalRelativeTolerance \* yi;
// }
// } else {
//
// for (int i = 0; i < scale.length; ++i)
//
//
// {
// final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));
// scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] \* yi;
// }
// }
//
//
// hNew = initializeStep(equations, forward, getOrder(), scale,
//
// stepStart, y, yDotK[0], yTmp, yDotK[1]);
//
//
// Sorry for the length of this message, looking forward to hearing from you soon
//
//
// Vincent Morand
//
//
//
//
//
@Test
public void polynomial() throws DerivativeException, IntegratorException {
| 153 | 74 | 134 | src/test/java/org/apache/commons/math/ode/nonstiff/AdamsMoultonIntegratorTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-338
## Issue-Title:
Wrong parameter for first step size guess for Embedded Runge Kutta methods
## Issue-Description:
In a space application using DOP853 i detected what seems to be a bad parameter in the call to the method initializeStep of class AdaptiveStepsizeIntegrator.
Here, DormandPrince853Integrator is a subclass for EmbeddedRungeKuttaIntegrator which perform the call to initializeStep at the beginning of its method integrate(...)
The problem comes from the array "scale" that is used as a parameter in the call off initializeStep(..)
Following the theory described by Hairer in his book "Solving Ordinary Differential Equations 1 : Nonstiff Problems", the scaling should be :
sci = Atol i + |y0i| \* Rtoli
Whereas EmbeddedRungeKuttaIntegrator uses : sci = Atoli
Note that the Gragg-Bulirsch-Stoer integrator uses the good implementation "sci = Atol i + |y0i| \* Rtoli " when he performs the call to the same method initializeStep(..)
In the method initializeStep, the error leads to a wrong step size h used to perform an Euler step. Most of the time it is unvisible for the user.
But in my space application the Euler step with this wrong step size h (much bigger than it should be) makes an exception occur (my satellite hits the ground...)
To fix the bug, one should use the same algorithm as in the rescale method in GraggBulirschStoerIntegrator
For exemple :
final double[] scale= new double[y0.length];;
if (vecAbsoluteTolerance == null) {
for (int i = 0; i < scale.length; ++i)
{
final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));
scale[i] = scalAbsoluteTolerance + scalRelativeTolerance \* yi;
}
} else {
for (int i = 0; i < scale.length; ++i)
{
final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));
scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] \* yi;
}
}
hNew = initializeStep(equations, forward, getOrder(), scale,
stepStart, y, yDotK[0], yTmp, yDotK[1]);
Sorry for the length of this message, looking forward to hearing from you soon
Vincent Morand
```
You are a professional Java test case writer, please create a test case named `polynomial` for the issue `Math-MATH-338`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void polynomial() throws DerivativeException, IntegratorException {
```
| 134 | [
"org.apache.commons.math.ode.nonstiff.EmbeddedRungeKuttaIntegrator"
] | 3a1124eeb1894e82ae4619a9d5206b37cf7fe8118033242dd3cea6657629fc67 | @Test
public void polynomial() throws DerivativeException, IntegratorException | // You are a professional Java test case writer, please create a test case named `polynomial` for the issue `Math-MATH-338`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-338
//
// ## Issue-Title:
// Wrong parameter for first step size guess for Embedded Runge Kutta methods
//
// ## Issue-Description:
//
// In a space application using DOP853 i detected what seems to be a bad parameter in the call to the method initializeStep of class AdaptiveStepsizeIntegrator.
//
//
// Here, DormandPrince853Integrator is a subclass for EmbeddedRungeKuttaIntegrator which perform the call to initializeStep at the beginning of its method integrate(...)
//
//
// The problem comes from the array "scale" that is used as a parameter in the call off initializeStep(..)
//
//
// Following the theory described by Hairer in his book "Solving Ordinary Differential Equations 1 : Nonstiff Problems", the scaling should be :
//
//
// sci = Atol i + |y0i| \* Rtoli
//
//
// Whereas EmbeddedRungeKuttaIntegrator uses : sci = Atoli
//
//
// Note that the Gragg-Bulirsch-Stoer integrator uses the good implementation "sci = Atol i + |y0i| \* Rtoli " when he performs the call to the same method initializeStep(..)
//
//
// In the method initializeStep, the error leads to a wrong step size h used to perform an Euler step. Most of the time it is unvisible for the user.
//
// But in my space application the Euler step with this wrong step size h (much bigger than it should be) makes an exception occur (my satellite hits the ground...)
//
//
// To fix the bug, one should use the same algorithm as in the rescale method in GraggBulirschStoerIntegrator
//
// For exemple :
//
//
// final double[] scale= new double[y0.length];;
//
//
// if (vecAbsoluteTolerance == null) {
//
// for (int i = 0; i < scale.length; ++i)
//
//
// {
// final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));
// scale[i] = scalAbsoluteTolerance + scalRelativeTolerance \* yi;
// }
// } else {
//
// for (int i = 0; i < scale.length; ++i)
//
//
// {
// final double yi = Math.max(Math.abs(y0[i]), Math.abs(y0[i]));
// scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] \* yi;
// }
// }
//
//
// hNew = initializeStep(equations, forward, getOrder(), scale,
//
// stepStart, y, yDotK[0], yTmp, yDotK[1]);
//
//
// Sorry for the length of this message, looking forward to hearing from you soon
//
//
// Vincent Morand
//
//
//
//
//
| 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.ode.nonstiff;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.math.ode.DerivativeException;
import org.apache.commons.math.ode.FirstOrderIntegrator;
import org.apache.commons.math.ode.IntegratorException;
import org.apache.commons.math.ode.TestProblem1;
import org.apache.commons.math.ode.TestProblem5;
import org.apache.commons.math.ode.TestProblem6;
import org.apache.commons.math.ode.TestProblemHandler;
import org.junit.Test;
public class AdamsMoultonIntegratorTest {
@Test(expected=IntegratorException.class)
public void dimensionCheck() throws DerivativeException, IntegratorException {
TestProblem1 pb = new TestProblem1();
FirstOrderIntegrator integ =
new AdamsMoultonIntegrator(2, 0.0, 1.0, 1.0e-10, 1.0e-10);
integ.integrate(pb,
0.0, new double[pb.getDimension()+10],
1.0, new double[pb.getDimension()+10]);
}
@Test(expected=IntegratorException.class)
public void testMinStep() throws DerivativeException, IntegratorException {
TestProblem1 pb = new TestProblem1();
double minStep = 0.1 * (pb.getFinalTime() - pb.getInitialTime());
double maxStep = pb.getFinalTime() - pb.getInitialTime();
double[] vecAbsoluteTolerance = { 1.0e-15, 1.0e-16 };
double[] vecRelativeTolerance = { 1.0e-15, 1.0e-16 };
FirstOrderIntegrator integ = new AdamsMoultonIntegrator(4, minStep, maxStep,
vecAbsoluteTolerance,
vecRelativeTolerance);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb,
pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
}
@Test
public void testIncreasingTolerance()
throws DerivativeException, IntegratorException {
int previousCalls = Integer.MAX_VALUE;
for (int i = -12; i < -2; ++i) {
TestProblem1 pb = new TestProblem1();
double minStep = 0;
double maxStep = pb.getFinalTime() - pb.getInitialTime();
double scalAbsoluteTolerance = Math.pow(10.0, i);
double scalRelativeTolerance = 0.01 * scalAbsoluteTolerance;
FirstOrderIntegrator integ = new AdamsMoultonIntegrator(4, minStep, maxStep,
scalAbsoluteTolerance,
scalRelativeTolerance);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb,
pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
// the 0.15 and 3.0 factors are only valid for this test
// and has been obtained from trial and error
// there is no general relation between local and global errors
assertTrue(handler.getMaximalValueError() > (0.15 * scalAbsoluteTolerance));
assertTrue(handler.getMaximalValueError() < (3.0 * scalAbsoluteTolerance));
assertEquals(0, handler.getMaximalTimeError(), 1.0e-16);
int calls = pb.getCalls();
assertEquals(integ.getEvaluations(), calls);
assertTrue(calls <= previousCalls);
previousCalls = calls;
}
}
@Test(expected = DerivativeException.class)
public void exceedMaxEvaluations() throws DerivativeException, IntegratorException {
TestProblem1 pb = new TestProblem1();
double range = pb.getFinalTime() - pb.getInitialTime();
AdamsMoultonIntegrator integ = new AdamsMoultonIntegrator(2, 0, range, 1.0e-12, 1.0e-12);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.setMaxEvaluations(650);
integ.integrate(pb,
pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
}
@Test
public void backward() throws DerivativeException, IntegratorException {
TestProblem5 pb = new TestProblem5();
double range = Math.abs(pb.getFinalTime() - pb.getInitialTime());
FirstOrderIntegrator integ = new AdamsMoultonIntegrator(4, 0, range, 1.0e-12, 1.0e-12);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
assertTrue(handler.getLastError() < 1.0e-9);
assertTrue(handler.getMaximalValueError() < 1.0e-9);
assertEquals(0, handler.getMaximalTimeError(), 1.0e-16);
assertEquals("Adams-Moulton", integ.getName());
}
@Test
public void polynomial() throws DerivativeException, IntegratorException {
TestProblem6 pb = new TestProblem6();
double range = Math.abs(pb.getFinalTime() - pb.getInitialTime());
for (int nSteps = 1; nSteps < 7; ++nSteps) {
AdamsMoultonIntegrator integ =
new AdamsMoultonIntegrator(nSteps, 1.0e-6 * range, 0.1 * range, 1.0e-9, 1.0e-9);
TestProblemHandler handler = new TestProblemHandler(pb, integ);
integ.addStepHandler(handler);
integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(),
pb.getFinalTime(), new double[pb.getDimension()]);
if (nSteps < 4) {
assertTrue(integ.getEvaluations() > 140);
} else {
assertTrue(integ.getEvaluations() < 90);
}
}
}
} |
||
public void testSimpleForIn() {
inline("var a,b,x = a in b; x",
"var a,b,x; a in b");
noInline("var a, b; var x = a in b; print(1); x");
noInline("var a,b,x = a in b; delete a[b]; x");
} | com.google.javascript.jscomp.FlowSensitiveInlineVariablesTest::testSimpleForIn | test/com/google/javascript/jscomp/FlowSensitiveInlineVariablesTest.java | 68 | test/com/google/javascript/jscomp/FlowSensitiveInlineVariablesTest.java | testSimpleForIn | /*
* 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.javascript.rhino.Node;
/**
* Unit tests for {@link FlowSensitiveInlineVariables}.
*
*/
public class FlowSensitiveInlineVariablesTest extends CompilerTestCase {
public static final String EXTERN_FUNCTIONS = "" +
"var print;\n" +
"/** @nosideeffects */ function noSFX() {} \n" +
" function hasSFX() {} \n";
@Override
public int getNumRepetitions() {
// Test repeatedly inline.
return 3;
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
//return new FlowSensitiveInlineVariables(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
(new MarkNoSideEffectCalls(compiler)).process(externs, root);
(new FlowSensitiveInlineVariables(compiler)).process(externs, root);
}
};
}
public void testSimpleAssign() {
inline("var x; x = 1; print(x)", "var x; print(1)");
inline("var x; x = 1; x", "var x; 1");
inline("var x; x = 1; var a = x", "var x; var a = 1");
inline("var x; x = 1; x = x + 1", "var x; x = 1 + 1");
}
public void testSimpleVar() {
inline("var x = 1; print(x)", "var x; print(1)");
inline("var x = 1; x", "var x; 1");
inline("var x = 1; var a = x", "var x; var a = 1");
inline("var x = 1; x = x + 1", "var x; x = 1 + 1");
}
public void testSimpleForIn() {
inline("var a,b,x = a in b; x",
"var a,b,x; a in b");
noInline("var a, b; var x = a in b; print(1); x");
noInline("var a,b,x = a in b; delete a[b]; x");
}
public void testExported() {
noInline("var _x = 1; print(_x)");
}
public void testDoNotInlineIncrement() {
noInline("var x = 1; x++;");
noInline("var x = 1; x--;");
}
public void testDoNotInlineAssignmentOp() {
noInline("var x = 1; x += 1;");
noInline("var x = 1; x -= 1;");
}
public void testDoNotInlineIntoLhsOfAssign() {
noInline("var x = 1; x += 3;");
}
public void testMultiUse() {
noInline("var x; x = 1; print(x); print (x);");
}
public void testMultiUseInSameCfgNode() {
noInline("var x; x = 1; print(x) || print (x);");
}
public void testMultiUseInTwoDifferentPath() {
noInline("var x = 1; if (print) { print(x) } else { alert(x) }");
}
public void testAssignmentBeforeDefinition() {
inline("x = 1; var x = 0; print(x)","x = 1; var x; print(0)" );
}
public void testVarInConditionPath() {
noInline("if (foo) { var x = 0 } print(x)");
}
public void testMultiDefinitionsBeforeUse() {
inline("var x = 0; x = 1; print(x)", "var x = 0; print(1)");
}
public void testMultiDefinitionsInSameCfgNode() {
noInline("var x; (x = 1) || (x = 2); print(x)");
noInline("var x; x = (1 || (x = 2)); print(x)");
noInline("var x;(x = 1) && (x = 2); print(x)");
noInline("var x;x = (1 && (x = 2)); print(x)");
noInline("var x; x = 1 , x = 2; print(x)");
}
public void testNotReachingDefinitions() {
noInline("var x; if (foo) { x = 0 } print (x)");
}
public void testNoInlineLoopCarriedDefinition() {
// First print is undefined instead.
noInline("var x; while(true) { print(x); x = 1; }");
// Prints 0 1 1 1 1....
noInline("var x = 0; while(true) { print(x); x = 1; }");
}
public void testDoNotExitLoop() {
noInline("while (z) { var x = 3; } var y = x;");
}
public void testDoNotInlineWithinLoop() {
noInline("var y = noSFX(); do { var z = y.foo(); } while (true);");
}
public void testDefinitionAfterUse() {
inline("var x = 0; print(x); x = 1", "var x; print(0); x = 1");
}
public void testInlineSameVariableInStraightLine() {
inline("var x; x = 1; print(x); x = 2; print(x)",
"var x; print(1); print(2)");
}
public void testInlineInDifferentPaths() {
inline("var x; if (print) {x = 1; print(x)} else {x = 2; print(x)}",
"var x; if (print) {print(1)} else {print(2)}");
}
public void testNoInlineInMergedPath() {
noInline(
"var x,y;x = 1;while(y) { if(y){ print(x) } else { x = 1 } } print(x)");
}
public void testInlineIntoExpressions() {
inline("var x = 1; print(x + 1);", "var x; print(1 + 1)");
}
public void testInlineExpressions1() {
inline("var a, b; var x = a+b; print(x)", "var a, b; var x; print(a+b)");
}
public void testInlineExpressions2() {
// We can't inline because of the redefinition of "a".
noInline("var a, b; var x = a + b; a = 1; print(x)");
}
public void testInlineExpressions3() {
inline("var a,b,x; x=a+b; x=a-b ; print(x)",
"var a,b,x; x=a+b; print(a-b)");
}
public void testInlineExpressions4() {
// Precision is lost due to comma's.
noInline("var a,b,x; x=a+b, x=a-b; print(x)");
}
public void testInlineExpressions5() {
noInline("var a; var x = a = 1; print(x)");
}
public void testInlineExpressions6() {
noInline("var a, x; a = 1 + (x = 1); print(x)");
}
public void testInlineExpression7() {
// Possible side effects in foo() that might conflict with bar();
noInline("var x = foo() + 1; bar(); print(x)");
// This is a possible case but we don't have analysis to prove this yet.
// TODO(user): It is possible to cover this case with the same algorithm
// as the missing return check.
noInline("var x = foo() + 1; print(x)");
}
public void testInlineExpression8() {
// The same variable inlined twice.
inline(
"var a,b;" +
"var x = a + b; print(x); x = a - b; print(x)",
"var a,b;" +
"var x; print(a + b); print(a - b)");
}
public void testInlineExpression9() {
// Check for actual control flow sensitivity.
inline(
"var a,b;" +
"var x; if (g) { x= a + b; print(x) } x = a - b; print(x)",
"var a,b;" +
"var x; if (g) { print(a + b)} print(a - b)");
}
public void testInlineExpression10() {
// The DFA is not fine grain enough for this.
noInline("var x, y; x = ((y = 1), print(y))");
}
public void testInlineExpressions11() {
inline("var x; x = x + 1; print(x)", "var x; print(x + 1)");
noInline("var x; x = x + 1; print(x); print(x)");
}
public void testInlineExpressions12() {
// ++ is an assignment and considered to modify state so it will not be
// inlined.
noInline("var x = 10; x = c++; print(x)");
}
public void testInlineExpressions13() {
inline("var a = 1, b = 2;" +
"var x = a;" +
"var y = b;" +
"var z = x + y;" +
"var i = z;" +
"var j = z + y;" +
"var k = i;",
"var a, b;" +
"var x;" +
"var y = 2;" +
"var z = 1 + y;" +
"var i;" +
"var j = z + y;" +
"var k = z;");
}
public void testNoInlineIfDefinitionMayNotReach() {
noInline("var x; if (x=1) {} x;");
}
public void testNoInlineEscapedToInnerFunction() {
noInline("var x = 1; function foo() { x = 2 }; print(x)");
}
public void testNoInlineLValue() {
noInline("var x; if (x = 1) { print(x) }");
}
public void testSwitchCase() {
inline("var x = 1; switch(x) { }", "var x; switch(1) { }");
}
public void testShadowedVariableInnerFunction() {
inline("var x = 1; print(x) || (function() { var x; x = 1; print(x)})()",
"var x; print(1) || (function() { var x; print(1)})()");
}
public void testCatch() {
noInline("var x = 0; try { } catch (x) { }");
noInline("try { } catch (x) { print(x) }");
}
public void testNoInlineGetProp() {
// We don't know if j alias a.b
noInline("var x = a.b.c; j.c = 1; print(x);");
}
public void testNoInlineGetProp2() {
noInline("var x = 1 * a.b.c; j.c = 1; print(x);");
}
public void testNoInlineGetProp3() {
// Anything inside a function is fine.
inline("var x = function(){1 * a.b.c}; print(x);",
"var x; print(function(){1 * a.b.c});");
}
public void testNoInlineGetEle() {
// Again we don't know if i = j
noInline("var x = a[i]; a[j] = 2; print(x); ");
}
// TODO(user): These should be inlinable.
public void testNoInlineConstructors() {
noInline("var x = new Iterator(); x.next();");
}
// TODO(user): These should be inlinable.
public void testNoInlineArrayLits() {
noInline("var x = []; print(x)");
}
// TODO(user): These should be inlinable.
public void testNoInlineObjectLits() {
noInline("var x = {}; print(x)");
}
// TODO(user): These should be inlinable after the REGEX checks.
public void testNoInlineRegExpLits() {
noInline("var x = /y/; print(x)");
}
public void testInlineConstructorCallsIntoLoop() {
// Don't inline construction into loops.
noInline("var x = new Iterator();" +
"for(i = 0; i < 10; i++) {j = x.next()}");
}
public void testRemoveWithLabels() {
inline("var x = 1; L: x = 2; print(x)", "var x = 1; print(2)");
inline("var x = 1; L: M: x = 2; print(x)", "var x = 1; print(2)");
inline("var x = 1; L: M: N: x = 2; print(x)", "var x = 1; print(2)");
}
public void testInlineAcrossSideEffect1() {
// This can't be inlined because print() has side-effects and might change
// the definition of noSFX.
//
// noSFX must be both const and pure in order to inline it.
noInline("var y; var x = noSFX(y); print(x)");
//inline("var y; var x = noSFX(y); print(x)", "var y;var x;print(noSFX(y))");
}
public void testInlineAcrossSideEffect2() {
// Think noSFX() as a function that reads y.foo and return it
// and SFX() write some new value of y.foo. If that's the case,
// inlining across hasSFX() is not valid.
// This is a case where hasSFX is right of the source of the inlining.
noInline("var y; var x = noSFX(y), z = hasSFX(y); print(x)");
noInline("var y; var x = noSFX(y), z = new hasSFX(y); print(x)");
noInline("var y; var x = new noSFX(y), z = new hasSFX(y); print(x)");
}
public void testInlineAcrossSideEffect3() {
// This is a case where hasSFX is left of the destination of the inlining.
noInline("var y; var x = noSFX(y); hasSFX(y), print(x)");
noInline("var y; var x = noSFX(y); new hasSFX(y), print(x)");
noInline("var y; var x = new noSFX(y); new hasSFX(y), print(x)");
}
public void testInlineAcrossSideEffect4() {
// This is a case where hasSFX is some control flow path between the
// source and its destination.
noInline("var y; var x = noSFX(y); hasSFX(y); print(x)");
noInline("var y; var x = noSFX(y); new hasSFX(y); print(x)");
noInline("var y; var x = new noSFX(y); new hasSFX(y); print(x)");
}
public void testCanInlineAcrossNoSideEffect() {
// This can't be inlined because print() has side-effects and might change
// the definition of noSFX. We should be able to mark noSFX as const
// in some way.
noInline(
"var y; var x = noSFX(y), z = noSFX(); noSFX(); noSFX(), print(x)");
//inline(
// "var y; var x = noSFX(y), z = noSFX(); noSFX(); noSFX(), print(x)",
// "var y; var x, z = noSFX(); noSFX(); noSFX(), print(noSFX(y))");
}
public void testDependOnOuterScopeVariables() {
noInline("var x; function foo() { var y = x; x = 0; print(y) }");
noInline("var x; function foo() { var y = x; x++; print(y) }");
// Sadly, we don't understand the data flow of outer scoped variables as
// it can be modified by code outside of this scope. We can't inline
// at all if the definition has dependence on such variable.
noInline("var x; function foo() { var y = x; print(y) }");
}
public void testInlineIfNameIsLeftSideOfAssign() {
inline("var x = 1; x = print(x) + 1", "var x; x = print(1) + 1");
inline("var x = 1; L: x = x + 2", "var x; L: x = 1 + 2");
inline("var x = 1; x = (x = x + 1)", "var x; x = (x = 1 + 1)");
noInline("var x = 1; x = (x = (x = 10) + x)");
noInline("var x = 1; x = (f(x) + (x = 10) + x);");
noInline("var x = 1; x=-1,foo(x)");
noInline("var x = 1; x-=1,foo(x)");
}
public void testInlineArguments() {
testSame("function _func(x) { print(x) }");
testSame("function _func(x,y) { if(y) { x = 1 }; print(x) }");
test("function f(x, y) { x = 1; print(x) }",
"function f(x, y) { print(1) }");
test("function f(x, y) { if (y) { x = 1; print(x) }}",
"function f(x, y) { if (y) { print(1) }}");
}
public void testInvalidInlineArguments1() {
testSame("function f(x, y) { x = 1; arguments[0] = 2; print(x) }");
testSame("function f(x, y) { x = 1; var z = arguments;" +
"z[0] = 2; z[1] = 3; print(x)}");
testSame("function g(a){a[0]=2} function f(x){x=1;g(arguments);print(x)}");
}
public void testInvalidInlineArguments2() {
testSame("function f(c) {var f = c; arguments[0] = this;" +
"f.apply(this, arguments); return this;}");
}
public void testForIn() {
noInline("var x; var y = {}; for(x in y){}");
noInline("var x; var y = {}; var z; for(x in z = y){print(z)}");
noInline("var x; var y = {}; var z; for(x in y){print(z)}");
}
public void testNotOkToSkipCheckPathBetweenNodes() {
noInline("var x; for(x = 1; foo(x);) {}");
noInline("var x; for(; x = 1;foo(x)) {}");
}
public void testIssue698() {
// Most of the flow algorithms operate on Vars. We want to make
// sure the algorithm bails out appropriately if it sees
// a var that it doesn't know about.
inline(
"var x = ''; "
+ "unknown.length < 2 && (unknown='0' + unknown);"
+ "x = x + unknown; "
+ "unknown.length < 3 && (unknown='0' + unknown);"
+ "x = x + unknown; "
+ "return x;",
"var x; "
+ "unknown.length < 2 && (unknown='0' + unknown);"
+ "x = '' + unknown; "
+ "unknown.length < 3 && (unknown='0' + unknown);"
+ "x = x + unknown; "
+ "return x;");
}
private void noInline(String input) {
inline(input, input);
}
private void inline(String input, String expected) {
test(EXTERN_FUNCTIONS, "function _func() {" + input + "}",
"function _func() {" + expected + "}", null, null);
}
} | // You are a professional Java test case writer, please create a test case named `testSimpleForIn` for the issue `Closure-773`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-773
//
// ## Issue-Title:
// Switched order of "delete key" and "key in" statements changes semantic
//
// ## Issue-Description:
// // Input:
//
// var customData = { key: 'value' };
//
// function testRemoveKey( key ) {
// var dataSlot = customData,
// retval = dataSlot && dataSlot[ key ],
// hadKey = dataSlot && ( key in dataSlot );
//
// if ( dataSlot )
// delete dataSlot[ key ];
//
// return hadKey ? retval : null;
// };
//
// console.log( testRemoveKey( 'key' ) ); // 'value'
// console.log( 'key' in customData ); // false
//
//
// // Compiled version:
//
// var customData={key:"value"};function testRemoveKey(b){var a=customData,c=a&&a[b];a&&delete a[b];return a&&b in a?c:null}console.log(testRemoveKey("key"));console.log("key"in customData);
//
// // null
// // false
//
//
// "b in a" is executed after "delete a[b]" what obviously doesn't make sense in this case.
//
//
// Reproducible on: http://closure-compiler.appspot.com/home and in "Version: 20120430 (revision 1918) Built on: 2012/04/30 18:02"
//
//
public void testSimpleForIn() {
| 68 | 15 | 63 | test/com/google/javascript/jscomp/FlowSensitiveInlineVariablesTest.java | test | ```markdown
## Issue-ID: Closure-773
## Issue-Title:
Switched order of "delete key" and "key in" statements changes semantic
## Issue-Description:
// Input:
var customData = { key: 'value' };
function testRemoveKey( key ) {
var dataSlot = customData,
retval = dataSlot && dataSlot[ key ],
hadKey = dataSlot && ( key in dataSlot );
if ( dataSlot )
delete dataSlot[ key ];
return hadKey ? retval : null;
};
console.log( testRemoveKey( 'key' ) ); // 'value'
console.log( 'key' in customData ); // false
// Compiled version:
var customData={key:"value"};function testRemoveKey(b){var a=customData,c=a&&a[b];a&&delete a[b];return a&&b in a?c:null}console.log(testRemoveKey("key"));console.log("key"in customData);
// null
// false
"b in a" is executed after "delete a[b]" what obviously doesn't make sense in this case.
Reproducible on: http://closure-compiler.appspot.com/home and in "Version: 20120430 (revision 1918) Built on: 2012/04/30 18:02"
```
You are a professional Java test case writer, please create a test case named `testSimpleForIn` for the issue `Closure-773`, utilizing the provided issue report information and the following function signature.
```java
public void testSimpleForIn() {
```
| 63 | [
"com.google.javascript.jscomp.FlowSensitiveInlineVariables"
] | 3a6e07fd09134513552c6551af6c69571de2460e5338a8b04fe2bfab6f39c4fc | public void testSimpleForIn() | // You are a professional Java test case writer, please create a test case named `testSimpleForIn` for the issue `Closure-773`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-773
//
// ## Issue-Title:
// Switched order of "delete key" and "key in" statements changes semantic
//
// ## Issue-Description:
// // Input:
//
// var customData = { key: 'value' };
//
// function testRemoveKey( key ) {
// var dataSlot = customData,
// retval = dataSlot && dataSlot[ key ],
// hadKey = dataSlot && ( key in dataSlot );
//
// if ( dataSlot )
// delete dataSlot[ key ];
//
// return hadKey ? retval : null;
// };
//
// console.log( testRemoveKey( 'key' ) ); // 'value'
// console.log( 'key' in customData ); // false
//
//
// // Compiled version:
//
// var customData={key:"value"};function testRemoveKey(b){var a=customData,c=a&&a[b];a&&delete a[b];return a&&b in a?c:null}console.log(testRemoveKey("key"));console.log("key"in customData);
//
// // null
// // false
//
//
// "b in a" is executed after "delete a[b]" what obviously doesn't make sense in this case.
//
//
// Reproducible on: http://closure-compiler.appspot.com/home and in "Version: 20120430 (revision 1918) Built on: 2012/04/30 18:02"
//
//
| 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.javascript.rhino.Node;
/**
* Unit tests for {@link FlowSensitiveInlineVariables}.
*
*/
public class FlowSensitiveInlineVariablesTest extends CompilerTestCase {
public static final String EXTERN_FUNCTIONS = "" +
"var print;\n" +
"/** @nosideeffects */ function noSFX() {} \n" +
" function hasSFX() {} \n";
@Override
public int getNumRepetitions() {
// Test repeatedly inline.
return 3;
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
//return new FlowSensitiveInlineVariables(compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
(new MarkNoSideEffectCalls(compiler)).process(externs, root);
(new FlowSensitiveInlineVariables(compiler)).process(externs, root);
}
};
}
public void testSimpleAssign() {
inline("var x; x = 1; print(x)", "var x; print(1)");
inline("var x; x = 1; x", "var x; 1");
inline("var x; x = 1; var a = x", "var x; var a = 1");
inline("var x; x = 1; x = x + 1", "var x; x = 1 + 1");
}
public void testSimpleVar() {
inline("var x = 1; print(x)", "var x; print(1)");
inline("var x = 1; x", "var x; 1");
inline("var x = 1; var a = x", "var x; var a = 1");
inline("var x = 1; x = x + 1", "var x; x = 1 + 1");
}
public void testSimpleForIn() {
inline("var a,b,x = a in b; x",
"var a,b,x; a in b");
noInline("var a, b; var x = a in b; print(1); x");
noInline("var a,b,x = a in b; delete a[b]; x");
}
public void testExported() {
noInline("var _x = 1; print(_x)");
}
public void testDoNotInlineIncrement() {
noInline("var x = 1; x++;");
noInline("var x = 1; x--;");
}
public void testDoNotInlineAssignmentOp() {
noInline("var x = 1; x += 1;");
noInline("var x = 1; x -= 1;");
}
public void testDoNotInlineIntoLhsOfAssign() {
noInline("var x = 1; x += 3;");
}
public void testMultiUse() {
noInline("var x; x = 1; print(x); print (x);");
}
public void testMultiUseInSameCfgNode() {
noInline("var x; x = 1; print(x) || print (x);");
}
public void testMultiUseInTwoDifferentPath() {
noInline("var x = 1; if (print) { print(x) } else { alert(x) }");
}
public void testAssignmentBeforeDefinition() {
inline("x = 1; var x = 0; print(x)","x = 1; var x; print(0)" );
}
public void testVarInConditionPath() {
noInline("if (foo) { var x = 0 } print(x)");
}
public void testMultiDefinitionsBeforeUse() {
inline("var x = 0; x = 1; print(x)", "var x = 0; print(1)");
}
public void testMultiDefinitionsInSameCfgNode() {
noInline("var x; (x = 1) || (x = 2); print(x)");
noInline("var x; x = (1 || (x = 2)); print(x)");
noInline("var x;(x = 1) && (x = 2); print(x)");
noInline("var x;x = (1 && (x = 2)); print(x)");
noInline("var x; x = 1 , x = 2; print(x)");
}
public void testNotReachingDefinitions() {
noInline("var x; if (foo) { x = 0 } print (x)");
}
public void testNoInlineLoopCarriedDefinition() {
// First print is undefined instead.
noInline("var x; while(true) { print(x); x = 1; }");
// Prints 0 1 1 1 1....
noInline("var x = 0; while(true) { print(x); x = 1; }");
}
public void testDoNotExitLoop() {
noInline("while (z) { var x = 3; } var y = x;");
}
public void testDoNotInlineWithinLoop() {
noInline("var y = noSFX(); do { var z = y.foo(); } while (true);");
}
public void testDefinitionAfterUse() {
inline("var x = 0; print(x); x = 1", "var x; print(0); x = 1");
}
public void testInlineSameVariableInStraightLine() {
inline("var x; x = 1; print(x); x = 2; print(x)",
"var x; print(1); print(2)");
}
public void testInlineInDifferentPaths() {
inline("var x; if (print) {x = 1; print(x)} else {x = 2; print(x)}",
"var x; if (print) {print(1)} else {print(2)}");
}
public void testNoInlineInMergedPath() {
noInline(
"var x,y;x = 1;while(y) { if(y){ print(x) } else { x = 1 } } print(x)");
}
public void testInlineIntoExpressions() {
inline("var x = 1; print(x + 1);", "var x; print(1 + 1)");
}
public void testInlineExpressions1() {
inline("var a, b; var x = a+b; print(x)", "var a, b; var x; print(a+b)");
}
public void testInlineExpressions2() {
// We can't inline because of the redefinition of "a".
noInline("var a, b; var x = a + b; a = 1; print(x)");
}
public void testInlineExpressions3() {
inline("var a,b,x; x=a+b; x=a-b ; print(x)",
"var a,b,x; x=a+b; print(a-b)");
}
public void testInlineExpressions4() {
// Precision is lost due to comma's.
noInline("var a,b,x; x=a+b, x=a-b; print(x)");
}
public void testInlineExpressions5() {
noInline("var a; var x = a = 1; print(x)");
}
public void testInlineExpressions6() {
noInline("var a, x; a = 1 + (x = 1); print(x)");
}
public void testInlineExpression7() {
// Possible side effects in foo() that might conflict with bar();
noInline("var x = foo() + 1; bar(); print(x)");
// This is a possible case but we don't have analysis to prove this yet.
// TODO(user): It is possible to cover this case with the same algorithm
// as the missing return check.
noInline("var x = foo() + 1; print(x)");
}
public void testInlineExpression8() {
// The same variable inlined twice.
inline(
"var a,b;" +
"var x = a + b; print(x); x = a - b; print(x)",
"var a,b;" +
"var x; print(a + b); print(a - b)");
}
public void testInlineExpression9() {
// Check for actual control flow sensitivity.
inline(
"var a,b;" +
"var x; if (g) { x= a + b; print(x) } x = a - b; print(x)",
"var a,b;" +
"var x; if (g) { print(a + b)} print(a - b)");
}
public void testInlineExpression10() {
// The DFA is not fine grain enough for this.
noInline("var x, y; x = ((y = 1), print(y))");
}
public void testInlineExpressions11() {
inline("var x; x = x + 1; print(x)", "var x; print(x + 1)");
noInline("var x; x = x + 1; print(x); print(x)");
}
public void testInlineExpressions12() {
// ++ is an assignment and considered to modify state so it will not be
// inlined.
noInline("var x = 10; x = c++; print(x)");
}
public void testInlineExpressions13() {
inline("var a = 1, b = 2;" +
"var x = a;" +
"var y = b;" +
"var z = x + y;" +
"var i = z;" +
"var j = z + y;" +
"var k = i;",
"var a, b;" +
"var x;" +
"var y = 2;" +
"var z = 1 + y;" +
"var i;" +
"var j = z + y;" +
"var k = z;");
}
public void testNoInlineIfDefinitionMayNotReach() {
noInline("var x; if (x=1) {} x;");
}
public void testNoInlineEscapedToInnerFunction() {
noInline("var x = 1; function foo() { x = 2 }; print(x)");
}
public void testNoInlineLValue() {
noInline("var x; if (x = 1) { print(x) }");
}
public void testSwitchCase() {
inline("var x = 1; switch(x) { }", "var x; switch(1) { }");
}
public void testShadowedVariableInnerFunction() {
inline("var x = 1; print(x) || (function() { var x; x = 1; print(x)})()",
"var x; print(1) || (function() { var x; print(1)})()");
}
public void testCatch() {
noInline("var x = 0; try { } catch (x) { }");
noInline("try { } catch (x) { print(x) }");
}
public void testNoInlineGetProp() {
// We don't know if j alias a.b
noInline("var x = a.b.c; j.c = 1; print(x);");
}
public void testNoInlineGetProp2() {
noInline("var x = 1 * a.b.c; j.c = 1; print(x);");
}
public void testNoInlineGetProp3() {
// Anything inside a function is fine.
inline("var x = function(){1 * a.b.c}; print(x);",
"var x; print(function(){1 * a.b.c});");
}
public void testNoInlineGetEle() {
// Again we don't know if i = j
noInline("var x = a[i]; a[j] = 2; print(x); ");
}
// TODO(user): These should be inlinable.
public void testNoInlineConstructors() {
noInline("var x = new Iterator(); x.next();");
}
// TODO(user): These should be inlinable.
public void testNoInlineArrayLits() {
noInline("var x = []; print(x)");
}
// TODO(user): These should be inlinable.
public void testNoInlineObjectLits() {
noInline("var x = {}; print(x)");
}
// TODO(user): These should be inlinable after the REGEX checks.
public void testNoInlineRegExpLits() {
noInline("var x = /y/; print(x)");
}
public void testInlineConstructorCallsIntoLoop() {
// Don't inline construction into loops.
noInline("var x = new Iterator();" +
"for(i = 0; i < 10; i++) {j = x.next()}");
}
public void testRemoveWithLabels() {
inline("var x = 1; L: x = 2; print(x)", "var x = 1; print(2)");
inline("var x = 1; L: M: x = 2; print(x)", "var x = 1; print(2)");
inline("var x = 1; L: M: N: x = 2; print(x)", "var x = 1; print(2)");
}
public void testInlineAcrossSideEffect1() {
// This can't be inlined because print() has side-effects and might change
// the definition of noSFX.
//
// noSFX must be both const and pure in order to inline it.
noInline("var y; var x = noSFX(y); print(x)");
//inline("var y; var x = noSFX(y); print(x)", "var y;var x;print(noSFX(y))");
}
public void testInlineAcrossSideEffect2() {
// Think noSFX() as a function that reads y.foo and return it
// and SFX() write some new value of y.foo. If that's the case,
// inlining across hasSFX() is not valid.
// This is a case where hasSFX is right of the source of the inlining.
noInline("var y; var x = noSFX(y), z = hasSFX(y); print(x)");
noInline("var y; var x = noSFX(y), z = new hasSFX(y); print(x)");
noInline("var y; var x = new noSFX(y), z = new hasSFX(y); print(x)");
}
public void testInlineAcrossSideEffect3() {
// This is a case where hasSFX is left of the destination of the inlining.
noInline("var y; var x = noSFX(y); hasSFX(y), print(x)");
noInline("var y; var x = noSFX(y); new hasSFX(y), print(x)");
noInline("var y; var x = new noSFX(y); new hasSFX(y), print(x)");
}
public void testInlineAcrossSideEffect4() {
// This is a case where hasSFX is some control flow path between the
// source and its destination.
noInline("var y; var x = noSFX(y); hasSFX(y); print(x)");
noInline("var y; var x = noSFX(y); new hasSFX(y); print(x)");
noInline("var y; var x = new noSFX(y); new hasSFX(y); print(x)");
}
public void testCanInlineAcrossNoSideEffect() {
// This can't be inlined because print() has side-effects and might change
// the definition of noSFX. We should be able to mark noSFX as const
// in some way.
noInline(
"var y; var x = noSFX(y), z = noSFX(); noSFX(); noSFX(), print(x)");
//inline(
// "var y; var x = noSFX(y), z = noSFX(); noSFX(); noSFX(), print(x)",
// "var y; var x, z = noSFX(); noSFX(); noSFX(), print(noSFX(y))");
}
public void testDependOnOuterScopeVariables() {
noInline("var x; function foo() { var y = x; x = 0; print(y) }");
noInline("var x; function foo() { var y = x; x++; print(y) }");
// Sadly, we don't understand the data flow of outer scoped variables as
// it can be modified by code outside of this scope. We can't inline
// at all if the definition has dependence on such variable.
noInline("var x; function foo() { var y = x; print(y) }");
}
public void testInlineIfNameIsLeftSideOfAssign() {
inline("var x = 1; x = print(x) + 1", "var x; x = print(1) + 1");
inline("var x = 1; L: x = x + 2", "var x; L: x = 1 + 2");
inline("var x = 1; x = (x = x + 1)", "var x; x = (x = 1 + 1)");
noInline("var x = 1; x = (x = (x = 10) + x)");
noInline("var x = 1; x = (f(x) + (x = 10) + x);");
noInline("var x = 1; x=-1,foo(x)");
noInline("var x = 1; x-=1,foo(x)");
}
public void testInlineArguments() {
testSame("function _func(x) { print(x) }");
testSame("function _func(x,y) { if(y) { x = 1 }; print(x) }");
test("function f(x, y) { x = 1; print(x) }",
"function f(x, y) { print(1) }");
test("function f(x, y) { if (y) { x = 1; print(x) }}",
"function f(x, y) { if (y) { print(1) }}");
}
public void testInvalidInlineArguments1() {
testSame("function f(x, y) { x = 1; arguments[0] = 2; print(x) }");
testSame("function f(x, y) { x = 1; var z = arguments;" +
"z[0] = 2; z[1] = 3; print(x)}");
testSame("function g(a){a[0]=2} function f(x){x=1;g(arguments);print(x)}");
}
public void testInvalidInlineArguments2() {
testSame("function f(c) {var f = c; arguments[0] = this;" +
"f.apply(this, arguments); return this;}");
}
public void testForIn() {
noInline("var x; var y = {}; for(x in y){}");
noInline("var x; var y = {}; var z; for(x in z = y){print(z)}");
noInline("var x; var y = {}; var z; for(x in y){print(z)}");
}
public void testNotOkToSkipCheckPathBetweenNodes() {
noInline("var x; for(x = 1; foo(x);) {}");
noInline("var x; for(; x = 1;foo(x)) {}");
}
public void testIssue698() {
// Most of the flow algorithms operate on Vars. We want to make
// sure the algorithm bails out appropriately if it sees
// a var that it doesn't know about.
inline(
"var x = ''; "
+ "unknown.length < 2 && (unknown='0' + unknown);"
+ "x = x + unknown; "
+ "unknown.length < 3 && (unknown='0' + unknown);"
+ "x = x + unknown; "
+ "return x;",
"var x; "
+ "unknown.length < 2 && (unknown='0' + unknown);"
+ "x = '' + unknown; "
+ "unknown.length < 3 && (unknown='0' + unknown);"
+ "x = x + unknown; "
+ "return x;");
}
private void noInline(String input) {
inline(input, input);
}
private void inline(String input, String expected) {
test(EXTERN_FUNCTIONS, "function _func() {" + input + "}",
"function _func() {" + expected + "}", null, null);
}
} |
||
@Test
public void typeVariable_of_self_type() {
GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
} | org.mockito.internal.util.reflection.GenericMetadataSupportTest::typeVariable_of_self_type | test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java | 54 | test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java | typeVariable_of_self_type | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util.reflection;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.internal.util.reflection.GenericMetadataSupport.inferFrom;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
@SuppressWarnings("unused")
public class GenericMetadataSupportTest {
interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
T self();
}
interface UpperBoundedTypeWithClass<E extends Number & Comparable<E>> {
E get();
}
interface UpperBoundedTypeWithInterfaces<E extends Comparable<E> & Cloneable> {
E get();
}
interface ListOfNumbers extends List<Number> {}
interface ListOfAnyNumbers<N extends Number & Cloneable> extends List<N> {}
interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
Set<Number> remove(Object key); // override with fixed ParameterizedType
List<? super Integer> returning_wildcard_with_class_lower_bound();
List<? super K> returning_wildcard_with_typeVar_lower_bound();
List<? extends K> returning_wildcard_with_typeVar_upper_bound();
K returningK();
<O extends K> List<O> paramType_with_type_params();
<S, T extends S> T two_type_params();
<O extends K> O typeVar_with_type_params();
}
static class StringList extends ArrayList<String> { }
@Test
public void typeVariable_of_self_type() {
GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
}
@Test
public void can_get_raw_type_from_Class() throws Exception {
assertThat(inferFrom(ListOfAnyNumbers.class).rawType()).isEqualTo(ListOfAnyNumbers.class);
assertThat(inferFrom(ListOfNumbers.class).rawType()).isEqualTo(ListOfNumbers.class);
assertThat(inferFrom(GenericsNest.class).rawType()).isEqualTo(GenericsNest.class);
assertThat(inferFrom(StringList.class).rawType()).isEqualTo(StringList.class);
}
@Test
public void can_get_raw_type_from_ParameterizedType() throws Exception {
assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class);
assertThat(inferFrom(ListOfNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class);
assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).rawType()).isEqualTo(Map.class);
assertThat(inferFrom(StringList.class.getGenericSuperclass()).rawType()).isEqualTo(ArrayList.class);
}
@Test
public void can_get_type_variables_from_Class() throws Exception {
assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("K");
assertThat(inferFrom(ListOfNumbers.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("N");
assertThat(inferFrom(Map.class).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V");
assertThat(inferFrom(Serializable.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void can_get_type_variables_from_ParameterizedType() throws Exception {
assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V");
assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("E");
assertThat(inferFrom(Integer.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("T");
assertThat(inferFrom(StringBuilder.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(StringList.class).resolveGenericReturnType(firstNamedMethod("iterator", StringList.class));
assertThat(genericMetadata.rawType()).isEqualTo(Iterator.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(String.class);
}
@Test
public void typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returningK", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0));
assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class);
}
@Test
public void fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Collection.class);
GenericMetadataSupport fromTypeVariableE = inferFrom(typeVariableValue(genericMetadata.actualTypeArguments(), "E"));
assertThat(fromTypeVariableE.rawType()).isEqualTo(Set.class);
assertThat(fromTypeVariableE.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("paramType_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
Type firstBoundOfE = ((GenericMetadataSupport.TypeVarBoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E")).firstBound();
assertThat(inferFrom(firstBoundOfE).rawType()).isEqualTo(Comparable.class);
}
@Test
public void typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("typeVar_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0));
assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class);
}
@Test
public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(StringBuilder.class).resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class));
assertThat(genericMetadata.rawType()).isEqualTo(StringBuilder.class);
assertThat(genericMetadata.actualTypeArguments()).isEmpty();
}
@Test
public void paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_class_lower_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(boundedType.firstBound()).isEqualTo(Integer.class);
assertThat(boundedType.interfaceBounds()).isEmpty();
}
@Test
public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_lower_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class); }
@Test
public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_upper_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class);
}
private Type typeVariableValue(Map<TypeVariable, Type> typeVariables, String typeVariableName) {
for (Map.Entry<TypeVariable, Type> typeVariableTypeEntry : typeVariables.entrySet()) {
if (typeVariableTypeEntry.getKey().getName().equals(typeVariableName)) {
return typeVariableTypeEntry.getValue();
}
}
fail("'" + typeVariableName + "' was not found in " + typeVariables);
return null; // unreachable
}
private Method firstNamedMethod(String methodName, Class<?> clazz) {
for (Method method : clazz.getMethods()) {
boolean protect_against_different_jdk_ordering_avoiding_bridge_methods = !method.isBridge();
if (method.getName().contains(methodName) && protect_against_different_jdk_ordering_avoiding_bridge_methods) {
return method;
}
}
throw new IllegalStateException("The method : '" + methodName + "' do not exist in '" + clazz.getSimpleName() + "'");
}
} | // You are a professional Java test case writer, please create a test case named `typeVariable_of_self_type` for the issue `Mockito-114`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-114
//
// ## Issue-Title:
// 1.10 regression (StackOverflowError) with interface where generic type has itself as upper bound
//
// ## Issue-Description:
// Add this to `GenericMetadataSupportTest`:
//
//
//
// ```
// interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
// T self();
// }
//
// @Test
// public void typeVariable\_of\_self\_type() {
// GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
//
// assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
// }
// ```
//
// It fails on master and 1.10.8 with this:
//
//
//
// ```
// java.lang.StackOverflowError
// at sun.reflect.generics.reflectiveObjects.TypeVariableImpl.hashCode(TypeVariableImpl.java:201)
// at java.util.HashMap.hash(HashMap.java:338)
// at java.util.HashMap.get(HashMap.java:556)
// at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:193)
// at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
// at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
//
// ```
//
// It worked on 1.9.5. May be caused by the changes in [ab9e9f3](https://github.com/mockito/mockito/commit/ab9e9f347705bf9f4ebace4b07b085088275a256) (cc [@bric3](https://github.com/bric3)).
//
//
// (Also note that while the above interface looks strange, it is commonly used for builder hierarchies, where base class methods want to return this with a more specific type.)
//
//
//
//
@Test
public void typeVariable_of_self_type() {
| 54 | 8 | 49 | test/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java | test | ```markdown
## Issue-ID: Mockito-114
## Issue-Title:
1.10 regression (StackOverflowError) with interface where generic type has itself as upper bound
## Issue-Description:
Add this to `GenericMetadataSupportTest`:
```
interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
T self();
}
@Test
public void typeVariable\_of\_self\_type() {
GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
}
```
It fails on master and 1.10.8 with this:
```
java.lang.StackOverflowError
at sun.reflect.generics.reflectiveObjects.TypeVariableImpl.hashCode(TypeVariableImpl.java:201)
at java.util.HashMap.hash(HashMap.java:338)
at java.util.HashMap.get(HashMap.java:556)
at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:193)
at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
```
It worked on 1.9.5. May be caused by the changes in [ab9e9f3](https://github.com/mockito/mockito/commit/ab9e9f347705bf9f4ebace4b07b085088275a256) (cc [@bric3](https://github.com/bric3)).
(Also note that while the above interface looks strange, it is commonly used for builder hierarchies, where base class methods want to return this with a more specific type.)
```
You are a professional Java test case writer, please create a test case named `typeVariable_of_self_type` for the issue `Mockito-114`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void typeVariable_of_self_type() {
```
| 49 | [
"org.mockito.internal.util.reflection.GenericMetadataSupport"
] | 3ac9bb69eba27fa73dc172acb13da3dbc73b7431f77f75d246a532e9a0e4310a | @Test
public void typeVariable_of_self_type() | // You are a professional Java test case writer, please create a test case named `typeVariable_of_self_type` for the issue `Mockito-114`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-114
//
// ## Issue-Title:
// 1.10 regression (StackOverflowError) with interface where generic type has itself as upper bound
//
// ## Issue-Description:
// Add this to `GenericMetadataSupportTest`:
//
//
//
// ```
// interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
// T self();
// }
//
// @Test
// public void typeVariable\_of\_self\_type() {
// GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
//
// assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
// }
// ```
//
// It fails on master and 1.10.8 with this:
//
//
//
// ```
// java.lang.StackOverflowError
// at sun.reflect.generics.reflectiveObjects.TypeVariableImpl.hashCode(TypeVariableImpl.java:201)
// at java.util.HashMap.hash(HashMap.java:338)
// at java.util.HashMap.get(HashMap.java:556)
// at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:193)
// at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
// at org.mockito.internal.util.reflection.GenericMetadataSupport.getActualTypeArgumentFor(GenericMetadataSupport.java:196)
//
// ```
//
// It worked on 1.9.5. May be caused by the changes in [ab9e9f3](https://github.com/mockito/mockito/commit/ab9e9f347705bf9f4ebace4b07b085088275a256) (cc [@bric3](https://github.com/bric3)).
//
//
// (Also note that while the above interface looks strange, it is commonly used for builder hierarchies, where base class methods want to return this with a more specific type.)
//
//
//
//
| Mockito | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.util.reflection;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.internal.util.reflection.GenericMetadataSupport.inferFrom;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
@SuppressWarnings("unused")
public class GenericMetadataSupportTest {
interface GenericsSelfReference<T extends GenericsSelfReference<T>> {
T self();
}
interface UpperBoundedTypeWithClass<E extends Number & Comparable<E>> {
E get();
}
interface UpperBoundedTypeWithInterfaces<E extends Comparable<E> & Cloneable> {
E get();
}
interface ListOfNumbers extends List<Number> {}
interface ListOfAnyNumbers<N extends Number & Cloneable> extends List<N> {}
interface GenericsNest<K extends Comparable<K> & Cloneable> extends Map<K, Set<Number>> {
Set<Number> remove(Object key); // override with fixed ParameterizedType
List<? super Integer> returning_wildcard_with_class_lower_bound();
List<? super K> returning_wildcard_with_typeVar_lower_bound();
List<? extends K> returning_wildcard_with_typeVar_upper_bound();
K returningK();
<O extends K> List<O> paramType_with_type_params();
<S, T extends S> T two_type_params();
<O extends K> O typeVar_with_type_params();
}
static class StringList extends ArrayList<String> { }
@Test
public void typeVariable_of_self_type() {
GenericMetadataSupport genericMetadata = inferFrom(GenericsSelfReference.class).resolveGenericReturnType(firstNamedMethod("self", GenericsSelfReference.class));
assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
}
@Test
public void can_get_raw_type_from_Class() throws Exception {
assertThat(inferFrom(ListOfAnyNumbers.class).rawType()).isEqualTo(ListOfAnyNumbers.class);
assertThat(inferFrom(ListOfNumbers.class).rawType()).isEqualTo(ListOfNumbers.class);
assertThat(inferFrom(GenericsNest.class).rawType()).isEqualTo(GenericsNest.class);
assertThat(inferFrom(StringList.class).rawType()).isEqualTo(StringList.class);
}
@Test
public void can_get_raw_type_from_ParameterizedType() throws Exception {
assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class);
assertThat(inferFrom(ListOfNumbers.class.getGenericInterfaces()[0]).rawType()).isEqualTo(List.class);
assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).rawType()).isEqualTo(Map.class);
assertThat(inferFrom(StringList.class.getGenericSuperclass()).rawType()).isEqualTo(ArrayList.class);
}
@Test
public void can_get_type_variables_from_Class() throws Exception {
assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("K");
assertThat(inferFrom(ListOfNumbers.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("N");
assertThat(inferFrom(Map.class).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V");
assertThat(inferFrom(Serializable.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void can_get_type_variables_from_ParameterizedType() throws Exception {
assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(2).onProperty("name").contains("K", "V");
assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("E");
assertThat(inferFrom(Integer.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).hasSize(1).onProperty("name").contains("T");
assertThat(inferFrom(StringBuilder.class.getGenericInterfaces()[0]).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(StringList.class).resolveGenericReturnType(firstNamedMethod("iterator", StringList.class));
assertThat(genericMetadata.rawType()).isEqualTo(Iterator.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(String.class);
}
@Test
public void typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returningK", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0));
assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class);
}
@Test
public void fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Collection.class);
GenericMetadataSupport fromTypeVariableE = inferFrom(typeVariableValue(genericMetadata.actualTypeArguments(), "E"));
assertThat(fromTypeVariableE.rawType()).isEqualTo(Set.class);
assertThat(fromTypeVariableE.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("paramType_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
Type firstBoundOfE = ((GenericMetadataSupport.TypeVarBoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E")).firstBound();
assertThat(inferFrom(firstBoundOfE).rawType()).isEqualTo(Comparable.class);
}
@Test
public void typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("typeVar_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
GenericMetadataSupport extraInterface_0 = inferFrom(genericMetadata.extraInterfaces().get(0));
assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class);
}
@Test
public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(StringBuilder.class).resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class));
assertThat(genericMetadata.rawType()).isEqualTo(StringBuilder.class);
assertThat(genericMetadata.actualTypeArguments()).isEmpty();
}
@Test
public void paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_class_lower_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(boundedType.firstBound()).isEqualTo(Integer.class);
assertThat(boundedType.interfaceBounds()).isEmpty();
}
@Test
public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_lower_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class); }
@Test
public void paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() throws Exception {
GenericMetadataSupport genericMetadata = inferFrom(GenericsNest.class).resolveGenericReturnType(firstNamedMethod("returning_wildcard_with_typeVar_upper_bound", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType = (GenericMetadataSupport.BoundedType) typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class);
}
private Type typeVariableValue(Map<TypeVariable, Type> typeVariables, String typeVariableName) {
for (Map.Entry<TypeVariable, Type> typeVariableTypeEntry : typeVariables.entrySet()) {
if (typeVariableTypeEntry.getKey().getName().equals(typeVariableName)) {
return typeVariableTypeEntry.getValue();
}
}
fail("'" + typeVariableName + "' was not found in " + typeVariables);
return null; // unreachable
}
private Method firstNamedMethod(String methodName, Class<?> clazz) {
for (Method method : clazz.getMethods()) {
boolean protect_against_different_jdk_ordering_avoiding_bridge_methods = !method.isBridge();
if (method.getName().contains(methodName) && protect_against_different_jdk_ordering_avoiding_bridge_methods) {
return method;
}
}
throw new IllegalStateException("The method : '" + methodName + "' do not exist in '" + clazz.getSimpleName() + "'");
}
} |
||
public void testExtremeValues() throws Exception {
NormalDistribution distribution = new NormalDistributionImpl(0, 1);
for (int i = 0; i < 100; i++) { // make sure no convergence exception
double lowerTail = distribution.cumulativeProbability(-i);
double upperTail = distribution.cumulativeProbability(i);
if (i < 9) { // make sure not top-coded
// For i = 10, due to bad tail precision in erf (MATH-364), 1 is returned
// TODO: once MATH-364 is resolved, replace 9 with 30
assertTrue(lowerTail > 0.0d);
assertTrue(upperTail < 1.0d);
}
else { // make sure top coding not reversed
assertTrue(lowerTail < 0.00001);
assertTrue(upperTail > 0.99999);
}
}
assertEquals(distribution.cumulativeProbability(Double.MAX_VALUE), 1, 0);
assertEquals(distribution.cumulativeProbability(-Double.MAX_VALUE), 0, 0);
assertEquals(distribution.cumulativeProbability(Double.POSITIVE_INFINITY), 1, 0);
assertEquals(distribution.cumulativeProbability(Double.NEGATIVE_INFINITY), 0, 0);
} | org.apache.commons.math.distribution.NormalDistributionTest::testExtremeValues | src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java | 178 | src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java | testExtremeValues | /*
* 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;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
/**
* 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 NormalDistribution 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.226325228634938d, -1.156887023657177d, -0.643949578356075d, -0.2027950777320613d, 0.305827808237559d,
6.42632522863494d, 5.35688702365718d, 4.843949578356074d, 4.40279507773206d, 3.89417219176244d};
}
/** 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};
}
/** Creates the default probability density test expected values */
@Override
public double[] makeDensityTestValues() {
return new double[] {0.00240506434076, 0.0190372444310, 0.0417464784322, 0.0736683145538, 0.125355951380,
0.00240506434076, 0.0190372444310, 0.0417464784322, 0.0736683145538, 0.125355951380};
}
// --------------------- Override tolerance --------------
protected double defaultTolerance = NormalDistributionImpl.DEFAULT_INVERSE_ABSOLUTE_ACCURACY;
@Override
protected void setUp() throws Exception {
super.setUp();
setTolerance(defaultTolerance);
}
//---------------------------- 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.02275013194817921, 0.158655253931457, 0.5, 0.841344746068543,
0.977249868051821, 0.99865010196837, 0.999968328758167, 0.999999713348428});
verifyCumulativeProbabilities();
}
public void testQuantiles() throws Exception {
setDensityTestValues(new double[] {0.0385649760808, 0.172836231799, 0.284958771715, 0.172836231799, 0.0385649760808,
0.00316560600853, 9.55930184035e-05, 1.06194251052e-06});
verifyQuantiles();
verifyDensities();
setDistribution(new NormalDistributionImpl(0, 1));
setDensityTestValues(new double[] {0.0539909665132, 0.241970724519, 0.398942280401, 0.241970724519, 0.0539909665132,
0.00443184841194, 0.000133830225765, 1.48671951473e-06});
verifyQuantiles();
verifyDensities();
setDistribution(new NormalDistributionImpl(0, 0.1));
setDensityTestValues(new double[] {0.539909665132, 2.41970724519, 3.98942280401, 2.41970724519,
0.539909665132, 0.0443184841194, 0.00133830225765, 1.48671951473e-05});
verifyQuantiles();
verifyDensities();
}
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 testGetStandardDeviation() {
NormalDistribution distribution = (NormalDistribution) getDistribution();
assertEquals(1.4, distribution.getStandardDeviation(), 0);
}
public void testPreconditions() {
try {
new NormalDistributionImpl(1, 0);
fail("Should have generated NotStrictlyPositiveException");
} catch (NotStrictlyPositiveException e) {
// 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 fixes for JIRA MATH-167, MATH-414
*/
public void testExtremeValues() throws Exception {
NormalDistribution distribution = new NormalDistributionImpl(0, 1);
for (int i = 0; i < 100; i++) { // make sure no convergence exception
double lowerTail = distribution.cumulativeProbability(-i);
double upperTail = distribution.cumulativeProbability(i);
if (i < 9) { // make sure not top-coded
// For i = 10, due to bad tail precision in erf (MATH-364), 1 is returned
// TODO: once MATH-364 is resolved, replace 9 with 30
assertTrue(lowerTail > 0.0d);
assertTrue(upperTail < 1.0d);
}
else { // make sure top coding not reversed
assertTrue(lowerTail < 0.00001);
assertTrue(upperTail > 0.99999);
}
}
assertEquals(distribution.cumulativeProbability(Double.MAX_VALUE), 1, 0);
assertEquals(distribution.cumulativeProbability(-Double.MAX_VALUE), 0, 0);
assertEquals(distribution.cumulativeProbability(Double.POSITIVE_INFINITY), 1, 0);
assertEquals(distribution.cumulativeProbability(Double.NEGATIVE_INFINITY), 0, 0);
}
public void testMath280() throws MathException {
NormalDistribution normal = new NormalDistributionImpl(0,1);
double result = normal.inverseCumulativeProbability(0.9986501019683698);
assertEquals(3.0, result, defaultTolerance);
result = normal.inverseCumulativeProbability(0.841344746068543);
assertEquals(1.0, result, defaultTolerance);
result = normal.inverseCumulativeProbability(0.9999683287581673);
assertEquals(4.0, result, defaultTolerance);
result = normal.inverseCumulativeProbability(0.9772498680518209);
assertEquals(2.0, result, defaultTolerance);
}
} | // You are a professional Java test case writer, please create a test case named `testExtremeValues` for the issue `Math-MATH-414`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-414
//
// ## Issue-Title:
// ConvergenceException in NormalDistributionImpl.cumulativeProbability()
//
// ## Issue-Description:
//
// I get a ConvergenceException in NormalDistributionImpl.cumulativeProbability() for very large/small parameters including Infinity, -Infinity.
//
// For instance in the following code:
//
//
// @Test
//
// public void testCumulative() {
//
// final NormalDistribution nd = new NormalDistributionImpl();
//
// for (int i = 0; i < 500; i++) {
//
// final double val = Math.exp![](/jira/images/icons/emoticons/information.png);
//
// try
//
//
// {
// System.out.println("val = " + val + " cumulative = " + nd.cumulativeProbability(val));
// }
// catch (MathException e)
//
//
// {
// e.printStackTrace();
// fail();
// }
// }
//
// }
//
//
// In version 2.0, I get no exception.
//
//
// My suggestion is to change in the implementation of cumulativeProbability(double) to catch all ConvergenceException (and return for very large and very small values), not just MaxIterationsExceededException.
//
//
//
//
//
public void testExtremeValues() throws Exception {
| 178 | /**
* Check to make sure top-coding of extreme values works correctly.
* Verifies fixes for JIRA MATH-167, MATH-414
*/ | 60 | 156 | src/test/java/org/apache/commons/math/distribution/NormalDistributionTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-414
## Issue-Title:
ConvergenceException in NormalDistributionImpl.cumulativeProbability()
## Issue-Description:
I get a ConvergenceException in NormalDistributionImpl.cumulativeProbability() for very large/small parameters including Infinity, -Infinity.
For instance in the following code:
@Test
public void testCumulative() {
final NormalDistribution nd = new NormalDistributionImpl();
for (int i = 0; i < 500; i++) {
final double val = Math.exp![](/jira/images/icons/emoticons/information.png);
try
{
System.out.println("val = " + val + " cumulative = " + nd.cumulativeProbability(val));
}
catch (MathException e)
{
e.printStackTrace();
fail();
}
}
}
In version 2.0, I get no exception.
My suggestion is to change in the implementation of cumulativeProbability(double) to catch all ConvergenceException (and return for very large and very small values), not just MaxIterationsExceededException.
```
You are a professional Java test case writer, please create a test case named `testExtremeValues` for the issue `Math-MATH-414`, utilizing the provided issue report information and the following function signature.
```java
public void testExtremeValues() throws Exception {
```
| 156 | [
"org.apache.commons.math.distribution.NormalDistributionImpl"
] | 3bb5fab0eb888b88c3303a7ca947d449f13e5de29087d2c961b07af897e109ec | public void testExtremeValues() throws Exception | // You are a professional Java test case writer, please create a test case named `testExtremeValues` for the issue `Math-MATH-414`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-414
//
// ## Issue-Title:
// ConvergenceException in NormalDistributionImpl.cumulativeProbability()
//
// ## Issue-Description:
//
// I get a ConvergenceException in NormalDistributionImpl.cumulativeProbability() for very large/small parameters including Infinity, -Infinity.
//
// For instance in the following code:
//
//
// @Test
//
// public void testCumulative() {
//
// final NormalDistribution nd = new NormalDistributionImpl();
//
// for (int i = 0; i < 500; i++) {
//
// final double val = Math.exp![](/jira/images/icons/emoticons/information.png);
//
// try
//
//
// {
// System.out.println("val = " + val + " cumulative = " + nd.cumulativeProbability(val));
// }
// catch (MathException e)
//
//
// {
// e.printStackTrace();
// fail();
// }
// }
//
// }
//
//
// In version 2.0, I get no exception.
//
//
// My suggestion is to change in the implementation of cumulativeProbability(double) to catch all ConvergenceException (and return for very large and very small values), not just MaxIterationsExceededException.
//
//
//
//
//
| 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;
import org.apache.commons.math.exception.NotStrictlyPositiveException;
/**
* 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 NormalDistribution 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.226325228634938d, -1.156887023657177d, -0.643949578356075d, -0.2027950777320613d, 0.305827808237559d,
6.42632522863494d, 5.35688702365718d, 4.843949578356074d, 4.40279507773206d, 3.89417219176244d};
}
/** 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};
}
/** Creates the default probability density test expected values */
@Override
public double[] makeDensityTestValues() {
return new double[] {0.00240506434076, 0.0190372444310, 0.0417464784322, 0.0736683145538, 0.125355951380,
0.00240506434076, 0.0190372444310, 0.0417464784322, 0.0736683145538, 0.125355951380};
}
// --------------------- Override tolerance --------------
protected double defaultTolerance = NormalDistributionImpl.DEFAULT_INVERSE_ABSOLUTE_ACCURACY;
@Override
protected void setUp() throws Exception {
super.setUp();
setTolerance(defaultTolerance);
}
//---------------------------- 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.02275013194817921, 0.158655253931457, 0.5, 0.841344746068543,
0.977249868051821, 0.99865010196837, 0.999968328758167, 0.999999713348428});
verifyCumulativeProbabilities();
}
public void testQuantiles() throws Exception {
setDensityTestValues(new double[] {0.0385649760808, 0.172836231799, 0.284958771715, 0.172836231799, 0.0385649760808,
0.00316560600853, 9.55930184035e-05, 1.06194251052e-06});
verifyQuantiles();
verifyDensities();
setDistribution(new NormalDistributionImpl(0, 1));
setDensityTestValues(new double[] {0.0539909665132, 0.241970724519, 0.398942280401, 0.241970724519, 0.0539909665132,
0.00443184841194, 0.000133830225765, 1.48671951473e-06});
verifyQuantiles();
verifyDensities();
setDistribution(new NormalDistributionImpl(0, 0.1));
setDensityTestValues(new double[] {0.539909665132, 2.41970724519, 3.98942280401, 2.41970724519,
0.539909665132, 0.0443184841194, 0.00133830225765, 1.48671951473e-05});
verifyQuantiles();
verifyDensities();
}
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 testGetStandardDeviation() {
NormalDistribution distribution = (NormalDistribution) getDistribution();
assertEquals(1.4, distribution.getStandardDeviation(), 0);
}
public void testPreconditions() {
try {
new NormalDistributionImpl(1, 0);
fail("Should have generated NotStrictlyPositiveException");
} catch (NotStrictlyPositiveException e) {
// 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 fixes for JIRA MATH-167, MATH-414
*/
public void testExtremeValues() throws Exception {
NormalDistribution distribution = new NormalDistributionImpl(0, 1);
for (int i = 0; i < 100; i++) { // make sure no convergence exception
double lowerTail = distribution.cumulativeProbability(-i);
double upperTail = distribution.cumulativeProbability(i);
if (i < 9) { // make sure not top-coded
// For i = 10, due to bad tail precision in erf (MATH-364), 1 is returned
// TODO: once MATH-364 is resolved, replace 9 with 30
assertTrue(lowerTail > 0.0d);
assertTrue(upperTail < 1.0d);
}
else { // make sure top coding not reversed
assertTrue(lowerTail < 0.00001);
assertTrue(upperTail > 0.99999);
}
}
assertEquals(distribution.cumulativeProbability(Double.MAX_VALUE), 1, 0);
assertEquals(distribution.cumulativeProbability(-Double.MAX_VALUE), 0, 0);
assertEquals(distribution.cumulativeProbability(Double.POSITIVE_INFINITY), 1, 0);
assertEquals(distribution.cumulativeProbability(Double.NEGATIVE_INFINITY), 0, 0);
}
public void testMath280() throws MathException {
NormalDistribution normal = new NormalDistributionImpl(0,1);
double result = normal.inverseCumulativeProbability(0.9986501019683698);
assertEquals(3.0, result, defaultTolerance);
result = normal.inverseCumulativeProbability(0.841344746068543);
assertEquals(1.0, result, defaultTolerance);
result = normal.inverseCumulativeProbability(0.9999683287581673);
assertEquals(4.0, result, defaultTolerance);
result = normal.inverseCumulativeProbability(0.9772498680518209);
assertEquals(2.0, result, defaultTolerance);
}
} |
|
public void testLocale() throws IOException
{
assertEquals(new Locale("en"), MAPPER.readValue(quote("en"), Locale.class));
assertEquals(new Locale("es", "ES"), MAPPER.readValue(quote("es_ES"), Locale.class));
assertEquals(new Locale("FI", "fi", "savo"),
MAPPER.readValue(quote("fi_FI_savo"), Locale.class));
// [databind#1123]
Locale loc = MAPPER.readValue(quote(""), Locale.class);
assertSame(Locale.ROOT, loc);
} | com.fasterxml.jackson.databind.deser.TestJdkTypes::testLocale | src/test/java/com/fasterxml/jackson/databind/deser/TestJdkTypes.java | 150 | src/test/java/com/fasterxml/jackson/databind/deser/TestJdkTypes.java | testLocale | package com.fasterxml.jackson.databind.deser;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class TestJdkTypes extends BaseMapTest
{
static class PrimitivesBean
{
public boolean booleanValue = true;
public byte byteValue = 3;
public char charValue = 'a';
public short shortValue = 37;
public int intValue = 1;
public long longValue = 100L;
public float floatValue = 0.25f;
public double doubleValue = -1.0;
}
static class WrappersBean
{
public Boolean booleanValue;
public Byte byteValue;
public Character charValue;
public Short shortValue;
public Integer intValue;
public Long longValue;
public Float floatValue;
public Double doubleValue;
}
static class ParamClassBean
{
public String name = "bar";
public Class<String> clazz ;
public ParamClassBean() { }
public ParamClassBean(String name) {
this.name = name;
clazz = String.class;
}
}
static class BooleanBean {
public Boolean wrapper;
public boolean primitive;
protected Boolean ctor;
@JsonCreator
public BooleanBean(@JsonProperty("ctor") Boolean foo) {
ctor = foo;
}
}
// [Issue#429]
static class StackTraceBean {
public final static int NUM = 13;
@JsonProperty("Location")
@JsonDeserialize(using=MyStackTraceElementDeserializer.class)
protected StackTraceElement location;
}
@SuppressWarnings("serial")
static class MyStackTraceElementDeserializer extends StdDeserializer<StackTraceElement>
{
public MyStackTraceElementDeserializer() { super(StackTraceElement.class); }
@Override
public StackTraceElement deserialize(JsonParser jp,
DeserializationContext ctxt) throws IOException, JsonProcessingException {
jp.skipChildren();
return new StackTraceElement("a", "b", "b", StackTraceBean.NUM);
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
/**
* Related to issues [JACKSON-155], [#170].
*/
public void testFile() throws Exception
{
// Not portable etc... has to do:
File src = new File("/test").getAbsoluteFile();
String abs = src.getAbsolutePath();
// escape backslashes (for portability with windows)
String json = MAPPER.writeValueAsString(abs);
File result = MAPPER.readValue(json, File.class);
assertEquals(abs, result.getAbsolutePath());
// Then #170
final ObjectMapper mapper2 = new ObjectMapper();
mapper2.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);
result = mapper2.readValue(json, File.class);
assertEquals(abs, result.getAbsolutePath());
}
public void testRegexps() throws IOException
{
final String PATTERN_STR = "abc:\\s?(\\d+)";
Pattern exp = Pattern.compile(PATTERN_STR);
/* Ok: easiest way is to just serialize first; problem
* is the backslash
*/
String json = MAPPER.writeValueAsString(exp);
Pattern result = MAPPER.readValue(json, Pattern.class);
assertEquals(exp.pattern(), result.pattern());
}
public void testCurrency() throws IOException
{
Currency usd = Currency.getInstance("USD");
assertEquals(usd, new ObjectMapper().readValue(quote("USD"), Currency.class));
}
public void testLocale() throws IOException
{
assertEquals(new Locale("en"), MAPPER.readValue(quote("en"), Locale.class));
assertEquals(new Locale("es", "ES"), MAPPER.readValue(quote("es_ES"), Locale.class));
assertEquals(new Locale("FI", "fi", "savo"),
MAPPER.readValue(quote("fi_FI_savo"), Locale.class));
// [databind#1123]
Locale loc = MAPPER.readValue(quote(""), Locale.class);
assertSame(Locale.ROOT, loc);
}
public void testNullForPrimitives() throws IOException
{
// by default, ok to rely on defaults
PrimitivesBean bean = MAPPER.readValue("{\"intValue\":null, \"booleanValue\":null, \"doubleValue\":null}",
PrimitivesBean.class);
assertNotNull(bean);
assertEquals(0, bean.intValue);
assertEquals(false, bean.booleanValue);
assertEquals(0.0, bean.doubleValue);
bean = MAPPER.readValue("{\"byteValue\":null, \"longValue\":null, \"floatValue\":null}",
PrimitivesBean.class);
assertNotNull(bean);
assertEquals((byte) 0, bean.byteValue);
assertEquals(0L, bean.longValue);
assertEquals(0.0f, bean.floatValue);
// but not when enabled
final ObjectMapper mapper2 = new ObjectMapper();
mapper2.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);
// boolean
try {
mapper2.readValue("{\"booleanValue\":null}", PrimitivesBean.class);
fail("Expected failure for boolean + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type boolean");
}
// byte/char/short/int/long
try {
mapper2.readValue("{\"byteValue\":null}", PrimitivesBean.class);
fail("Expected failure for byte + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type byte");
}
try {
mapper2.readValue("{\"charValue\":null}", PrimitivesBean.class);
fail("Expected failure for char + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type char");
}
try {
mapper2.readValue("{\"shortValue\":null}", PrimitivesBean.class);
fail("Expected failure for short + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type short");
}
try {
mapper2.readValue("{\"intValue\":null}", PrimitivesBean.class);
fail("Expected failure for int + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type int");
}
try {
mapper2.readValue("{\"longValue\":null}", PrimitivesBean.class);
fail("Expected failure for long + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type long");
}
// float/double
try {
mapper2.readValue("{\"floatValue\":null}", PrimitivesBean.class);
fail("Expected failure for float + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type float");
}
try {
mapper2.readValue("{\"doubleValue\":null}", PrimitivesBean.class);
fail("Expected failure for double + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type double");
}
}
/**
* Test for [JACKSON-483], allow handling of CharSequence
*/
public void testCharSequence() throws IOException
{
CharSequence cs = MAPPER.readValue("\"abc\"", CharSequence.class);
assertEquals(String.class, cs.getClass());
assertEquals("abc", cs.toString());
}
// [JACKSON-484]
public void testInetAddress() throws IOException
{
InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class);
assertEquals("127.0.0.1", address.getHostAddress());
// should we try resolving host names? That requires connectivity...
final String HOST = "google.com";
address = MAPPER.readValue(quote(HOST), InetAddress.class);
assertEquals(HOST, address.getHostName());
}
public void testInetSocketAddress() throws IOException
{
InetSocketAddress address = MAPPER.readValue(quote("127.0.0.1"), InetSocketAddress.class);
assertEquals("127.0.0.1", address.getAddress().getHostAddress());
InetSocketAddress ip6 = MAPPER.readValue(
quote("2001:db8:85a3:8d3:1319:8a2e:370:7348"), InetSocketAddress.class);
assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6.getAddress().getHostAddress());
InetSocketAddress ip6port = MAPPER.readValue(
quote("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443"), InetSocketAddress.class);
assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6port.getAddress().getHostAddress());
assertEquals(443, ip6port.getPort());
// should we try resolving host names? That requires connectivity...
final String HOST = "www.google.com";
address = MAPPER.readValue(quote(HOST), InetSocketAddress.class);
assertEquals(HOST, address.getHostName());
final String HOST_AND_PORT = HOST+":80";
address = MAPPER.readValue(quote(HOST_AND_PORT), InetSocketAddress.class);
assertEquals(HOST, address.getHostName());
assertEquals(80, address.getPort());
}
// [JACKSON-597]
public void testClass() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
assertSame(String.class, mapper.readValue(quote("java.lang.String"), Class.class));
// then primitive types
assertSame(Boolean.TYPE, mapper.readValue(quote("boolean"), Class.class));
assertSame(Byte.TYPE, mapper.readValue(quote("byte"), Class.class));
assertSame(Short.TYPE, mapper.readValue(quote("short"), Class.class));
assertSame(Character.TYPE, mapper.readValue(quote("char"), Class.class));
assertSame(Integer.TYPE, mapper.readValue(quote("int"), Class.class));
assertSame(Long.TYPE, mapper.readValue(quote("long"), Class.class));
assertSame(Float.TYPE, mapper.readValue(quote("float"), Class.class));
assertSame(Double.TYPE, mapper.readValue(quote("double"), Class.class));
assertSame(Void.TYPE, mapper.readValue(quote("void"), Class.class));
}
// [JACKSON-605]
public void testClassWithParams() throws IOException
{
String json = MAPPER.writeValueAsString(new ParamClassBean("Foobar"));
ParamClassBean result = MAPPER.readValue(json, ParamClassBean.class);
assertEquals("Foobar", result.name);
assertSame(String.class, result.clazz);
}
// by default, should return nulls, n'est pas?
public void testEmptyStringForWrappers() throws IOException
{
WrappersBean bean;
// by default, ok to rely on defaults
bean = MAPPER.readValue("{\"booleanValue\":\"\"}", WrappersBean.class);
assertNull(bean.booleanValue);
bean = MAPPER.readValue("{\"byteValue\":\"\"}", WrappersBean.class);
assertNull(bean.byteValue);
// char/Character is different... not sure if this should work or not:
bean = MAPPER.readValue("{\"charValue\":\"\"}", WrappersBean.class);
assertNull(bean.charValue);
bean = MAPPER.readValue("{\"shortValue\":\"\"}", WrappersBean.class);
assertNull(bean.shortValue);
bean = MAPPER.readValue("{\"intValue\":\"\"}", WrappersBean.class);
assertNull(bean.intValue);
bean = MAPPER.readValue("{\"longValue\":\"\"}", WrappersBean.class);
assertNull(bean.longValue);
bean = MAPPER.readValue("{\"floatValue\":\"\"}", WrappersBean.class);
assertNull(bean.floatValue);
bean = MAPPER.readValue("{\"doubleValue\":\"\"}", WrappersBean.class);
assertNull(bean.doubleValue);
}
// for [JACKSON-616]
// @since 1.9
public void testEmptyStringForPrimitives() throws IOException
{
PrimitivesBean bean;
bean = MAPPER.readValue("{\"booleanValue\":\"\"}", PrimitivesBean.class);
assertFalse(bean.booleanValue);
bean = MAPPER.readValue("{\"byteValue\":\"\"}", PrimitivesBean.class);
assertEquals((byte) 0, bean.byteValue);
bean = MAPPER.readValue("{\"charValue\":\"\"}", PrimitivesBean.class);
assertEquals((char) 0, bean.charValue);
bean = MAPPER.readValue("{\"shortValue\":\"\"}", PrimitivesBean.class);
assertEquals((short) 0, bean.shortValue);
bean = MAPPER.readValue("{\"intValue\":\"\"}", PrimitivesBean.class);
assertEquals(0, bean.intValue);
bean = MAPPER.readValue("{\"longValue\":\"\"}", PrimitivesBean.class);
assertEquals(0L, bean.longValue);
bean = MAPPER.readValue("{\"floatValue\":\"\"}", PrimitivesBean.class);
assertEquals(0.0f, bean.floatValue);
bean = MAPPER.readValue("{\"doubleValue\":\"\"}", PrimitivesBean.class);
assertEquals(0.0, bean.doubleValue);
}
// for [JACKSON-652]
// @since 1.9
public void testUntypedWithJsonArrays() throws Exception
{
// by default we get:
Object ob = MAPPER.readValue("[1]", Object.class);
assertTrue(ob instanceof List<?>);
// but can change to produce Object[]:
MAPPER.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
ob = MAPPER.readValue("[1]", Object.class);
assertEquals(Object[].class, ob.getClass());
}
// Test for verifying that Long values are coerced to boolean correctly as well
public void testLongToBoolean() throws Exception
{
long value = 1L + Integer.MAX_VALUE;
BooleanBean b = MAPPER.readValue("{\"primitive\" : "+value+", \"wrapper\":"+value+", \"ctor\":"+value+"}",
BooleanBean.class);
assertEquals(Boolean.TRUE, b.wrapper);
assertTrue(b.primitive);
assertEquals(Boolean.TRUE, b.ctor);
}
// [JACKSON-789]
public void testCharset() throws Exception
{
Charset UTF8 = Charset.forName("UTF-8");
assertSame(UTF8, MAPPER.readValue(quote("UTF-8"), Charset.class));
}
// [JACKSON-888]
public void testStackTraceElement() throws Exception
{
StackTraceElement elem = null;
try {
throw new IllegalStateException();
} catch (Exception e) {
elem = e.getStackTrace()[0];
}
String json = MAPPER.writeValueAsString(elem);
StackTraceElement back = MAPPER.readValue(json, StackTraceElement.class);
assertEquals("testStackTraceElement", back.getMethodName());
assertEquals(elem.getLineNumber(), back.getLineNumber());
assertEquals(elem.getClassName(), back.getClassName());
assertEquals(elem.isNativeMethod(), back.isNativeMethod());
assertTrue(back.getClassName().endsWith("TestJdkTypes"));
assertFalse(back.isNativeMethod());
}
// [Issue#239]
public void testByteBuffer() throws Exception
{
byte[] INPUT = new byte[] { 1, 3, 9, -1, 6 };
String exp = MAPPER.writeValueAsString(INPUT);
ByteBuffer result = MAPPER.readValue(exp, ByteBuffer.class);
assertNotNull(result);
assertEquals(INPUT.length, result.remaining());
for (int i = 0; i < INPUT.length; ++i) {
assertEquals(INPUT[i], result.get());
}
assertEquals(0, result.remaining());
}
public void testStringBuilder() throws Exception
{
StringBuilder sb = MAPPER.readValue(quote("abc"), StringBuilder.class);
assertEquals("abc", sb.toString());
}
// [Issue#429]
public void testStackTraceElementWithCustom() throws Exception
{
// first, via bean that contains StackTraceElement
StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"),
StackTraceBean.class);
assertNotNull(bean);
assertNotNull(bean.location);
assertEquals(StackTraceBean.NUM, bean.location.getLineNumber());
// and then directly, iff registered
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(StackTraceElement.class, new MyStackTraceElementDeserializer());
mapper.registerModule(module);
StackTraceElement elem = mapper.readValue("123", StackTraceElement.class);
assertNotNull(elem);
assertEquals(StackTraceBean.NUM, elem.getLineNumber());
// and finally, even as part of real exception
IOException ioe = mapper.readValue(aposToQuotes("{'stackTrace':[ 123, 456 ]}"),
IOException.class);
assertNotNull(ioe);
StackTraceElement[] traces = ioe.getStackTrace();
assertNotNull(traces);
assertEquals(2, traces.length);
assertEquals(StackTraceBean.NUM, traces[0].getLineNumber());
assertEquals(StackTraceBean.NUM, traces[1].getLineNumber());
}
/*
/**********************************************************
/* Single-array handling tests
/**********************************************************
*/
// [Issue#381]
public void testSingleElementArray() throws Exception {
final int intTest = 932832;
final double doubleTest = 32.3234;
final long longTest = 2374237428374293423L;
final short shortTest = (short) intTest;
final float floatTest = 84.3743f;
final byte byteTest = (byte) 43;
final char charTest = 'c';
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
final int intValue = mapper.readValue(asArray(intTest), Integer.TYPE);
assertEquals(intTest, intValue);
final Integer integerWrapperValue = mapper.readValue(asArray(Integer.valueOf(intTest)), Integer.class);
assertEquals(Integer.valueOf(intTest), integerWrapperValue);
final double doubleValue = mapper.readValue(asArray(doubleTest), Double.class);
assertEquals(doubleTest, doubleValue);
final Double doubleWrapperValue = mapper.readValue(asArray(Double.valueOf(doubleTest)), Double.class);
assertEquals(Double.valueOf(doubleTest), doubleWrapperValue);
final long longValue = mapper.readValue(asArray(longTest), Long.TYPE);
assertEquals(longTest, longValue);
final Long longWrapperValue = mapper.readValue(asArray(Long.valueOf(longTest)), Long.class);
assertEquals(Long.valueOf(longTest), longWrapperValue);
final short shortValue = mapper.readValue(asArray(shortTest), Short.TYPE);
assertEquals(shortTest, shortValue);
final Short shortWrapperValue = mapper.readValue(asArray(Short.valueOf(shortTest)), Short.class);
assertEquals(Short.valueOf(shortTest), shortWrapperValue);
final float floatValue = mapper.readValue(asArray(floatTest), Float.TYPE);
assertEquals(floatTest, floatValue);
final Float floatWrapperValue = mapper.readValue(asArray(Float.valueOf(floatTest)), Float.class);
assertEquals(Float.valueOf(floatTest), floatWrapperValue);
final byte byteValue = mapper.readValue(asArray(byteTest), Byte.TYPE);
assertEquals(byteTest, byteValue);
final Byte byteWrapperValue = mapper.readValue(asArray(Byte.valueOf(byteTest)), Byte.class);
assertEquals(Byte.valueOf(byteTest), byteWrapperValue);
final char charValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.TYPE);
assertEquals(charTest, charValue);
final Character charWrapperValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.class);
assertEquals(Character.valueOf(charTest), charWrapperValue);
final boolean booleanTrueValue = mapper.readValue(asArray(true), Boolean.TYPE);
assertTrue(booleanTrueValue);
final boolean booleanFalseValue = mapper.readValue(asArray(false), Boolean.TYPE);
assertFalse(booleanFalseValue);
final Boolean booleanWrapperTrueValue = mapper.readValue(asArray(Boolean.valueOf(true)), Boolean.class);
assertEquals(Boolean.TRUE, booleanWrapperTrueValue);
}
private static String asArray(Object value) {
final String stringVal = value.toString();
return new StringBuilder(stringVal.length() + 2).append("[").append(stringVal).append("]").toString();
}
public void testSingleElementArrayException() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
try {
mapper.readValue("[42]", Integer.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42]", Integer.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.273]", Double.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.2723]", Double.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342]", Long.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342342]", Long.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42]", Short.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42]", Short.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[327.2323]", Float.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[82.81902]", Float.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22]", Byte.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22]", Byte.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("['d']", Character.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("['d']", Character.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true]", Boolean.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true]", Boolean.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
}
public void testMultiValueArrayException() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
try {
mapper.readValue("[42,42]", Integer.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42,42]", Integer.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.273,42.273]", Double.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.2723,42.273]", Double.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342,42342342342342]", Long.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342342,42342342342342]", Long.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42,42]", Short.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42,42]", Short.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[327.2323,327.2323]", Float.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[82.81902,327.2323]", Float.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22,23]", Byte.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22,23]", Byte.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true,false]", Boolean.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true,false]", Boolean.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
}
} | // You are a professional Java test case writer, please create a test case named `testLocale` for the issue `JacksonDatabind-1123`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1123
//
// ## Issue-Title:
// Serializing and Deserializing Locale.ROOT
//
// ## Issue-Description:
// Serializing and Deserializing Locale objects seems to work just fine, until you try on the Root Locale.
//
// It writes it out as an empty string and when it reads it in, the value is null
//
//
//
// ```
// @Test
// public void testLocaleDeserialization() throws IOException {
// ObjectMapper objectMapper = new ObjectMapper();
// Locale root = Locale.ROOT;
// String json = objectMapper.writeValueAsString(root);
// System.out.printf("Root Locale: '%s'", json);
// Locale actual = objectMapper.readValue(json, Locale.class);
// Assert.assertEquals(root, actual);
// }
//
// ```
//
// Here is the output:
//
// Root Locale: '""'
//
// java.lang.AssertionError:
//
// Expected :
//
// Actual :null
//
//
//
//
public void testLocale() throws IOException {
| 150 | 42 | 141 | src/test/java/com/fasterxml/jackson/databind/deser/TestJdkTypes.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1123
## Issue-Title:
Serializing and Deserializing Locale.ROOT
## Issue-Description:
Serializing and Deserializing Locale objects seems to work just fine, until you try on the Root Locale.
It writes it out as an empty string and when it reads it in, the value is null
```
@Test
public void testLocaleDeserialization() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Locale root = Locale.ROOT;
String json = objectMapper.writeValueAsString(root);
System.out.printf("Root Locale: '%s'", json);
Locale actual = objectMapper.readValue(json, Locale.class);
Assert.assertEquals(root, actual);
}
```
Here is the output:
Root Locale: '""'
java.lang.AssertionError:
Expected :
Actual :null
```
You are a professional Java test case writer, please create a test case named `testLocale` for the issue `JacksonDatabind-1123`, utilizing the provided issue report information and the following function signature.
```java
public void testLocale() throws IOException {
```
| 141 | [
"com.fasterxml.jackson.databind.deser.std.FromStringDeserializer"
] | 3d5d16e1554b998a5a8d7bb4c7ed9bb525ce23c6224ac7fbebd6029b7090c004 | public void testLocale() throws IOException
| // You are a professional Java test case writer, please create a test case named `testLocale` for the issue `JacksonDatabind-1123`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1123
//
// ## Issue-Title:
// Serializing and Deserializing Locale.ROOT
//
// ## Issue-Description:
// Serializing and Deserializing Locale objects seems to work just fine, until you try on the Root Locale.
//
// It writes it out as an empty string and when it reads it in, the value is null
//
//
//
// ```
// @Test
// public void testLocaleDeserialization() throws IOException {
// ObjectMapper objectMapper = new ObjectMapper();
// Locale root = Locale.ROOT;
// String json = objectMapper.writeValueAsString(root);
// System.out.printf("Root Locale: '%s'", json);
// Locale actual = objectMapper.readValue(json, Locale.class);
// Assert.assertEquals(root, actual);
// }
//
// ```
//
// Here is the output:
//
// Root Locale: '""'
//
// java.lang.AssertionError:
//
// Expected :
//
// Actual :null
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.deser;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class TestJdkTypes extends BaseMapTest
{
static class PrimitivesBean
{
public boolean booleanValue = true;
public byte byteValue = 3;
public char charValue = 'a';
public short shortValue = 37;
public int intValue = 1;
public long longValue = 100L;
public float floatValue = 0.25f;
public double doubleValue = -1.0;
}
static class WrappersBean
{
public Boolean booleanValue;
public Byte byteValue;
public Character charValue;
public Short shortValue;
public Integer intValue;
public Long longValue;
public Float floatValue;
public Double doubleValue;
}
static class ParamClassBean
{
public String name = "bar";
public Class<String> clazz ;
public ParamClassBean() { }
public ParamClassBean(String name) {
this.name = name;
clazz = String.class;
}
}
static class BooleanBean {
public Boolean wrapper;
public boolean primitive;
protected Boolean ctor;
@JsonCreator
public BooleanBean(@JsonProperty("ctor") Boolean foo) {
ctor = foo;
}
}
// [Issue#429]
static class StackTraceBean {
public final static int NUM = 13;
@JsonProperty("Location")
@JsonDeserialize(using=MyStackTraceElementDeserializer.class)
protected StackTraceElement location;
}
@SuppressWarnings("serial")
static class MyStackTraceElementDeserializer extends StdDeserializer<StackTraceElement>
{
public MyStackTraceElementDeserializer() { super(StackTraceElement.class); }
@Override
public StackTraceElement deserialize(JsonParser jp,
DeserializationContext ctxt) throws IOException, JsonProcessingException {
jp.skipChildren();
return new StackTraceElement("a", "b", "b", StackTraceBean.NUM);
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
/**
* Related to issues [JACKSON-155], [#170].
*/
public void testFile() throws Exception
{
// Not portable etc... has to do:
File src = new File("/test").getAbsoluteFile();
String abs = src.getAbsolutePath();
// escape backslashes (for portability with windows)
String json = MAPPER.writeValueAsString(abs);
File result = MAPPER.readValue(json, File.class);
assertEquals(abs, result.getAbsolutePath());
// Then #170
final ObjectMapper mapper2 = new ObjectMapper();
mapper2.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);
result = mapper2.readValue(json, File.class);
assertEquals(abs, result.getAbsolutePath());
}
public void testRegexps() throws IOException
{
final String PATTERN_STR = "abc:\\s?(\\d+)";
Pattern exp = Pattern.compile(PATTERN_STR);
/* Ok: easiest way is to just serialize first; problem
* is the backslash
*/
String json = MAPPER.writeValueAsString(exp);
Pattern result = MAPPER.readValue(json, Pattern.class);
assertEquals(exp.pattern(), result.pattern());
}
public void testCurrency() throws IOException
{
Currency usd = Currency.getInstance("USD");
assertEquals(usd, new ObjectMapper().readValue(quote("USD"), Currency.class));
}
public void testLocale() throws IOException
{
assertEquals(new Locale("en"), MAPPER.readValue(quote("en"), Locale.class));
assertEquals(new Locale("es", "ES"), MAPPER.readValue(quote("es_ES"), Locale.class));
assertEquals(new Locale("FI", "fi", "savo"),
MAPPER.readValue(quote("fi_FI_savo"), Locale.class));
// [databind#1123]
Locale loc = MAPPER.readValue(quote(""), Locale.class);
assertSame(Locale.ROOT, loc);
}
public void testNullForPrimitives() throws IOException
{
// by default, ok to rely on defaults
PrimitivesBean bean = MAPPER.readValue("{\"intValue\":null, \"booleanValue\":null, \"doubleValue\":null}",
PrimitivesBean.class);
assertNotNull(bean);
assertEquals(0, bean.intValue);
assertEquals(false, bean.booleanValue);
assertEquals(0.0, bean.doubleValue);
bean = MAPPER.readValue("{\"byteValue\":null, \"longValue\":null, \"floatValue\":null}",
PrimitivesBean.class);
assertNotNull(bean);
assertEquals((byte) 0, bean.byteValue);
assertEquals(0L, bean.longValue);
assertEquals(0.0f, bean.floatValue);
// but not when enabled
final ObjectMapper mapper2 = new ObjectMapper();
mapper2.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);
// boolean
try {
mapper2.readValue("{\"booleanValue\":null}", PrimitivesBean.class);
fail("Expected failure for boolean + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type boolean");
}
// byte/char/short/int/long
try {
mapper2.readValue("{\"byteValue\":null}", PrimitivesBean.class);
fail("Expected failure for byte + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type byte");
}
try {
mapper2.readValue("{\"charValue\":null}", PrimitivesBean.class);
fail("Expected failure for char + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type char");
}
try {
mapper2.readValue("{\"shortValue\":null}", PrimitivesBean.class);
fail("Expected failure for short + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type short");
}
try {
mapper2.readValue("{\"intValue\":null}", PrimitivesBean.class);
fail("Expected failure for int + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type int");
}
try {
mapper2.readValue("{\"longValue\":null}", PrimitivesBean.class);
fail("Expected failure for long + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type long");
}
// float/double
try {
mapper2.readValue("{\"floatValue\":null}", PrimitivesBean.class);
fail("Expected failure for float + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type float");
}
try {
mapper2.readValue("{\"doubleValue\":null}", PrimitivesBean.class);
fail("Expected failure for double + null");
} catch (JsonMappingException e) {
verifyException(e, "Can not map JSON null into type double");
}
}
/**
* Test for [JACKSON-483], allow handling of CharSequence
*/
public void testCharSequence() throws IOException
{
CharSequence cs = MAPPER.readValue("\"abc\"", CharSequence.class);
assertEquals(String.class, cs.getClass());
assertEquals("abc", cs.toString());
}
// [JACKSON-484]
public void testInetAddress() throws IOException
{
InetAddress address = MAPPER.readValue(quote("127.0.0.1"), InetAddress.class);
assertEquals("127.0.0.1", address.getHostAddress());
// should we try resolving host names? That requires connectivity...
final String HOST = "google.com";
address = MAPPER.readValue(quote(HOST), InetAddress.class);
assertEquals(HOST, address.getHostName());
}
public void testInetSocketAddress() throws IOException
{
InetSocketAddress address = MAPPER.readValue(quote("127.0.0.1"), InetSocketAddress.class);
assertEquals("127.0.0.1", address.getAddress().getHostAddress());
InetSocketAddress ip6 = MAPPER.readValue(
quote("2001:db8:85a3:8d3:1319:8a2e:370:7348"), InetSocketAddress.class);
assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6.getAddress().getHostAddress());
InetSocketAddress ip6port = MAPPER.readValue(
quote("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443"), InetSocketAddress.class);
assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", ip6port.getAddress().getHostAddress());
assertEquals(443, ip6port.getPort());
// should we try resolving host names? That requires connectivity...
final String HOST = "www.google.com";
address = MAPPER.readValue(quote(HOST), InetSocketAddress.class);
assertEquals(HOST, address.getHostName());
final String HOST_AND_PORT = HOST+":80";
address = MAPPER.readValue(quote(HOST_AND_PORT), InetSocketAddress.class);
assertEquals(HOST, address.getHostName());
assertEquals(80, address.getPort());
}
// [JACKSON-597]
public void testClass() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
assertSame(String.class, mapper.readValue(quote("java.lang.String"), Class.class));
// then primitive types
assertSame(Boolean.TYPE, mapper.readValue(quote("boolean"), Class.class));
assertSame(Byte.TYPE, mapper.readValue(quote("byte"), Class.class));
assertSame(Short.TYPE, mapper.readValue(quote("short"), Class.class));
assertSame(Character.TYPE, mapper.readValue(quote("char"), Class.class));
assertSame(Integer.TYPE, mapper.readValue(quote("int"), Class.class));
assertSame(Long.TYPE, mapper.readValue(quote("long"), Class.class));
assertSame(Float.TYPE, mapper.readValue(quote("float"), Class.class));
assertSame(Double.TYPE, mapper.readValue(quote("double"), Class.class));
assertSame(Void.TYPE, mapper.readValue(quote("void"), Class.class));
}
// [JACKSON-605]
public void testClassWithParams() throws IOException
{
String json = MAPPER.writeValueAsString(new ParamClassBean("Foobar"));
ParamClassBean result = MAPPER.readValue(json, ParamClassBean.class);
assertEquals("Foobar", result.name);
assertSame(String.class, result.clazz);
}
// by default, should return nulls, n'est pas?
public void testEmptyStringForWrappers() throws IOException
{
WrappersBean bean;
// by default, ok to rely on defaults
bean = MAPPER.readValue("{\"booleanValue\":\"\"}", WrappersBean.class);
assertNull(bean.booleanValue);
bean = MAPPER.readValue("{\"byteValue\":\"\"}", WrappersBean.class);
assertNull(bean.byteValue);
// char/Character is different... not sure if this should work or not:
bean = MAPPER.readValue("{\"charValue\":\"\"}", WrappersBean.class);
assertNull(bean.charValue);
bean = MAPPER.readValue("{\"shortValue\":\"\"}", WrappersBean.class);
assertNull(bean.shortValue);
bean = MAPPER.readValue("{\"intValue\":\"\"}", WrappersBean.class);
assertNull(bean.intValue);
bean = MAPPER.readValue("{\"longValue\":\"\"}", WrappersBean.class);
assertNull(bean.longValue);
bean = MAPPER.readValue("{\"floatValue\":\"\"}", WrappersBean.class);
assertNull(bean.floatValue);
bean = MAPPER.readValue("{\"doubleValue\":\"\"}", WrappersBean.class);
assertNull(bean.doubleValue);
}
// for [JACKSON-616]
// @since 1.9
public void testEmptyStringForPrimitives() throws IOException
{
PrimitivesBean bean;
bean = MAPPER.readValue("{\"booleanValue\":\"\"}", PrimitivesBean.class);
assertFalse(bean.booleanValue);
bean = MAPPER.readValue("{\"byteValue\":\"\"}", PrimitivesBean.class);
assertEquals((byte) 0, bean.byteValue);
bean = MAPPER.readValue("{\"charValue\":\"\"}", PrimitivesBean.class);
assertEquals((char) 0, bean.charValue);
bean = MAPPER.readValue("{\"shortValue\":\"\"}", PrimitivesBean.class);
assertEquals((short) 0, bean.shortValue);
bean = MAPPER.readValue("{\"intValue\":\"\"}", PrimitivesBean.class);
assertEquals(0, bean.intValue);
bean = MAPPER.readValue("{\"longValue\":\"\"}", PrimitivesBean.class);
assertEquals(0L, bean.longValue);
bean = MAPPER.readValue("{\"floatValue\":\"\"}", PrimitivesBean.class);
assertEquals(0.0f, bean.floatValue);
bean = MAPPER.readValue("{\"doubleValue\":\"\"}", PrimitivesBean.class);
assertEquals(0.0, bean.doubleValue);
}
// for [JACKSON-652]
// @since 1.9
public void testUntypedWithJsonArrays() throws Exception
{
// by default we get:
Object ob = MAPPER.readValue("[1]", Object.class);
assertTrue(ob instanceof List<?>);
// but can change to produce Object[]:
MAPPER.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
ob = MAPPER.readValue("[1]", Object.class);
assertEquals(Object[].class, ob.getClass());
}
// Test for verifying that Long values are coerced to boolean correctly as well
public void testLongToBoolean() throws Exception
{
long value = 1L + Integer.MAX_VALUE;
BooleanBean b = MAPPER.readValue("{\"primitive\" : "+value+", \"wrapper\":"+value+", \"ctor\":"+value+"}",
BooleanBean.class);
assertEquals(Boolean.TRUE, b.wrapper);
assertTrue(b.primitive);
assertEquals(Boolean.TRUE, b.ctor);
}
// [JACKSON-789]
public void testCharset() throws Exception
{
Charset UTF8 = Charset.forName("UTF-8");
assertSame(UTF8, MAPPER.readValue(quote("UTF-8"), Charset.class));
}
// [JACKSON-888]
public void testStackTraceElement() throws Exception
{
StackTraceElement elem = null;
try {
throw new IllegalStateException();
} catch (Exception e) {
elem = e.getStackTrace()[0];
}
String json = MAPPER.writeValueAsString(elem);
StackTraceElement back = MAPPER.readValue(json, StackTraceElement.class);
assertEquals("testStackTraceElement", back.getMethodName());
assertEquals(elem.getLineNumber(), back.getLineNumber());
assertEquals(elem.getClassName(), back.getClassName());
assertEquals(elem.isNativeMethod(), back.isNativeMethod());
assertTrue(back.getClassName().endsWith("TestJdkTypes"));
assertFalse(back.isNativeMethod());
}
// [Issue#239]
public void testByteBuffer() throws Exception
{
byte[] INPUT = new byte[] { 1, 3, 9, -1, 6 };
String exp = MAPPER.writeValueAsString(INPUT);
ByteBuffer result = MAPPER.readValue(exp, ByteBuffer.class);
assertNotNull(result);
assertEquals(INPUT.length, result.remaining());
for (int i = 0; i < INPUT.length; ++i) {
assertEquals(INPUT[i], result.get());
}
assertEquals(0, result.remaining());
}
public void testStringBuilder() throws Exception
{
StringBuilder sb = MAPPER.readValue(quote("abc"), StringBuilder.class);
assertEquals("abc", sb.toString());
}
// [Issue#429]
public void testStackTraceElementWithCustom() throws Exception
{
// first, via bean that contains StackTraceElement
StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"),
StackTraceBean.class);
assertNotNull(bean);
assertNotNull(bean.location);
assertEquals(StackTraceBean.NUM, bean.location.getLineNumber());
// and then directly, iff registered
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(StackTraceElement.class, new MyStackTraceElementDeserializer());
mapper.registerModule(module);
StackTraceElement elem = mapper.readValue("123", StackTraceElement.class);
assertNotNull(elem);
assertEquals(StackTraceBean.NUM, elem.getLineNumber());
// and finally, even as part of real exception
IOException ioe = mapper.readValue(aposToQuotes("{'stackTrace':[ 123, 456 ]}"),
IOException.class);
assertNotNull(ioe);
StackTraceElement[] traces = ioe.getStackTrace();
assertNotNull(traces);
assertEquals(2, traces.length);
assertEquals(StackTraceBean.NUM, traces[0].getLineNumber());
assertEquals(StackTraceBean.NUM, traces[1].getLineNumber());
}
/*
/**********************************************************
/* Single-array handling tests
/**********************************************************
*/
// [Issue#381]
public void testSingleElementArray() throws Exception {
final int intTest = 932832;
final double doubleTest = 32.3234;
final long longTest = 2374237428374293423L;
final short shortTest = (short) intTest;
final float floatTest = 84.3743f;
final byte byteTest = (byte) 43;
final char charTest = 'c';
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
final int intValue = mapper.readValue(asArray(intTest), Integer.TYPE);
assertEquals(intTest, intValue);
final Integer integerWrapperValue = mapper.readValue(asArray(Integer.valueOf(intTest)), Integer.class);
assertEquals(Integer.valueOf(intTest), integerWrapperValue);
final double doubleValue = mapper.readValue(asArray(doubleTest), Double.class);
assertEquals(doubleTest, doubleValue);
final Double doubleWrapperValue = mapper.readValue(asArray(Double.valueOf(doubleTest)), Double.class);
assertEquals(Double.valueOf(doubleTest), doubleWrapperValue);
final long longValue = mapper.readValue(asArray(longTest), Long.TYPE);
assertEquals(longTest, longValue);
final Long longWrapperValue = mapper.readValue(asArray(Long.valueOf(longTest)), Long.class);
assertEquals(Long.valueOf(longTest), longWrapperValue);
final short shortValue = mapper.readValue(asArray(shortTest), Short.TYPE);
assertEquals(shortTest, shortValue);
final Short shortWrapperValue = mapper.readValue(asArray(Short.valueOf(shortTest)), Short.class);
assertEquals(Short.valueOf(shortTest), shortWrapperValue);
final float floatValue = mapper.readValue(asArray(floatTest), Float.TYPE);
assertEquals(floatTest, floatValue);
final Float floatWrapperValue = mapper.readValue(asArray(Float.valueOf(floatTest)), Float.class);
assertEquals(Float.valueOf(floatTest), floatWrapperValue);
final byte byteValue = mapper.readValue(asArray(byteTest), Byte.TYPE);
assertEquals(byteTest, byteValue);
final Byte byteWrapperValue = mapper.readValue(asArray(Byte.valueOf(byteTest)), Byte.class);
assertEquals(Byte.valueOf(byteTest), byteWrapperValue);
final char charValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.TYPE);
assertEquals(charTest, charValue);
final Character charWrapperValue = mapper.readValue(asArray(quote(String.valueOf(charTest))), Character.class);
assertEquals(Character.valueOf(charTest), charWrapperValue);
final boolean booleanTrueValue = mapper.readValue(asArray(true), Boolean.TYPE);
assertTrue(booleanTrueValue);
final boolean booleanFalseValue = mapper.readValue(asArray(false), Boolean.TYPE);
assertFalse(booleanFalseValue);
final Boolean booleanWrapperTrueValue = mapper.readValue(asArray(Boolean.valueOf(true)), Boolean.class);
assertEquals(Boolean.TRUE, booleanWrapperTrueValue);
}
private static String asArray(Object value) {
final String stringVal = value.toString();
return new StringBuilder(stringVal.length() + 2).append("[").append(stringVal).append("]").toString();
}
public void testSingleElementArrayException() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
try {
mapper.readValue("[42]", Integer.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42]", Integer.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.273]", Double.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.2723]", Double.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342]", Long.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342342]", Long.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42]", Short.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42]", Short.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[327.2323]", Float.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[82.81902]", Float.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22]", Byte.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22]", Byte.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("['d']", Character.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("['d']", Character.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true]", Boolean.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true]", Boolean.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
}
public void testMultiValueArrayException() throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
try {
mapper.readValue("[42,42]", Integer.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42,42]", Integer.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.273,42.273]", Double.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42.2723,42.273]", Double.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342,42342342342342]", Long.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42342342342342342,42342342342342]", Long.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42,42]", Short.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[42,42]", Short.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[327.2323,327.2323]", Float.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[82.81902,327.2323]", Float.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22,23]", Byte.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[22,23]", Byte.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue(asArray(quote("c") + "," + quote("d")), Character.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true,false]", Boolean.class);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
try {
mapper.readValue("[true,false]", Boolean.TYPE);
fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
} catch (JsonMappingException exp) {
//Exception was thrown correctly
}
}
} |
||
public void testcharSequenceKeyMap() throws Exception {
String JSON = aposToQuotes("{'a':'b'}");
Map<CharSequence,String> result = MAPPER.readValue(JSON, new TypeReference<Map<CharSequence,String>>() { });
assertNotNull(result);
assertEquals(1, result.size());
assertEquals("b", result.get("a"));
} | com.fasterxml.jackson.databind.deser.TestMapDeserialization::testcharSequenceKeyMap | src/test/java/com/fasterxml/jackson/databind/deser/TestMapDeserialization.java | 510 | src/test/java/com/fasterxml/jackson/databind/deser/TestMapDeserialization.java | testcharSequenceKeyMap | package com.fasterxml.jackson.databind.deser;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
@SuppressWarnings("serial")
public class TestMapDeserialization
extends BaseMapTest
{
static enum Key {
KEY1, KEY2, WHATEVER;
}
static class BrokenMap
extends HashMap<Object,Object>
{
// No default ctor, nor @JsonCreators
public BrokenMap(boolean dummy) { super(); }
}
@JsonDeserialize(using=MapDeserializer.class)
static class CustomMap extends LinkedHashMap<String,String> { }
static class MapDeserializer extends StdDeserializer<CustomMap>
{
public MapDeserializer() { super(CustomMap.class); }
@Override
public CustomMap deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException
{
CustomMap result = new CustomMap();
result.put("x", jp.getText());
return result;
}
}
static class KeyType {
protected String value;
private KeyType(String v, boolean bogus) {
value = v;
}
@JsonCreator
public static KeyType create(String v) {
return new KeyType(v, true);
}
}
// Issue #142
public static class EnumMapContainer {
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public EnumMap<KeyEnum,ITestType> testTypes;
}
public static class ListContainer {
public List<ITestType> testTypes;
}
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public static interface ITestType { }
public static enum KeyEnum {
A, B
}
public static enum ConcreteType implements ITestType {
ONE, TWO;
}
static class ClassStringMap extends HashMap<Class<?>,String> { }
/*
/**********************************************************
/* Test methods, untyped (Object valued) maps
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testUntypedMap() throws Exception
{
// to get "untyped" default map-to-map, pass Object.class
String JSON = "{ \"foo\" : \"bar\", \"crazy\" : true, \"null\" : null }";
// Not a guaranteed cast theoretically, but will work:
@SuppressWarnings("unchecked")
Map<String,Object> result = (Map<String,Object>)MAPPER.readValue(JSON, Object.class);
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(3, result.size());
assertEquals("bar", result.get("foo"));
assertEquals(Boolean.TRUE, result.get("crazy"));
assertNull(result.get("null"));
// Plus, non existing:
assertNull(result.get("bar"));
assertNull(result.get(3));
}
public void testBigUntypedMap() throws Exception
{
Map<String,Object> map = new LinkedHashMap<String,Object>();
for (int i = 0; i < 1100; ++i) {
if ((i & 1) == 0) {
map.put(String.valueOf(i), Integer.valueOf(i));
} else {
Map<String,Object> map2 = new LinkedHashMap<String,Object>();
map2.put("x", Integer.valueOf(i));
map.put(String.valueOf(i), map2);
}
}
String json = MAPPER.writeValueAsString(map);
Object bound = MAPPER.readValue(json, Object.class);
assertEquals(map, bound);
}
/**
* Let's also try another way to express "gimme a Map" deserialization;
* this time by specifying a Map class, to reduce need to cast
*/
public void testUntypedMap2() throws Exception
{
// to get "untyped" default map-to-map, pass Object.class
String JSON = "{ \"a\" : \"x\" }";
@SuppressWarnings("unchecked")
HashMap<String,Object> result = /*(HashMap<String,Object>)*/ MAPPER.readValue(JSON, HashMap.class);
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(1, result.size());
assertEquals("x", result.get("a"));
}
/**
* Unit test for [JACKSON-185]
*/
public void testUntypedMap3() throws Exception
{
String JSON = "{\"a\":[{\"a\":\"b\"},\"value\"]}";
Map<?,?> result = MAPPER.readValue(JSON, Map.class);
assertTrue(result instanceof Map<?,?>);
assertEquals(1, result.size());
Object ob = result.get("a");
assertNotNull(ob);
Collection<?> list = (Collection<?>)ob;
assertEquals(2, list.size());
JSON = "{ \"var1\":\"val1\", \"var2\":\"val2\", "
+"\"subvars\": ["
+" { \"subvar1\" : \"subvar2\", \"x\" : \"y\" }, "
+" { \"a\":1 } ]"
+" }"
;
result = MAPPER.readValue(JSON, Map.class);
assertTrue(result instanceof Map<?,?>);
assertEquals(3, result.size());
}
private static final String UNTYPED_MAP_JSON =
"{ \"double\":42.0, \"string\":\"string\","
+"\"boolean\":true, \"list\":[\"list0\"],"
+"\"null\":null }";
static class ObjectWrapperMap extends HashMap<String, ObjectWrapper> { }
public void testSpecialMap() throws IOException
{
final ObjectWrapperMap map = MAPPER.readValue(UNTYPED_MAP_JSON, ObjectWrapperMap.class);
assertNotNull(map);
_doTestUntyped(map);
}
public void testGenericMap() throws IOException
{
final Map<String, ObjectWrapper> map = MAPPER.readValue
(UNTYPED_MAP_JSON,
new TypeReference<Map<String, ObjectWrapper>>() { });
_doTestUntyped(map);
}
private void _doTestUntyped(final Map<String, ObjectWrapper> map)
{
ObjectWrapper w = map.get("double");
assertNotNull(w);
assertEquals(Double.valueOf(42), w.getObject());
assertEquals("string", map.get("string").getObject());
assertEquals(Boolean.TRUE, map.get("boolean").getObject());
assertEquals(Collections.singletonList("list0"), map.get("list").getObject());
assertTrue(map.containsKey("null"));
assertNull(map.get("null"));
assertEquals(5, map.size());
}
// [JACKSON-620]: allow "" to mean 'null' for Maps
public void testFromEmptyString() throws Exception
{
ObjectMapper m = new ObjectMapper();
m.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Map<?,?> result = m.readValue(quote(""), Map.class);
assertNull(result);
}
/*
/**********************************************************
/* Test methods, typed maps
/**********************************************************
*/
public void testExactStringIntMap() throws Exception
{
// to get typing, must use type reference
String JSON = "{ \"foo\" : 13, \"bar\" : -39, \n \"\" : 0 }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<HashMap<String,Integer>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(3, result.size());
assertEquals(Integer.valueOf(13), result.get("foo"));
assertEquals(Integer.valueOf(-39), result.get("bar"));
assertEquals(Integer.valueOf(0), result.get(""));
assertNull(result.get("foobar"));
assertNull(result.get(" "));
}
/**
* Let's also check that it is possible to do type conversions
* to allow use of non-String Map keys.
*/
public void testIntBooleanMap() throws Exception
{
// to get typing, must use type reference
String JSON = "{ \"1\" : true, \"-1\" : false }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<HashMap<Integer,Boolean>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(2, result.size());
assertEquals(Boolean.TRUE, result.get(Integer.valueOf(1)));
assertEquals(Boolean.FALSE, result.get(Integer.valueOf(-1)));
assertNull(result.get("foobar"));
assertNull(result.get(0));
}
public void testExactStringStringMap() throws Exception
{
// to get typing, must use type reference
String JSON = "{ \"a\" : \"b\" }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<TreeMap<String,String>>() { });
assertNotNull(result);
assertEquals(TreeMap.class, result.getClass());
assertEquals(1, result.size());
assertEquals("b", result.get("a"));
assertNull(result.get("b"));
}
/**
* Unit test that verifies that it's ok to have incomplete
* information about Map class itself, as long as it's something
* we good guess about: for example, <code>Map.Class</code> will
* be replaced by something like <code>HashMap.class</code>,
* if given.
*/
public void testGenericStringIntMap() throws Exception
{
// to get typing, must use type reference; but with abstract type
String JSON = "{ \"a\" : 1, \"b\" : 2, \"c\" : -99 }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<Map<String,Integer>>() { });
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(3, result.size());
assertEquals(Integer.valueOf(-99), result.get("c"));
assertEquals(Integer.valueOf(2), result.get("b"));
assertEquals(Integer.valueOf(1), result.get("a"));
assertNull(result.get(""));
}
// [Databind#540]
public void testMapFromEmptyArray() throws Exception
{
final String JSON = " [\n]";
assertFalse(MAPPER.isEnabled(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT));
// first, verify default settings which do not accept empty Array
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(JSON, Map.class);
fail("Should not accept Empty Array for Map by default");
} catch (JsonProcessingException e) {
verifyException(e, "START_ARRAY token");
}
// should be ok to enable dynamically:
ObjectReader r = MAPPER.readerFor(Map.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
Map<?,?> result = r.readValue(JSON);
assertNull(result);
EnumMap<?,?> result2 = r.forType(new TypeReference<EnumMap<Key,String>>() { })
.readValue(JSON);
assertNull(result2);
}
/*
/**********************************************************
/* Test methods, maps with enums
/**********************************************************
*/
public void testEnumMap() throws Exception
{
String JSON = "{ \"KEY1\" : \"\", \"WHATEVER\" : null }";
// to get typing, must use type reference
EnumMap<Key,String> result = MAPPER.readValue
(JSON, new TypeReference<EnumMap<Key,String>>() { });
assertNotNull(result);
assertEquals(EnumMap.class, result.getClass());
assertEquals(2, result.size());
assertEquals("", result.get(Key.KEY1));
// null should be ok too...
assertTrue(result.containsKey(Key.WHATEVER));
assertNull(result.get(Key.WHATEVER));
// plus we have nothing for this key
assertFalse(result.containsKey(Key.KEY2));
assertNull(result.get(Key.KEY2));
}
public void testMapWithEnums() throws Exception
{
String JSON = "{ \"KEY2\" : \"WHATEVER\" }";
// to get typing, must use type reference
Map<Enum<?>,Enum<?>> result = MAPPER.readValue
(JSON, new TypeReference<Map<Key,Key>>() { });
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(1, result.size());
assertEquals(Key.WHATEVER, result.get(Key.KEY2));
assertNull(result.get(Key.WHATEVER));
assertNull(result.get(Key.KEY1));
}
public void testEnumPolymorphicSerializationTest() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
List<ITestType> testTypesList = new ArrayList<ITestType>();
testTypesList.add(ConcreteType.ONE);
testTypesList.add(ConcreteType.TWO);
ListContainer listContainer = new ListContainer();
listContainer.testTypes = testTypesList;
String json = mapper.writeValueAsString(listContainer);
listContainer = mapper.readValue(json, ListContainer.class);
EnumMapContainer enumMapContainer = new EnumMapContainer();
EnumMap<KeyEnum,ITestType> testTypesMap = new EnumMap<KeyEnum,ITestType>(KeyEnum.class);
testTypesMap.put(KeyEnum.A, ConcreteType.ONE);
testTypesMap.put(KeyEnum.B, ConcreteType.TWO);
enumMapContainer.testTypes = testTypesMap;
json = mapper.writeValueAsString(enumMapContainer);
enumMapContainer = mapper.readValue(json, EnumMapContainer.class);
}
/*
/**********************************************************
/* Test methods, maps with Date
/**********************************************************
*/
public void testDateMap() throws Exception
{
Date date1=new Date(123456000L);
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
String JSON = "{ \""+ fmt.format(date1)+"\" : \"\", \""+new Date(0).getTime()+"\" : null }";
HashMap<Date,String> result= MAPPER.readValue
(JSON, new TypeReference<HashMap<Date,String>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(2, result.size());
assertTrue(result.containsKey(date1));
assertEquals("", result.get(new Date(123456000L)));
assertTrue(result.containsKey(new Date(0)));
assertNull(result.get(new Date(0)));
}
/*
/**********************************************************
/* Test methods, maps with various alternative key types
/**********************************************************
*/
public void testCalendarMap() throws Exception
{
// 18-Jun-2015, tatu: Should be safest to use default timezone that mapper would use
TimeZone tz = MAPPER.getSerializationConfig().getTimeZone();
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(123456000L);
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
String JSON = "{ \""+fmt.format(c.getTime())+"\" : \"\", \""+new Date(0).getTime()+"\" : null }";
HashMap<Calendar,String> result = MAPPER.readValue
(JSON, new TypeReference<HashMap<Calendar,String>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(2, result.size());
assertTrue(result.containsKey(c));
assertEquals("", result.get(c));
c.setTimeInMillis(0);
assertTrue(result.containsKey(c));
assertNull(result.get(c));
}
public void testUUIDKeyMap() throws Exception
{
UUID key = UUID.nameUUIDFromBytes("foobar".getBytes("UTF-8"));
String JSON = "{ \""+key+"\":4}";
Map<UUID,Object> result = MAPPER.readValue(JSON, new TypeReference<Map<UUID,Object>>() { });
assertNotNull(result);
assertEquals(1, result.size());
Object ob = result.keySet().iterator().next();
assertNotNull(ob);
assertEquals(UUID.class, ob.getClass());
assertEquals(key, ob);
}
public void testLocaleKeyMap() throws Exception {
Locale key = Locale.CHINA;
String JSON = "{ \"" + key + "\":4}";
Map<Locale, Object> result = MAPPER.readValue(JSON, new TypeReference<Map<Locale, Object>>() {
});
assertNotNull(result);
assertEquals(1, result.size());
Object ob = result.keySet().iterator().next();
assertNotNull(ob);
assertEquals(Locale.class, ob.getClass());
assertEquals(key, ob);
}
public void testCurrencyKeyMap() throws Exception {
Currency key = Currency.getInstance("USD");
String JSON = "{ \"" + key + "\":4}";
Map<Currency, Object> result = MAPPER.readValue(JSON, new TypeReference<Map<Currency, Object>>() {
});
assertNotNull(result);
assertEquals(1, result.size());
Object ob = result.keySet().iterator().next();
assertNotNull(ob);
assertEquals(Currency.class, ob.getClass());
assertEquals(key, ob);
}
// Test confirming that @JsonCreator may be used with Map Key types
public void testKeyWithCreator() throws Exception
{
// first, key should deserialize normally:
KeyType key = MAPPER.readValue(quote("abc"), KeyType.class);
assertEquals("abc", key.value);
Map<KeyType,Integer> map = MAPPER.readValue("{\"foo\":3}", new TypeReference<Map<KeyType,Integer>>() {} );
assertEquals(1, map.size());
key = map.keySet().iterator().next();
assertEquals("foo", key.value);
}
public void testClassKeyMap() throws Exception {
ClassStringMap map = MAPPER.readValue(aposToQuotes("{'java.lang.String':'foo'}"),
ClassStringMap.class);
assertNotNull(map);
assertEquals(1, map.size());
assertEquals("foo", map.get(String.class));
}
public void testcharSequenceKeyMap() throws Exception {
String JSON = aposToQuotes("{'a':'b'}");
Map<CharSequence,String> result = MAPPER.readValue(JSON, new TypeReference<Map<CharSequence,String>>() { });
assertNotNull(result);
assertEquals(1, result.size());
assertEquals("b", result.get("a"));
}
/*
/**********************************************************
/* Test methods, annotated Maps
/**********************************************************
*/
/**
* Simple test to ensure that @JsonDeserialize.using is
* recognized
*/
public void testMapWithDeserializer() throws Exception
{
CustomMap result = MAPPER.readValue(quote("xyz"), CustomMap.class);
assertEquals(1, result.size());
assertEquals("xyz", result.get("x"));
}
/*
/**********************************************************
/* Test methods, annotated Map.Entry
/**********************************************************
*/
public void testMapEntrySimpleTypes() throws Exception
{
List<Map.Entry<String,Long>> stuff = MAPPER.readValue(aposToQuotes("[{'a':15},{'b':42}]"),
new TypeReference<List<Map.Entry<String,Long>>>() { });
assertNotNull(stuff);
assertEquals(2, stuff.size());
assertNotNull(stuff.get(1));
assertEquals("b", stuff.get(1).getKey());
assertEquals(Long.valueOf(42), stuff.get(1).getValue());
}
public void testMapEntryWithStringBean() throws Exception
{
List<Map.Entry<Integer,StringWrapper>> stuff = MAPPER.readValue(aposToQuotes("[{'28':'Foo'},{'13':'Bar'}]"),
new TypeReference<List<Map.Entry<Integer,StringWrapper>>>() { });
assertNotNull(stuff);
assertEquals(2, stuff.size());
assertNotNull(stuff.get(1));
assertEquals(Integer.valueOf(13), stuff.get(1).getKey());
StringWrapper sw = stuff.get(1).getValue();
assertEquals("Bar", sw.str);
}
public void testMapEntryFail() throws Exception
{
try {
/*List<Map.Entry<Integer,StringWrapper>> stuff =*/ MAPPER.readValue(aposToQuotes("[{'28':'Foo','13':'Bar'}]"),
new TypeReference<List<Map.Entry<Integer,StringWrapper>>>() { });
fail("Should not have passed");
} catch (Exception e) {
verifyException(e, "more than one entry in JSON");
}
}
/*
/**********************************************************
/* Test methods, other exotic Map types
/**********************************************************
*/
// [databind#810]
public void testReadProperties() throws Exception
{
Properties props = MAPPER.readValue(aposToQuotes("{'a':'foo', 'b':123, 'c':true}"),
Properties.class);
assertEquals(3, props.size());
assertEquals("foo", props.getProperty("a"));
assertEquals("123", props.getProperty("b"));
assertEquals("true", props.getProperty("c"));
}
// JDK singletonMap
public void testSingletonMapRoundtrip() throws Exception
{
final TypeReference<?> type = new TypeReference<Map<String,IntWrapper>>() { };
String json = MAPPER.writeValueAsString(Collections.singletonMap("value", new IntWrapper(5)));
Map<String,IntWrapper> result = MAPPER.readValue(json, type);
assertNotNull(result);
assertEquals(1, result.size());
IntWrapper w = result.get("value");
assertNotNull(w);
assertEquals(5, w.i);
}
/*
/**********************************************************
/* Error tests
/**********************************************************
*/
public void testMapError() throws Exception
{
try {
Object result = MAPPER.readValue("[ 1, 2 ]",
new TypeReference<Map<String,String>>() { });
fail("Expected an exception, but got result value: "+result);
} catch (JsonMappingException jex) {
verifyException(jex, "START_ARRAY");
}
}
public void testNoCtorMap() throws Exception
{
try {
BrokenMap result = MAPPER.readValue("{ \"a\" : 3 }", BrokenMap.class);
// should never get here; assert added to remove compiler warning
assertNull(result);
} catch (JsonMappingException e) {
// instead, should get this exception:
verifyException(e, "no default constructor found");
}
}
} | // You are a professional Java test case writer, please create a test case named `testcharSequenceKeyMap` for the issue `JacksonDatabind-1506`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1506
//
// ## Issue-Title:
// Missing KeyDeserializer for CharSequence
//
// ## Issue-Description:
// Looks like use of nominal Map key type of `CharSequence` does not work yet (as of 2.7.8 / 2.8.6).
//
// This is something that is needed to work with certain frameworks, such as Avro's generated POJOs.
//
//
//
//
public void testcharSequenceKeyMap() throws Exception {
| 510 | 71 | 504 | src/test/java/com/fasterxml/jackson/databind/deser/TestMapDeserialization.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1506
## Issue-Title:
Missing KeyDeserializer for CharSequence
## Issue-Description:
Looks like use of nominal Map key type of `CharSequence` does not work yet (as of 2.7.8 / 2.8.6).
This is something that is needed to work with certain frameworks, such as Avro's generated POJOs.
```
You are a professional Java test case writer, please create a test case named `testcharSequenceKeyMap` for the issue `JacksonDatabind-1506`, utilizing the provided issue report information and the following function signature.
```java
public void testcharSequenceKeyMap() throws Exception {
```
| 504 | [
"com.fasterxml.jackson.databind.deser.std.StdKeyDeserializer"
] | 3db1e9728642736e786c223d95a7188d961f82acfe9459a6d21b7d684cbcf0ad | public void testcharSequenceKeyMap() throws Exception | // You are a professional Java test case writer, please create a test case named `testcharSequenceKeyMap` for the issue `JacksonDatabind-1506`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1506
//
// ## Issue-Title:
// Missing KeyDeserializer for CharSequence
//
// ## Issue-Description:
// Looks like use of nominal Map key type of `CharSequence` does not work yet (as of 2.7.8 / 2.8.6).
//
// This is something that is needed to work with certain frameworks, such as Avro's generated POJOs.
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.deser;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
@SuppressWarnings("serial")
public class TestMapDeserialization
extends BaseMapTest
{
static enum Key {
KEY1, KEY2, WHATEVER;
}
static class BrokenMap
extends HashMap<Object,Object>
{
// No default ctor, nor @JsonCreators
public BrokenMap(boolean dummy) { super(); }
}
@JsonDeserialize(using=MapDeserializer.class)
static class CustomMap extends LinkedHashMap<String,String> { }
static class MapDeserializer extends StdDeserializer<CustomMap>
{
public MapDeserializer() { super(CustomMap.class); }
@Override
public CustomMap deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException
{
CustomMap result = new CustomMap();
result.put("x", jp.getText());
return result;
}
}
static class KeyType {
protected String value;
private KeyType(String v, boolean bogus) {
value = v;
}
@JsonCreator
public static KeyType create(String v) {
return new KeyType(v, true);
}
}
// Issue #142
public static class EnumMapContainer {
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public EnumMap<KeyEnum,ITestType> testTypes;
}
public static class ListContainer {
public List<ITestType> testTypes;
}
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public static interface ITestType { }
public static enum KeyEnum {
A, B
}
public static enum ConcreteType implements ITestType {
ONE, TWO;
}
static class ClassStringMap extends HashMap<Class<?>,String> { }
/*
/**********************************************************
/* Test methods, untyped (Object valued) maps
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testUntypedMap() throws Exception
{
// to get "untyped" default map-to-map, pass Object.class
String JSON = "{ \"foo\" : \"bar\", \"crazy\" : true, \"null\" : null }";
// Not a guaranteed cast theoretically, but will work:
@SuppressWarnings("unchecked")
Map<String,Object> result = (Map<String,Object>)MAPPER.readValue(JSON, Object.class);
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(3, result.size());
assertEquals("bar", result.get("foo"));
assertEquals(Boolean.TRUE, result.get("crazy"));
assertNull(result.get("null"));
// Plus, non existing:
assertNull(result.get("bar"));
assertNull(result.get(3));
}
public void testBigUntypedMap() throws Exception
{
Map<String,Object> map = new LinkedHashMap<String,Object>();
for (int i = 0; i < 1100; ++i) {
if ((i & 1) == 0) {
map.put(String.valueOf(i), Integer.valueOf(i));
} else {
Map<String,Object> map2 = new LinkedHashMap<String,Object>();
map2.put("x", Integer.valueOf(i));
map.put(String.valueOf(i), map2);
}
}
String json = MAPPER.writeValueAsString(map);
Object bound = MAPPER.readValue(json, Object.class);
assertEquals(map, bound);
}
/**
* Let's also try another way to express "gimme a Map" deserialization;
* this time by specifying a Map class, to reduce need to cast
*/
public void testUntypedMap2() throws Exception
{
// to get "untyped" default map-to-map, pass Object.class
String JSON = "{ \"a\" : \"x\" }";
@SuppressWarnings("unchecked")
HashMap<String,Object> result = /*(HashMap<String,Object>)*/ MAPPER.readValue(JSON, HashMap.class);
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(1, result.size());
assertEquals("x", result.get("a"));
}
/**
* Unit test for [JACKSON-185]
*/
public void testUntypedMap3() throws Exception
{
String JSON = "{\"a\":[{\"a\":\"b\"},\"value\"]}";
Map<?,?> result = MAPPER.readValue(JSON, Map.class);
assertTrue(result instanceof Map<?,?>);
assertEquals(1, result.size());
Object ob = result.get("a");
assertNotNull(ob);
Collection<?> list = (Collection<?>)ob;
assertEquals(2, list.size());
JSON = "{ \"var1\":\"val1\", \"var2\":\"val2\", "
+"\"subvars\": ["
+" { \"subvar1\" : \"subvar2\", \"x\" : \"y\" }, "
+" { \"a\":1 } ]"
+" }"
;
result = MAPPER.readValue(JSON, Map.class);
assertTrue(result instanceof Map<?,?>);
assertEquals(3, result.size());
}
private static final String UNTYPED_MAP_JSON =
"{ \"double\":42.0, \"string\":\"string\","
+"\"boolean\":true, \"list\":[\"list0\"],"
+"\"null\":null }";
static class ObjectWrapperMap extends HashMap<String, ObjectWrapper> { }
public void testSpecialMap() throws IOException
{
final ObjectWrapperMap map = MAPPER.readValue(UNTYPED_MAP_JSON, ObjectWrapperMap.class);
assertNotNull(map);
_doTestUntyped(map);
}
public void testGenericMap() throws IOException
{
final Map<String, ObjectWrapper> map = MAPPER.readValue
(UNTYPED_MAP_JSON,
new TypeReference<Map<String, ObjectWrapper>>() { });
_doTestUntyped(map);
}
private void _doTestUntyped(final Map<String, ObjectWrapper> map)
{
ObjectWrapper w = map.get("double");
assertNotNull(w);
assertEquals(Double.valueOf(42), w.getObject());
assertEquals("string", map.get("string").getObject());
assertEquals(Boolean.TRUE, map.get("boolean").getObject());
assertEquals(Collections.singletonList("list0"), map.get("list").getObject());
assertTrue(map.containsKey("null"));
assertNull(map.get("null"));
assertEquals(5, map.size());
}
// [JACKSON-620]: allow "" to mean 'null' for Maps
public void testFromEmptyString() throws Exception
{
ObjectMapper m = new ObjectMapper();
m.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Map<?,?> result = m.readValue(quote(""), Map.class);
assertNull(result);
}
/*
/**********************************************************
/* Test methods, typed maps
/**********************************************************
*/
public void testExactStringIntMap() throws Exception
{
// to get typing, must use type reference
String JSON = "{ \"foo\" : 13, \"bar\" : -39, \n \"\" : 0 }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<HashMap<String,Integer>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(3, result.size());
assertEquals(Integer.valueOf(13), result.get("foo"));
assertEquals(Integer.valueOf(-39), result.get("bar"));
assertEquals(Integer.valueOf(0), result.get(""));
assertNull(result.get("foobar"));
assertNull(result.get(" "));
}
/**
* Let's also check that it is possible to do type conversions
* to allow use of non-String Map keys.
*/
public void testIntBooleanMap() throws Exception
{
// to get typing, must use type reference
String JSON = "{ \"1\" : true, \"-1\" : false }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<HashMap<Integer,Boolean>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(2, result.size());
assertEquals(Boolean.TRUE, result.get(Integer.valueOf(1)));
assertEquals(Boolean.FALSE, result.get(Integer.valueOf(-1)));
assertNull(result.get("foobar"));
assertNull(result.get(0));
}
public void testExactStringStringMap() throws Exception
{
// to get typing, must use type reference
String JSON = "{ \"a\" : \"b\" }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<TreeMap<String,String>>() { });
assertNotNull(result);
assertEquals(TreeMap.class, result.getClass());
assertEquals(1, result.size());
assertEquals("b", result.get("a"));
assertNull(result.get("b"));
}
/**
* Unit test that verifies that it's ok to have incomplete
* information about Map class itself, as long as it's something
* we good guess about: for example, <code>Map.Class</code> will
* be replaced by something like <code>HashMap.class</code>,
* if given.
*/
public void testGenericStringIntMap() throws Exception
{
// to get typing, must use type reference; but with abstract type
String JSON = "{ \"a\" : 1, \"b\" : 2, \"c\" : -99 }";
Map<String,Integer> result = MAPPER.readValue
(JSON, new TypeReference<Map<String,Integer>>() { });
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(3, result.size());
assertEquals(Integer.valueOf(-99), result.get("c"));
assertEquals(Integer.valueOf(2), result.get("b"));
assertEquals(Integer.valueOf(1), result.get("a"));
assertNull(result.get(""));
}
// [Databind#540]
public void testMapFromEmptyArray() throws Exception
{
final String JSON = " [\n]";
assertFalse(MAPPER.isEnabled(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT));
// first, verify default settings which do not accept empty Array
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(JSON, Map.class);
fail("Should not accept Empty Array for Map by default");
} catch (JsonProcessingException e) {
verifyException(e, "START_ARRAY token");
}
// should be ok to enable dynamically:
ObjectReader r = MAPPER.readerFor(Map.class)
.with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
Map<?,?> result = r.readValue(JSON);
assertNull(result);
EnumMap<?,?> result2 = r.forType(new TypeReference<EnumMap<Key,String>>() { })
.readValue(JSON);
assertNull(result2);
}
/*
/**********************************************************
/* Test methods, maps with enums
/**********************************************************
*/
public void testEnumMap() throws Exception
{
String JSON = "{ \"KEY1\" : \"\", \"WHATEVER\" : null }";
// to get typing, must use type reference
EnumMap<Key,String> result = MAPPER.readValue
(JSON, new TypeReference<EnumMap<Key,String>>() { });
assertNotNull(result);
assertEquals(EnumMap.class, result.getClass());
assertEquals(2, result.size());
assertEquals("", result.get(Key.KEY1));
// null should be ok too...
assertTrue(result.containsKey(Key.WHATEVER));
assertNull(result.get(Key.WHATEVER));
// plus we have nothing for this key
assertFalse(result.containsKey(Key.KEY2));
assertNull(result.get(Key.KEY2));
}
public void testMapWithEnums() throws Exception
{
String JSON = "{ \"KEY2\" : \"WHATEVER\" }";
// to get typing, must use type reference
Map<Enum<?>,Enum<?>> result = MAPPER.readValue
(JSON, new TypeReference<Map<Key,Key>>() { });
assertNotNull(result);
assertTrue(result instanceof Map<?,?>);
assertEquals(1, result.size());
assertEquals(Key.WHATEVER, result.get(Key.KEY2));
assertNull(result.get(Key.WHATEVER));
assertNull(result.get(Key.KEY1));
}
public void testEnumPolymorphicSerializationTest() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
List<ITestType> testTypesList = new ArrayList<ITestType>();
testTypesList.add(ConcreteType.ONE);
testTypesList.add(ConcreteType.TWO);
ListContainer listContainer = new ListContainer();
listContainer.testTypes = testTypesList;
String json = mapper.writeValueAsString(listContainer);
listContainer = mapper.readValue(json, ListContainer.class);
EnumMapContainer enumMapContainer = new EnumMapContainer();
EnumMap<KeyEnum,ITestType> testTypesMap = new EnumMap<KeyEnum,ITestType>(KeyEnum.class);
testTypesMap.put(KeyEnum.A, ConcreteType.ONE);
testTypesMap.put(KeyEnum.B, ConcreteType.TWO);
enumMapContainer.testTypes = testTypesMap;
json = mapper.writeValueAsString(enumMapContainer);
enumMapContainer = mapper.readValue(json, EnumMapContainer.class);
}
/*
/**********************************************************
/* Test methods, maps with Date
/**********************************************************
*/
public void testDateMap() throws Exception
{
Date date1=new Date(123456000L);
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
String JSON = "{ \""+ fmt.format(date1)+"\" : \"\", \""+new Date(0).getTime()+"\" : null }";
HashMap<Date,String> result= MAPPER.readValue
(JSON, new TypeReference<HashMap<Date,String>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(2, result.size());
assertTrue(result.containsKey(date1));
assertEquals("", result.get(new Date(123456000L)));
assertTrue(result.containsKey(new Date(0)));
assertNull(result.get(new Date(0)));
}
/*
/**********************************************************
/* Test methods, maps with various alternative key types
/**********************************************************
*/
public void testCalendarMap() throws Exception
{
// 18-Jun-2015, tatu: Should be safest to use default timezone that mapper would use
TimeZone tz = MAPPER.getSerializationConfig().getTimeZone();
Calendar c = Calendar.getInstance(tz);
c.setTimeInMillis(123456000L);
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
String JSON = "{ \""+fmt.format(c.getTime())+"\" : \"\", \""+new Date(0).getTime()+"\" : null }";
HashMap<Calendar,String> result = MAPPER.readValue
(JSON, new TypeReference<HashMap<Calendar,String>>() { });
assertNotNull(result);
assertEquals(HashMap.class, result.getClass());
assertEquals(2, result.size());
assertTrue(result.containsKey(c));
assertEquals("", result.get(c));
c.setTimeInMillis(0);
assertTrue(result.containsKey(c));
assertNull(result.get(c));
}
public void testUUIDKeyMap() throws Exception
{
UUID key = UUID.nameUUIDFromBytes("foobar".getBytes("UTF-8"));
String JSON = "{ \""+key+"\":4}";
Map<UUID,Object> result = MAPPER.readValue(JSON, new TypeReference<Map<UUID,Object>>() { });
assertNotNull(result);
assertEquals(1, result.size());
Object ob = result.keySet().iterator().next();
assertNotNull(ob);
assertEquals(UUID.class, ob.getClass());
assertEquals(key, ob);
}
public void testLocaleKeyMap() throws Exception {
Locale key = Locale.CHINA;
String JSON = "{ \"" + key + "\":4}";
Map<Locale, Object> result = MAPPER.readValue(JSON, new TypeReference<Map<Locale, Object>>() {
});
assertNotNull(result);
assertEquals(1, result.size());
Object ob = result.keySet().iterator().next();
assertNotNull(ob);
assertEquals(Locale.class, ob.getClass());
assertEquals(key, ob);
}
public void testCurrencyKeyMap() throws Exception {
Currency key = Currency.getInstance("USD");
String JSON = "{ \"" + key + "\":4}";
Map<Currency, Object> result = MAPPER.readValue(JSON, new TypeReference<Map<Currency, Object>>() {
});
assertNotNull(result);
assertEquals(1, result.size());
Object ob = result.keySet().iterator().next();
assertNotNull(ob);
assertEquals(Currency.class, ob.getClass());
assertEquals(key, ob);
}
// Test confirming that @JsonCreator may be used with Map Key types
public void testKeyWithCreator() throws Exception
{
// first, key should deserialize normally:
KeyType key = MAPPER.readValue(quote("abc"), KeyType.class);
assertEquals("abc", key.value);
Map<KeyType,Integer> map = MAPPER.readValue("{\"foo\":3}", new TypeReference<Map<KeyType,Integer>>() {} );
assertEquals(1, map.size());
key = map.keySet().iterator().next();
assertEquals("foo", key.value);
}
public void testClassKeyMap() throws Exception {
ClassStringMap map = MAPPER.readValue(aposToQuotes("{'java.lang.String':'foo'}"),
ClassStringMap.class);
assertNotNull(map);
assertEquals(1, map.size());
assertEquals("foo", map.get(String.class));
}
public void testcharSequenceKeyMap() throws Exception {
String JSON = aposToQuotes("{'a':'b'}");
Map<CharSequence,String> result = MAPPER.readValue(JSON, new TypeReference<Map<CharSequence,String>>() { });
assertNotNull(result);
assertEquals(1, result.size());
assertEquals("b", result.get("a"));
}
/*
/**********************************************************
/* Test methods, annotated Maps
/**********************************************************
*/
/**
* Simple test to ensure that @JsonDeserialize.using is
* recognized
*/
public void testMapWithDeserializer() throws Exception
{
CustomMap result = MAPPER.readValue(quote("xyz"), CustomMap.class);
assertEquals(1, result.size());
assertEquals("xyz", result.get("x"));
}
/*
/**********************************************************
/* Test methods, annotated Map.Entry
/**********************************************************
*/
public void testMapEntrySimpleTypes() throws Exception
{
List<Map.Entry<String,Long>> stuff = MAPPER.readValue(aposToQuotes("[{'a':15},{'b':42}]"),
new TypeReference<List<Map.Entry<String,Long>>>() { });
assertNotNull(stuff);
assertEquals(2, stuff.size());
assertNotNull(stuff.get(1));
assertEquals("b", stuff.get(1).getKey());
assertEquals(Long.valueOf(42), stuff.get(1).getValue());
}
public void testMapEntryWithStringBean() throws Exception
{
List<Map.Entry<Integer,StringWrapper>> stuff = MAPPER.readValue(aposToQuotes("[{'28':'Foo'},{'13':'Bar'}]"),
new TypeReference<List<Map.Entry<Integer,StringWrapper>>>() { });
assertNotNull(stuff);
assertEquals(2, stuff.size());
assertNotNull(stuff.get(1));
assertEquals(Integer.valueOf(13), stuff.get(1).getKey());
StringWrapper sw = stuff.get(1).getValue();
assertEquals("Bar", sw.str);
}
public void testMapEntryFail() throws Exception
{
try {
/*List<Map.Entry<Integer,StringWrapper>> stuff =*/ MAPPER.readValue(aposToQuotes("[{'28':'Foo','13':'Bar'}]"),
new TypeReference<List<Map.Entry<Integer,StringWrapper>>>() { });
fail("Should not have passed");
} catch (Exception e) {
verifyException(e, "more than one entry in JSON");
}
}
/*
/**********************************************************
/* Test methods, other exotic Map types
/**********************************************************
*/
// [databind#810]
public void testReadProperties() throws Exception
{
Properties props = MAPPER.readValue(aposToQuotes("{'a':'foo', 'b':123, 'c':true}"),
Properties.class);
assertEquals(3, props.size());
assertEquals("foo", props.getProperty("a"));
assertEquals("123", props.getProperty("b"));
assertEquals("true", props.getProperty("c"));
}
// JDK singletonMap
public void testSingletonMapRoundtrip() throws Exception
{
final TypeReference<?> type = new TypeReference<Map<String,IntWrapper>>() { };
String json = MAPPER.writeValueAsString(Collections.singletonMap("value", new IntWrapper(5)));
Map<String,IntWrapper> result = MAPPER.readValue(json, type);
assertNotNull(result);
assertEquals(1, result.size());
IntWrapper w = result.get("value");
assertNotNull(w);
assertEquals(5, w.i);
}
/*
/**********************************************************
/* Error tests
/**********************************************************
*/
public void testMapError() throws Exception
{
try {
Object result = MAPPER.readValue("[ 1, 2 ]",
new TypeReference<Map<String,String>>() { });
fail("Expected an exception, but got result value: "+result);
} catch (JsonMappingException jex) {
verifyException(jex, "START_ARRAY");
}
}
public void testNoCtorMap() throws Exception
{
try {
BrokenMap result = MAPPER.readValue("{ \"a\" : 3 }", BrokenMap.class);
// should never get here; assert added to remove compiler warning
assertNull(result);
} catch (JsonMappingException e) {
// instead, should get this exception:
verifyException(e, "no default constructor found");
}
}
} |
||
public void testLang457() {
String[] badInputs = new String[] { "l", "L", "f", "F", "junk", "bobL"};
for(int i=0; i<badInputs.length; i++) {
try {
NumberUtils.createNumber(badInputs[i]);
fail("NumberFormatException was expected for " + badInputs[i]);
} catch (NumberFormatException e) {
return; // expected
}
}
} | org.apache.commons.lang.NumberUtilsTest::testLang457 | src/test/org/apache/commons/lang/NumberUtilsTest.java | 533 | src/test/org/apache/commons/lang/NumberUtilsTest.java | testLang457 | /*
* 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.math.BigDecimal;
import java.math.BigInteger;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit tests {@link org.apache.commons.lang.NumberUtils}.
*
* @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @author Eric Pugh
* @author Phil Steitz
* @author Stephen Colebourne
* @version $Id$
*/
public class NumberUtilsTest extends TestCase {
public NumberUtilsTest(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite(NumberUtilsTest.class);
suite.setName("NumberUtils Tests");
return suite;
}
//---------------------------------------------------------------------
/**
* Test for int stringToInt(String)
*/
public void testStringToIntString() {
assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345);
assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0);
}
/**
* Test for int stringToInt(String, int)
*/
public void testStringToIntStringI() {
assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345);
assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 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) 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 BigInteger(Long.MAX_VALUE + "0"), NumberUtils.createNumber(Long.MAX_VALUE + "0L"));
assertEquals("createNumber(String) 7 failed", new Long(12345), NumberUtils.createNumber("12345L"));
assertEquals("createNumber(String) 8 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5"));
assertEquals("createNumber(String) 9 failed", new Integer("-12345"), NumberUtils.createNumber("-12345"));
assertTrue("createNumber(String) 10 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue());
assertTrue("createNumber(String) 11 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue());
assertEquals("createNumber(String) 12 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200"));
assertEquals("createNumber(String) 13 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20"));
assertEquals("createNumber(String) 14 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200"));
assertEquals("createNumber(String) 15 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200"));
assertEquals("createNumber(String) 16 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200"));
// 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));
}
public void testCreateFloat() {
assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5"));
}
public void testCreateDouble() {
assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5"));
}
public void testCreateInteger() {
assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345"));
}
public void testCreateLong() {
assertEquals("createInteger(String) failed", new Long("12345"), NumberUtils.createLong("12345"));
}
public void testCreateBigInteger() {
assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345"));
}
public void testCreateBigDecimal() {
assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"));
}
public void testMinimumLong() {
assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.minimum(12345L, 12345L + 1L, 12345L + 2L));
assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345 + 2L));
assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L + 2L, 12345L));
assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345L));
assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.minimum(12345L, 12345L, 12345L));
}
public void testMinimumInt() {
assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.minimum(12345, 12345 + 1, 12345 + 2));
assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345 + 2));
assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.minimum(12345 + 1, 12345 + 2, 12345));
assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345));
assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.minimum(12345, 12345, 12345));
}
public void testMaximumLong() {
assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.maximum(12345L, 12345L - 1L, 12345L - 2L));
assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L - 2L));
assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L - 2L, 12345L));
assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L));
assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.maximum(12345L, 12345L, 12345L));
}
public void testMaximumInt() {
assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.maximum(12345, 12345 - 1, 12345 - 2));
assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345 - 2));
assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.maximum(12345 - 1, 12345 - 2, 12345));
assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345));
assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.maximum(12345, 12345, 12345));
}
public void testCompareDouble() {
assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0);
assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0);
assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1);
assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0);
assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1);
assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0);
assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0);
assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0);
}
public void testCompareFloat() {
assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0);
assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0);
assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1);
assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0);
assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1);
assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0);
assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0);
assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.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));
}
public void testIsNumberInvalidInput() {
String val = "0x";
assertEquals("isNumber() with 0x wasn't false", false, NumberUtils.isNumber(val));
val = "0x3x3";
assertEquals("isNumber() with 0x3x3 wasn't false", false, NumberUtils.isNumber(val));
val = "20EE-3";
assertEquals("isNumber() with 20EE-3 wasn't false", false, NumberUtils.isNumber(val));
val = "2435q";
assertEquals("isNumber() with 2435q wasn't false", false, NumberUtils.isNumber(val));
val = ".";
assertEquals("isNumber() with . wasn't false", false, 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;
} catch (NullPointerException e) {
return false;
}
}
public void testPublicNoArgConstructor() {
try {
NumberUtils nu = new NumberUtils();
} catch( Exception e ) {
fail( "Error calling public no-arg constructor" );
}
}
public void testLang457() {
String[] badInputs = new String[] { "l", "L", "f", "F", "junk", "bobL"};
for(int i=0; i<badInputs.length; i++) {
try {
NumberUtils.createNumber(badInputs[i]);
fail("NumberFormatException was expected for " + badInputs[i]);
} catch (NumberFormatException e) {
return; // expected
}
}
}
} | // You are a professional Java test case writer, please create a test case named `testLang457` for the issue `Lang-LANG-457`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-457
//
// ## Issue-Title:
// NumberUtils createNumber thows a StringIndexOutOfBoundsException when only an "l" is passed in.
//
// ## Issue-Description:
//
// Seems to be similar to [~~LANG-300~~](https://issues.apache.org/jira/browse/LANG-300 "NumberUtils.createNumber throws NumberFormatException for one digit long"), except that if you don't place a digit in front of the "l" or "L" it throws a StringIndexOutOfBoundsException instead.
//
//
//
//
//
public void testLang457() {
| 533 | 44 | 523 | src/test/org/apache/commons/lang/NumberUtilsTest.java | src/test | ```markdown
## Issue-ID: Lang-LANG-457
## Issue-Title:
NumberUtils createNumber thows a StringIndexOutOfBoundsException when only an "l" is passed in.
## Issue-Description:
Seems to be similar to [~~LANG-300~~](https://issues.apache.org/jira/browse/LANG-300 "NumberUtils.createNumber throws NumberFormatException for one digit long"), except that if you don't place a digit in front of the "l" or "L" it throws a StringIndexOutOfBoundsException instead.
```
You are a professional Java test case writer, please create a test case named `testLang457` for the issue `Lang-LANG-457`, utilizing the provided issue report information and the following function signature.
```java
public void testLang457() {
```
| 523 | [
"org.apache.commons.lang.NumberUtils"
] | 3dd913a0927df71d67c42548e5f6b1b4dc7d5bcc39f1b5a3fda002f3b21d905b | public void testLang457() | // You are a professional Java test case writer, please create a test case named `testLang457` for the issue `Lang-LANG-457`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-457
//
// ## Issue-Title:
// NumberUtils createNumber thows a StringIndexOutOfBoundsException when only an "l" is passed in.
//
// ## Issue-Description:
//
// Seems to be similar to [~~LANG-300~~](https://issues.apache.org/jira/browse/LANG-300 "NumberUtils.createNumber throws NumberFormatException for one digit long"), except that if you don't place a digit in front of the "l" or "L" it throws a StringIndexOutOfBoundsException instead.
//
//
//
//
//
| 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.math.BigDecimal;
import java.math.BigInteger;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit tests {@link org.apache.commons.lang.NumberUtils}.
*
* @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @author Eric Pugh
* @author Phil Steitz
* @author Stephen Colebourne
* @version $Id$
*/
public class NumberUtilsTest extends TestCase {
public NumberUtilsTest(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite(NumberUtilsTest.class);
suite.setName("NumberUtils Tests");
return suite;
}
//---------------------------------------------------------------------
/**
* Test for int stringToInt(String)
*/
public void testStringToIntString() {
assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345);
assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0);
}
/**
* Test for int stringToInt(String, int)
*/
public void testStringToIntStringI() {
assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345);
assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 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) 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 BigInteger(Long.MAX_VALUE + "0"), NumberUtils.createNumber(Long.MAX_VALUE + "0L"));
assertEquals("createNumber(String) 7 failed", new Long(12345), NumberUtils.createNumber("12345L"));
assertEquals("createNumber(String) 8 failed", new Float("-1234.5"), NumberUtils.createNumber("-1234.5"));
assertEquals("createNumber(String) 9 failed", new Integer("-12345"), NumberUtils.createNumber("-12345"));
assertTrue("createNumber(String) 10 failed", 0xFADE == NumberUtils.createNumber("0xFADE").intValue());
assertTrue("createNumber(String) 11 failed", -0xFADE == NumberUtils.createNumber("-0xFADE").intValue());
assertEquals("createNumber(String) 12 failed", new Double("1.1E200"), NumberUtils.createNumber("1.1E200"));
assertEquals("createNumber(String) 13 failed", new Float("1.1E20"), NumberUtils.createNumber("1.1E20"));
assertEquals("createNumber(String) 14 failed", new Double("-1.1E200"), NumberUtils.createNumber("-1.1E200"));
assertEquals("createNumber(String) 15 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200"));
assertEquals("createNumber(String) 16 failed", new Double("1.1E-200"), NumberUtils.createNumber("1.1E-200"));
// 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));
}
public void testCreateFloat() {
assertEquals("createFloat(String) failed", new Float("1234.5"), NumberUtils.createFloat("1234.5"));
}
public void testCreateDouble() {
assertEquals("createDouble(String) failed", new Double("1234.5"), NumberUtils.createDouble("1234.5"));
}
public void testCreateInteger() {
assertEquals("createInteger(String) failed", new Integer("12345"), NumberUtils.createInteger("12345"));
}
public void testCreateLong() {
assertEquals("createInteger(String) failed", new Long("12345"), NumberUtils.createLong("12345"));
}
public void testCreateBigInteger() {
assertEquals("createBigInteger(String) failed", new BigInteger("12345"), NumberUtils.createBigInteger("12345"));
}
public void testCreateBigDecimal() {
assertEquals("createBigDecimal(String) failed", new BigDecimal("1234.5"), NumberUtils.createBigDecimal("1234.5"));
}
public void testMinimumLong() {
assertEquals("minimum(long,long,long) 1 failed", 12345L, NumberUtils.minimum(12345L, 12345L + 1L, 12345L + 2L));
assertEquals("minimum(long,long,long) 2 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345 + 2L));
assertEquals("minimum(long,long,long) 3 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L + 2L, 12345L));
assertEquals("minimum(long,long,long) 4 failed", 12345L, NumberUtils.minimum(12345L + 1L, 12345L, 12345L));
assertEquals("minimum(long,long,long) 5 failed", 12345L, NumberUtils.minimum(12345L, 12345L, 12345L));
}
public void testMinimumInt() {
assertEquals("minimum(int,int,int) 1 failed", 12345, NumberUtils.minimum(12345, 12345 + 1, 12345 + 2));
assertEquals("minimum(int,int,int) 2 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345 + 2));
assertEquals("minimum(int,int,int) 3 failed", 12345, NumberUtils.minimum(12345 + 1, 12345 + 2, 12345));
assertEquals("minimum(int,int,int) 4 failed", 12345, NumberUtils.minimum(12345 + 1, 12345, 12345));
assertEquals("minimum(int,int,int) 5 failed", 12345, NumberUtils.minimum(12345, 12345, 12345));
}
public void testMaximumLong() {
assertEquals("maximum(long,long,long) 1 failed", 12345L, NumberUtils.maximum(12345L, 12345L - 1L, 12345L - 2L));
assertEquals("maximum(long,long,long) 2 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L - 2L));
assertEquals("maximum(long,long,long) 3 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L - 2L, 12345L));
assertEquals("maximum(long,long,long) 4 failed", 12345L, NumberUtils.maximum(12345L - 1L, 12345L, 12345L));
assertEquals("maximum(long,long,long) 5 failed", 12345L, NumberUtils.maximum(12345L, 12345L, 12345L));
}
public void testMaximumInt() {
assertEquals("maximum(int,int,int) 1 failed", 12345, NumberUtils.maximum(12345, 12345 - 1, 12345 - 2));
assertEquals("maximum(int,int,int) 2 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345 - 2));
assertEquals("maximum(int,int,int) 3 failed", 12345, NumberUtils.maximum(12345 - 1, 12345 - 2, 12345));
assertEquals("maximum(int,int,int) 4 failed", 12345, NumberUtils.maximum(12345 - 1, 12345, 12345));
assertEquals("maximum(int,int,int) 5 failed", 12345, NumberUtils.maximum(12345, 12345, 12345));
}
public void testCompareDouble() {
assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0);
assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0);
assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1);
assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0);
assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1);
assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0);
assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0);
assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0);
}
public void testCompareFloat() {
assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0);
assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0);
assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1);
assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0);
assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1);
assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0);
assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0);
assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.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));
}
public void testIsNumberInvalidInput() {
String val = "0x";
assertEquals("isNumber() with 0x wasn't false", false, NumberUtils.isNumber(val));
val = "0x3x3";
assertEquals("isNumber() with 0x3x3 wasn't false", false, NumberUtils.isNumber(val));
val = "20EE-3";
assertEquals("isNumber() with 20EE-3 wasn't false", false, NumberUtils.isNumber(val));
val = "2435q";
assertEquals("isNumber() with 2435q wasn't false", false, NumberUtils.isNumber(val));
val = ".";
assertEquals("isNumber() with . wasn't false", false, 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;
} catch (NullPointerException e) {
return false;
}
}
public void testPublicNoArgConstructor() {
try {
NumberUtils nu = new NumberUtils();
} catch( Exception e ) {
fail( "Error calling public no-arg constructor" );
}
}
public void testLang457() {
String[] badInputs = new String[] { "l", "L", "f", "F", "junk", "bobL"};
for(int i=0; i<badInputs.length; i++) {
try {
NumberUtils.createNumber(badInputs[i]);
fail("NumberFormatException was expected for " + badInputs[i]);
} catch (NumberFormatException e) {
return; // expected
}
}
}
} |
||
@Test
public void testMinMaxFloat() {
float[][] pairs = {
{ -50.0f, 50.0f },
{ Float.POSITIVE_INFINITY, 1.0f },
{ Float.NEGATIVE_INFINITY, 1.0f },
{ Float.NaN, 1.0f },
{ Float.POSITIVE_INFINITY, 0.0f },
{ Float.NEGATIVE_INFINITY, 0.0f },
{ Float.NaN, 0.0f },
{ Float.NaN, Float.NEGATIVE_INFINITY },
{ Float.NaN, Float.POSITIVE_INFINITY }
};
for (float[] pair : pairs) {
Assert.assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
Math.min(pair[0], pair[1]),
FastMath.min(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("min(" + pair[1] + ", " + pair[0] + ")",
Math.min(pair[1], pair[0]),
FastMath.min(pair[1], pair[0]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[0] + ", " + pair[1] + ")",
Math.max(pair[0], pair[1]),
FastMath.max(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[1] + ", " + pair[0] + ")",
Math.max(pair[1], pair[0]),
FastMath.max(pair[1], pair[0]),
MathUtils.EPSILON);
}
} | org.apache.commons.math.util.FastMathTest::testMinMaxFloat | src/test/java/org/apache/commons/math/util/FastMathTest.java | 107 | src/test/java/org/apache/commons/math/util/FastMathTest.java | testMinMaxFloat | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.util;
import org.apache.commons.math.dfp.Dfp;
import org.apache.commons.math.dfp.DfpField;
import org.apache.commons.math.dfp.DfpMath;
import org.apache.commons.math.random.MersenneTwister;
import org.apache.commons.math.random.RandomGenerator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class FastMathTest {
private static final double MAX_ERROR_ULP = 0.51;
private static final int NUMBER_OF_TRIALS = 1000;
private DfpField field;
private RandomGenerator generator;
@Before
public void setUp() {
field = new DfpField(40);
generator = new MersenneTwister(6176597458463500194l);
}
@Test
public void testMinMaxDouble() {
double[][] pairs = {
{ -50.0, 50.0 },
{ Double.POSITIVE_INFINITY, 1.0 },
{ Double.NEGATIVE_INFINITY, 1.0 },
{ Double.NaN, 1.0 },
{ Double.POSITIVE_INFINITY, 0.0 },
{ Double.NEGATIVE_INFINITY, 0.0 },
{ Double.NaN, 0.0 },
{ Double.NaN, Double.NEGATIVE_INFINITY },
{ Double.NaN, Double.POSITIVE_INFINITY },
{ MathUtils.SAFE_MIN, MathUtils.EPSILON }
};
for (double[] pair : pairs) {
Assert.assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
Math.min(pair[0], pair[1]),
FastMath.min(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("min(" + pair[1] + ", " + pair[0] + ")",
Math.min(pair[1], pair[0]),
FastMath.min(pair[1], pair[0]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[0] + ", " + pair[1] + ")",
Math.max(pair[0], pair[1]),
FastMath.max(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[1] + ", " + pair[0] + ")",
Math.max(pair[1], pair[0]),
FastMath.max(pair[1], pair[0]),
MathUtils.EPSILON);
}
}
@Test
public void testMinMaxFloat() {
float[][] pairs = {
{ -50.0f, 50.0f },
{ Float.POSITIVE_INFINITY, 1.0f },
{ Float.NEGATIVE_INFINITY, 1.0f },
{ Float.NaN, 1.0f },
{ Float.POSITIVE_INFINITY, 0.0f },
{ Float.NEGATIVE_INFINITY, 0.0f },
{ Float.NaN, 0.0f },
{ Float.NaN, Float.NEGATIVE_INFINITY },
{ Float.NaN, Float.POSITIVE_INFINITY }
};
for (float[] pair : pairs) {
Assert.assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
Math.min(pair[0], pair[1]),
FastMath.min(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("min(" + pair[1] + ", " + pair[0] + ")",
Math.min(pair[1], pair[0]),
FastMath.min(pair[1], pair[0]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[0] + ", " + pair[1] + ")",
Math.max(pair[0], pair[1]),
FastMath.max(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[1] + ", " + pair[0] + ")",
Math.max(pair[1], pair[0]),
FastMath.max(pair[1], pair[0]),
MathUtils.EPSILON);
}
}
@Test
public void testConstants() {
Assert.assertEquals(Math.PI, FastMath.PI, 1.0e-20);
Assert.assertEquals(Math.E, FastMath.E, 1.0e-20);
}
@Test
public void testAtan2() {
double y1 = 1.2713504628280707e10;
double x1 = -5.674940885228782e-10;
Assert.assertEquals(Math.atan2(y1, x1), FastMath.atan2(y1, x1), 2 * MathUtils.EPSILON);
double y2 = 0.0;
double x2 = Double.POSITIVE_INFINITY;
Assert.assertEquals(Math.atan2(y2, x2), FastMath.atan2(y2, x2), MathUtils.SAFE_MIN);
}
@Test
public void testHyperbolic() {
double maxErr = 0;
for (double x = -30; x < 30; x += 0.001) {
double tst = FastMath.sinh(x);
double ref = Math.sinh(x);
maxErr = FastMath.max(maxErr, FastMath.abs(ref - tst) / FastMath.ulp(ref));
}
Assert.assertEquals(0, maxErr, 2);
maxErr = 0;
for (double x = -30; x < 30; x += 0.001) {
double tst = FastMath.cosh(x);
double ref = Math.cosh(x);
maxErr = FastMath.max(maxErr, FastMath.abs(ref - tst) / FastMath.ulp(ref));
}
Assert.assertEquals(0, maxErr, 2);
maxErr = 0;
for (double x = -0.5; x < 0.5; x += 0.001) {
double tst = FastMath.tanh(x);
double ref = Math.tanh(x);
maxErr = FastMath.max(maxErr, FastMath.abs(ref - tst) / FastMath.ulp(ref));
}
Assert.assertEquals(0, maxErr, 4);
}
@Test
public void testHyperbolicInverses() {
double maxErr = 0;
for (double x = -30; x < 30; x += 0.01) {
maxErr = FastMath.max(maxErr, FastMath.abs(x - FastMath.sinh(FastMath.asinh(x))) / (2 * FastMath.ulp(x)));
}
Assert.assertEquals(0, maxErr, 3);
maxErr = 0;
for (double x = 1; x < 30; x += 0.01) {
maxErr = FastMath.max(maxErr, FastMath.abs(x - FastMath.cosh(FastMath.acosh(x))) / (2 * FastMath.ulp(x)));
}
Assert.assertEquals(0, maxErr, 2);
maxErr = 0;
for (double x = -1 + MathUtils.EPSILON; x < 1 - MathUtils.EPSILON; x += 0.0001) {
maxErr = FastMath.max(maxErr, FastMath.abs(x - FastMath.tanh(FastMath.atanh(x))) / (2 * FastMath.ulp(x)));
}
Assert.assertEquals(0, maxErr, 2);
}
@Test
public void testLogAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.exp(generator.nextDouble() * 1416.0 - 708.0) * generator.nextDouble();
// double x = generator.nextDouble()*2.0;
double tst = FastMath.log(x);
double ref = DfpMath.log(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0.0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.log(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("log() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testLog10Accuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.exp(generator.nextDouble() * 1416.0 - 708.0) * generator.nextDouble();
// double x = generator.nextDouble()*2.0;
double tst = FastMath.log10(x);
double ref = DfpMath.log(field.newDfp(x)).divide(DfpMath.log(field.newDfp("10"))).toDouble();
double err = (tst - ref) / ref;
if (err != 0.0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.log(field.newDfp(x)).divide(DfpMath.log(field.newDfp("10")))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("log10() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testLog1pAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.exp(generator.nextDouble() * 10.0 - 5.0) * generator.nextDouble();
// double x = generator.nextDouble()*2.0;
double tst = FastMath.log1p(x);
double ref = DfpMath.log(field.newDfp(x).add(field.getOne())).toDouble();
double err = (tst - ref) / ref;
if (err != 0.0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.log(field.newDfp(x).add(field.getOne()))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("log1p() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testLogSpecialCases() {
double x;
x = FastMath.log(0.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("Log of zero should be -Inf");
x = FastMath.log(-0.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("Log of zero should be -Inf");
x = FastMath.log(Double.NaN);
if (x == x)
throw new RuntimeException("Log of NaN should be NaN");
x = FastMath.log(-1.0);
if (x == x)
throw new RuntimeException("Log of negative number should be NaN");
x = FastMath.log(Double.MIN_VALUE);
if (x != -744.4400719213812)
throw new RuntimeException(
"Log of Double.MIN_VALUE should be -744.4400719213812");
x = FastMath.log(-1.0);
if (x == x)
throw new RuntimeException("Log of negative number should be NaN");
x = FastMath.log(Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("Log of infinity should be infinity");
}
@Test
public void testExpSpecialCases() {
double x;
/* Smallest value that will round up to Double.MIN_VALUE */
x = FastMath.exp(-745.1332191019411);
if (x != Double.MIN_VALUE)
throw new RuntimeException(
"exp(-745.1332191019411) should be Double.MIN_VALUE");
x = FastMath.exp(-745.1332191019412);
if (x != 0.0)
throw new RuntimeException("exp(-745.1332191019412) should be 0.0");
x = FastMath.exp(Double.NaN);
if (x == x)
throw new RuntimeException("exp of NaN should be NaN");
x = FastMath.exp(Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("exp of infinity should be infinity");
x = FastMath.exp(Double.NEGATIVE_INFINITY);
if (x != 0.0)
throw new RuntimeException("exp of -infinity should be 0.0");
x = FastMath.exp(1.0);
if (x != Math.E)
throw new RuntimeException("exp(1) should be Math.E");
}
@Test
public void testPowSpecialCases() {
double x;
x = FastMath.pow(-1.0, 0.0);
if (x != 1.0)
throw new RuntimeException("pow(x, 0) should be 1.0");
x = FastMath.pow(-1.0, -0.0);
if (x != 1.0)
throw new RuntimeException("pow(x, -0) should be 1.0");
x = FastMath.pow(Math.PI, 1.0);
if (x != Math.PI)
throw new RuntimeException("pow(PI, 1.0) should be PI");
x = FastMath.pow(-Math.PI, 1.0);
if (x != -Math.PI)
throw new RuntimeException("pow(-PI, 1.0) should be PI");
x = FastMath.pow(Math.PI, Double.NaN);
if (x == x)
throw new RuntimeException("pow(PI, NaN) should be NaN");
x = FastMath.pow(Double.NaN, Math.PI);
if (x == x)
throw new RuntimeException("pow(NaN, PI) should be NaN");
x = FastMath.pow(2.0, Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(2.0, Infinity) should be Infinity");
x = FastMath.pow(0.5, Double.NEGATIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(0.5, -Infinity) should be Infinity");
x = FastMath.pow(0.5, Double.POSITIVE_INFINITY);
if (x != 0.0)
throw new RuntimeException("pow(0.5, Infinity) should be 0.0");
x = FastMath.pow(2.0, Double.NEGATIVE_INFINITY);
if (x != 0.0)
throw new RuntimeException("pow(2.0, -Infinity) should be 0.0");
x = FastMath.pow(0.0, 0.5);
if (x != 0.0)
throw new RuntimeException("pow(0.0, 0.5) should be 0.0");
x = FastMath.pow(Double.POSITIVE_INFINITY, -0.5);
if (x != 0.0)
throw new RuntimeException("pow(Inf, -0.5) should be 0.0");
x = FastMath.pow(0.0, -0.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(0.0, -0.5) should be Inf");
x = FastMath.pow(Double.POSITIVE_INFINITY, 0.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(Inf, 0.5) should be Inf");
x = FastMath.pow(-0.0, -3.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("pow(-0.0, -3.0) should be -Inf");
x = FastMath.pow(Double.NEGATIVE_INFINITY, 3.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("pow(-Inf, -3.0) should be -Inf");
x = FastMath.pow(-0.0, -3.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(-0.0, -3.5) should be Inf");
x = FastMath.pow(Double.POSITIVE_INFINITY, 3.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(Inf, 3.5) should be Inf");
x = FastMath.pow(-2.0, 3.0);
if (x != -8.0)
throw new RuntimeException("pow(-2.0, 3.0) should be -8.0");
x = FastMath.pow(-2.0, 3.5);
if (x == x)
throw new RuntimeException("pow(-2.0, 3.5) should be NaN");
}
@Test
public void testAtan2SpecialCases() {
double x;
x = FastMath.atan2(Double.NaN, 0.0);
if (x == x)
throw new RuntimeException("atan2(NaN, 0.0) should be NaN");
x = FastMath.atan2(0.0, Double.NaN);
if (x == x)
throw new RuntimeException("atan2(0.0, NaN) should be NaN");
x = FastMath.atan2(0.0, 0.0);
if (x != 0.0 || 1 / x != Double.POSITIVE_INFINITY)
throw new RuntimeException("atan2(0.0, 0.0) should be 0.0");
x = FastMath.atan2(0.0, 0.001);
if (x != 0.0 || 1 / x != Double.POSITIVE_INFINITY)
throw new RuntimeException("atan2(0.0, 0.001) should be 0.0");
x = FastMath.atan2(0.1, Double.POSITIVE_INFINITY);
if (x != 0.0 || 1 / x != Double.POSITIVE_INFINITY)
throw new RuntimeException("atan2(0.1, +Inf) should be 0.0");
x = FastMath.atan2(-0.0, 0.0);
if (x != 0.0 || 1 / x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("atan2(-0.0, 0.0) should be -0.0");
x = FastMath.atan2(-0.0, 0.001);
if (x != 0.0 || 1 / x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("atan2(-0.0, 0.001) should be -0.0");
x = FastMath.atan2(-0.1, Double.POSITIVE_INFINITY);
if (x != 0.0 || 1 / x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("atan2(-0.0, +Inf) should be -0.0");
x = FastMath.atan2(0.0, -0.0);
if (x != Math.PI)
throw new RuntimeException("atan2(0.0, -0.0) should be PI");
x = FastMath.atan2(0.1, Double.NEGATIVE_INFINITY);
if (x != Math.PI)
throw new RuntimeException("atan2(0.1, -Inf) should be PI");
x = FastMath.atan2(-0.0, -0.0);
if (x != -Math.PI)
throw new RuntimeException("atan2(-0.0, -0.0) should be -PI");
x = FastMath.atan2(-0.1, Double.NEGATIVE_INFINITY);
if (x != -Math.PI)
throw new RuntimeException("atan2(0.1, -Inf) should be -PI");
x = FastMath.atan2(0.1, 0.0);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(0.1, 0.0) should be PI/2");
x = FastMath.atan2(0.1, -0.0);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(0.1, -0.0) should be PI/2");
x = FastMath.atan2(Double.POSITIVE_INFINITY, 0.1);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(Inf, 0.1) should be PI/2");
x = FastMath.atan2(Double.POSITIVE_INFINITY, -0.1);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(Inf, -0.1) should be PI/2");
x = FastMath.atan2(-0.1, 0.0);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-0.1, 0.0) should be -PI/2");
x = FastMath.atan2(-0.1, -0.0);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-0.1, -0.0) should be -PI/2");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, 0.1);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-Inf, 0.1) should be -PI/2");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, -0.1);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-Inf, -0.1) should be -PI/2");
x = FastMath.atan2(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
if (x != Math.PI / 4)
throw new RuntimeException("atan2(Inf, Inf) should be PI/4");
x = FastMath.atan2(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
if (x != Math.PI * 3.0 / 4.0)
throw new RuntimeException("atan2(Inf, -Inf) should be PI * 3/4");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
if (x != -Math.PI / 4)
throw new RuntimeException("atan2(-Inf, Inf) should be -PI/4");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
if (x != -Math.PI * 3.0 / 4.0)
throw new RuntimeException("atan2(-Inf, -Inf) should be -PI * 3/4");
}
@Test
public void testPowAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = (generator.nextDouble() * 2.0 + 0.25);
double y = (generator.nextDouble() * 1200.0 - 600.0) * generator.nextDouble();
/*
* double x = FastMath.floor(generator.nextDouble()*1024.0 - 512.0); double
* y; if (x != 0) y = FastMath.floor(512.0 / FastMath.abs(x)); else
* y = generator.nextDouble()*1200.0; y = y - y/2; x = FastMath.pow(2.0, x) *
* generator.nextDouble(); y = y * generator.nextDouble();
*/
// double x = generator.nextDouble()*2.0;
double tst = FastMath.pow(x, y);
double ref = DfpMath.pow(field.newDfp(x), field.newDfp(y)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.pow(field.newDfp(x), field.newDfp(y))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + y + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("pow() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testExpAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.exp(x);
double ref = DfpMath.exp(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("exp() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testSinAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = ((generator.nextDouble() * Math.PI) - Math.PI / 2.0) *
Math.pow(2, 21) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.sin(x);
double ref = DfpMath.sin(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.sin(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("sin() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testCosAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = ((generator.nextDouble() * Math.PI) - Math.PI / 2.0) *
Math.pow(2, 21) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.cos(x);
double ref = DfpMath.cos(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.cos(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("cos() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testTanAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = ((generator.nextDouble() * Math.PI) - Math.PI / 2.0) *
Math.pow(2, 12) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.tan(x);
double ref = DfpMath.tan(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.tan(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("tan() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAtanAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
// double x = ((generator.nextDouble() * Math.PI) - Math.PI/2.0) *
// generator.nextDouble();
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.atan(x);
double ref = DfpMath.atan(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.atan(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("atan() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAtan2Accuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = generator.nextDouble() - 0.5;
double y = generator.nextDouble() - 0.5;
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.atan2(y, x);
Dfp refdfp = DfpMath.atan(field.newDfp(y)
.divide(field.newDfp(x)));
/* Make adjustments for sign */
if (x < 0.0) {
if (y > 0.0)
refdfp = field.getPi().add(refdfp);
else
refdfp = refdfp.subtract(field.getPi());
}
double ref = refdfp.toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(refdfp).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + y + "\t" + tst + "\t" + ref + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("atan2() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testExpm1Accuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = (generator.nextDouble() * 20.0) - 10.0;
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.expm1(x);
double ref = DfpMath.exp(field.newDfp(x)).subtract(field.getOne()).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x)).subtract(field.getOne())).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("expm1() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAsinAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
double tst = FastMath.asin(x);
double ref = DfpMath.asin(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.asin(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("asin() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAcosAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
double tst = FastMath.acos(x);
double ref = DfpMath.acos(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.acos(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("acos() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
private Dfp cosh(Dfp x) {
return DfpMath.exp(x).add(DfpMath.exp(x.negate())).divide(2);
}
private Dfp sinh(Dfp x) {
return DfpMath.exp(x).subtract(DfpMath.exp(x.negate())).divide(2);
}
private Dfp tanh(Dfp x) {
return sinh(x).divide(cosh(x));
}
@Test
public void testSinhAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = FastMath.sinh(x);
double ref = sinh(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(sinh(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("sinh() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testCoshAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = FastMath.cosh(x);
double ref = cosh(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(cosh(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("cosh() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testTanhAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = FastMath.tanh(x);
double ref = tanh(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(tanh(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("tanh() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testCbrtAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 200.0) - 100.0) * generator.nextDouble();
double tst = FastMath.cbrt(x);
double ref = cbrt(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(cbrt(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("cbrt() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
private Dfp cbrt(Dfp x) {
boolean negative=false;
if (x.lessThan(field.getZero())) {
negative = true;
x = x.negate();
}
Dfp y = DfpMath.pow(x, field.getOne().divide(3));
if (negative) {
y = y.negate();
}
return y;
}
@Test
public void testToDegrees() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = generator.nextDouble();
double tst = field.newDfp(x).multiply(180).divide(field.getPi()).toDouble();
double ref = FastMath.toDegrees(x);
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x)).subtract(field.getOne())).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("toDegrees() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testToRadians() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = generator.nextDouble();
double tst = field.newDfp(x).multiply(field.getPi()).divide(180).toDouble();
double ref = FastMath.toRadians(x);
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x)).subtract(field.getOne())).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("toRadians() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Ignore
@Test
public void testPerformance() {
final int numberOfRuns = 10000000;
for (int j = 0; j < 10; j++) {
double x = 0;
long time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.log(Math.PI + i/* 1.0 + i/1e9 */);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.log " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.log(Math.PI + i/* 1.0 + i/1e9 */);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.log " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.pow(Math.PI + i / 1e6, i / 1e6);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.pow " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.pow(Math.PI + i / 1e6, i / 1e6);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.pow " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.exp(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.exp " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.exp(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.exp " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.sin(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.sin " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.sin(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.sin " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.asin(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.asin " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.asin(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.asin " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.cos(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.cos " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.cos(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.cos " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.acos(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.acos " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.acos(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.acos " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.tan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.tan " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.tan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.tan " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.atan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.atan " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.atan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.atan " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.cbrt(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.cbrt " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.cbrt(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.cbrt " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.cosh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.cosh " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.cosh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.cosh " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.sinh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.sinh " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.sinh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.sinh " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.tanh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.tanh " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.tanh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.tanh " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.expm1(-i / 100000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.expm1 " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.expm1(-i / 100000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.expm1 " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.expm1(-i / 100000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.expm1 " + time + "\t" + x);
}
}
} | // You are a professional Java test case writer, please create a test case named `testMinMaxFloat` for the issue `Math-MATH-482`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-482
//
// ## Issue-Title:
// FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f
//
// ## Issue-Description:
//
// FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f.
//
//
// This is because the wrong variable is returned.
//
//
// The bug was not detected by the test case "testMinMaxFloat()" because that has a bug too - it tests doubles, not floats.
//
//
//
//
//
@Test
public void testMinMaxFloat() {
| 107 | 59 | 76 | src/test/java/org/apache/commons/math/util/FastMathTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-482
## Issue-Title:
FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f
## Issue-Description:
FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f.
This is because the wrong variable is returned.
The bug was not detected by the test case "testMinMaxFloat()" because that has a bug too - it tests doubles, not floats.
```
You are a professional Java test case writer, please create a test case named `testMinMaxFloat` for the issue `Math-MATH-482`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testMinMaxFloat() {
```
| 76 | [
"org.apache.commons.math.util.FastMath"
] | 3eddad48f38ae8c77fb39a7e4e7f580a3f026ace4e37c495a626701548ebcd73 | @Test
public void testMinMaxFloat() | // You are a professional Java test case writer, please create a test case named `testMinMaxFloat` for the issue `Math-MATH-482`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-482
//
// ## Issue-Title:
// FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f
//
// ## Issue-Description:
//
// FastMath.max(50.0f, -50.0f) => -50.0f; should be +50.0f.
//
//
// This is because the wrong variable is returned.
//
//
// The bug was not detected by the test case "testMinMaxFloat()" because that has a bug too - it tests doubles, not floats.
//
//
//
//
//
| Math | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.util;
import org.apache.commons.math.dfp.Dfp;
import org.apache.commons.math.dfp.DfpField;
import org.apache.commons.math.dfp.DfpMath;
import org.apache.commons.math.random.MersenneTwister;
import org.apache.commons.math.random.RandomGenerator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class FastMathTest {
private static final double MAX_ERROR_ULP = 0.51;
private static final int NUMBER_OF_TRIALS = 1000;
private DfpField field;
private RandomGenerator generator;
@Before
public void setUp() {
field = new DfpField(40);
generator = new MersenneTwister(6176597458463500194l);
}
@Test
public void testMinMaxDouble() {
double[][] pairs = {
{ -50.0, 50.0 },
{ Double.POSITIVE_INFINITY, 1.0 },
{ Double.NEGATIVE_INFINITY, 1.0 },
{ Double.NaN, 1.0 },
{ Double.POSITIVE_INFINITY, 0.0 },
{ Double.NEGATIVE_INFINITY, 0.0 },
{ Double.NaN, 0.0 },
{ Double.NaN, Double.NEGATIVE_INFINITY },
{ Double.NaN, Double.POSITIVE_INFINITY },
{ MathUtils.SAFE_MIN, MathUtils.EPSILON }
};
for (double[] pair : pairs) {
Assert.assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
Math.min(pair[0], pair[1]),
FastMath.min(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("min(" + pair[1] + ", " + pair[0] + ")",
Math.min(pair[1], pair[0]),
FastMath.min(pair[1], pair[0]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[0] + ", " + pair[1] + ")",
Math.max(pair[0], pair[1]),
FastMath.max(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[1] + ", " + pair[0] + ")",
Math.max(pair[1], pair[0]),
FastMath.max(pair[1], pair[0]),
MathUtils.EPSILON);
}
}
@Test
public void testMinMaxFloat() {
float[][] pairs = {
{ -50.0f, 50.0f },
{ Float.POSITIVE_INFINITY, 1.0f },
{ Float.NEGATIVE_INFINITY, 1.0f },
{ Float.NaN, 1.0f },
{ Float.POSITIVE_INFINITY, 0.0f },
{ Float.NEGATIVE_INFINITY, 0.0f },
{ Float.NaN, 0.0f },
{ Float.NaN, Float.NEGATIVE_INFINITY },
{ Float.NaN, Float.POSITIVE_INFINITY }
};
for (float[] pair : pairs) {
Assert.assertEquals("min(" + pair[0] + ", " + pair[1] + ")",
Math.min(pair[0], pair[1]),
FastMath.min(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("min(" + pair[1] + ", " + pair[0] + ")",
Math.min(pair[1], pair[0]),
FastMath.min(pair[1], pair[0]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[0] + ", " + pair[1] + ")",
Math.max(pair[0], pair[1]),
FastMath.max(pair[0], pair[1]),
MathUtils.EPSILON);
Assert.assertEquals("max(" + pair[1] + ", " + pair[0] + ")",
Math.max(pair[1], pair[0]),
FastMath.max(pair[1], pair[0]),
MathUtils.EPSILON);
}
}
@Test
public void testConstants() {
Assert.assertEquals(Math.PI, FastMath.PI, 1.0e-20);
Assert.assertEquals(Math.E, FastMath.E, 1.0e-20);
}
@Test
public void testAtan2() {
double y1 = 1.2713504628280707e10;
double x1 = -5.674940885228782e-10;
Assert.assertEquals(Math.atan2(y1, x1), FastMath.atan2(y1, x1), 2 * MathUtils.EPSILON);
double y2 = 0.0;
double x2 = Double.POSITIVE_INFINITY;
Assert.assertEquals(Math.atan2(y2, x2), FastMath.atan2(y2, x2), MathUtils.SAFE_MIN);
}
@Test
public void testHyperbolic() {
double maxErr = 0;
for (double x = -30; x < 30; x += 0.001) {
double tst = FastMath.sinh(x);
double ref = Math.sinh(x);
maxErr = FastMath.max(maxErr, FastMath.abs(ref - tst) / FastMath.ulp(ref));
}
Assert.assertEquals(0, maxErr, 2);
maxErr = 0;
for (double x = -30; x < 30; x += 0.001) {
double tst = FastMath.cosh(x);
double ref = Math.cosh(x);
maxErr = FastMath.max(maxErr, FastMath.abs(ref - tst) / FastMath.ulp(ref));
}
Assert.assertEquals(0, maxErr, 2);
maxErr = 0;
for (double x = -0.5; x < 0.5; x += 0.001) {
double tst = FastMath.tanh(x);
double ref = Math.tanh(x);
maxErr = FastMath.max(maxErr, FastMath.abs(ref - tst) / FastMath.ulp(ref));
}
Assert.assertEquals(0, maxErr, 4);
}
@Test
public void testHyperbolicInverses() {
double maxErr = 0;
for (double x = -30; x < 30; x += 0.01) {
maxErr = FastMath.max(maxErr, FastMath.abs(x - FastMath.sinh(FastMath.asinh(x))) / (2 * FastMath.ulp(x)));
}
Assert.assertEquals(0, maxErr, 3);
maxErr = 0;
for (double x = 1; x < 30; x += 0.01) {
maxErr = FastMath.max(maxErr, FastMath.abs(x - FastMath.cosh(FastMath.acosh(x))) / (2 * FastMath.ulp(x)));
}
Assert.assertEquals(0, maxErr, 2);
maxErr = 0;
for (double x = -1 + MathUtils.EPSILON; x < 1 - MathUtils.EPSILON; x += 0.0001) {
maxErr = FastMath.max(maxErr, FastMath.abs(x - FastMath.tanh(FastMath.atanh(x))) / (2 * FastMath.ulp(x)));
}
Assert.assertEquals(0, maxErr, 2);
}
@Test
public void testLogAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.exp(generator.nextDouble() * 1416.0 - 708.0) * generator.nextDouble();
// double x = generator.nextDouble()*2.0;
double tst = FastMath.log(x);
double ref = DfpMath.log(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0.0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.log(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("log() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testLog10Accuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.exp(generator.nextDouble() * 1416.0 - 708.0) * generator.nextDouble();
// double x = generator.nextDouble()*2.0;
double tst = FastMath.log10(x);
double ref = DfpMath.log(field.newDfp(x)).divide(DfpMath.log(field.newDfp("10"))).toDouble();
double err = (tst - ref) / ref;
if (err != 0.0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.log(field.newDfp(x)).divide(DfpMath.log(field.newDfp("10")))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("log10() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testLog1pAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = Math.exp(generator.nextDouble() * 10.0 - 5.0) * generator.nextDouble();
// double x = generator.nextDouble()*2.0;
double tst = FastMath.log1p(x);
double ref = DfpMath.log(field.newDfp(x).add(field.getOne())).toDouble();
double err = (tst - ref) / ref;
if (err != 0.0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.log(field.newDfp(x).add(field.getOne()))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("log1p() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testLogSpecialCases() {
double x;
x = FastMath.log(0.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("Log of zero should be -Inf");
x = FastMath.log(-0.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("Log of zero should be -Inf");
x = FastMath.log(Double.NaN);
if (x == x)
throw new RuntimeException("Log of NaN should be NaN");
x = FastMath.log(-1.0);
if (x == x)
throw new RuntimeException("Log of negative number should be NaN");
x = FastMath.log(Double.MIN_VALUE);
if (x != -744.4400719213812)
throw new RuntimeException(
"Log of Double.MIN_VALUE should be -744.4400719213812");
x = FastMath.log(-1.0);
if (x == x)
throw new RuntimeException("Log of negative number should be NaN");
x = FastMath.log(Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("Log of infinity should be infinity");
}
@Test
public void testExpSpecialCases() {
double x;
/* Smallest value that will round up to Double.MIN_VALUE */
x = FastMath.exp(-745.1332191019411);
if (x != Double.MIN_VALUE)
throw new RuntimeException(
"exp(-745.1332191019411) should be Double.MIN_VALUE");
x = FastMath.exp(-745.1332191019412);
if (x != 0.0)
throw new RuntimeException("exp(-745.1332191019412) should be 0.0");
x = FastMath.exp(Double.NaN);
if (x == x)
throw new RuntimeException("exp of NaN should be NaN");
x = FastMath.exp(Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("exp of infinity should be infinity");
x = FastMath.exp(Double.NEGATIVE_INFINITY);
if (x != 0.0)
throw new RuntimeException("exp of -infinity should be 0.0");
x = FastMath.exp(1.0);
if (x != Math.E)
throw new RuntimeException("exp(1) should be Math.E");
}
@Test
public void testPowSpecialCases() {
double x;
x = FastMath.pow(-1.0, 0.0);
if (x != 1.0)
throw new RuntimeException("pow(x, 0) should be 1.0");
x = FastMath.pow(-1.0, -0.0);
if (x != 1.0)
throw new RuntimeException("pow(x, -0) should be 1.0");
x = FastMath.pow(Math.PI, 1.0);
if (x != Math.PI)
throw new RuntimeException("pow(PI, 1.0) should be PI");
x = FastMath.pow(-Math.PI, 1.0);
if (x != -Math.PI)
throw new RuntimeException("pow(-PI, 1.0) should be PI");
x = FastMath.pow(Math.PI, Double.NaN);
if (x == x)
throw new RuntimeException("pow(PI, NaN) should be NaN");
x = FastMath.pow(Double.NaN, Math.PI);
if (x == x)
throw new RuntimeException("pow(NaN, PI) should be NaN");
x = FastMath.pow(2.0, Double.POSITIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(2.0, Infinity) should be Infinity");
x = FastMath.pow(0.5, Double.NEGATIVE_INFINITY);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(0.5, -Infinity) should be Infinity");
x = FastMath.pow(0.5, Double.POSITIVE_INFINITY);
if (x != 0.0)
throw new RuntimeException("pow(0.5, Infinity) should be 0.0");
x = FastMath.pow(2.0, Double.NEGATIVE_INFINITY);
if (x != 0.0)
throw new RuntimeException("pow(2.0, -Infinity) should be 0.0");
x = FastMath.pow(0.0, 0.5);
if (x != 0.0)
throw new RuntimeException("pow(0.0, 0.5) should be 0.0");
x = FastMath.pow(Double.POSITIVE_INFINITY, -0.5);
if (x != 0.0)
throw new RuntimeException("pow(Inf, -0.5) should be 0.0");
x = FastMath.pow(0.0, -0.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(0.0, -0.5) should be Inf");
x = FastMath.pow(Double.POSITIVE_INFINITY, 0.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(Inf, 0.5) should be Inf");
x = FastMath.pow(-0.0, -3.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("pow(-0.0, -3.0) should be -Inf");
x = FastMath.pow(Double.NEGATIVE_INFINITY, 3.0);
if (x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("pow(-Inf, -3.0) should be -Inf");
x = FastMath.pow(-0.0, -3.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(-0.0, -3.5) should be Inf");
x = FastMath.pow(Double.POSITIVE_INFINITY, 3.5);
if (x != Double.POSITIVE_INFINITY)
throw new RuntimeException("pow(Inf, 3.5) should be Inf");
x = FastMath.pow(-2.0, 3.0);
if (x != -8.0)
throw new RuntimeException("pow(-2.0, 3.0) should be -8.0");
x = FastMath.pow(-2.0, 3.5);
if (x == x)
throw new RuntimeException("pow(-2.0, 3.5) should be NaN");
}
@Test
public void testAtan2SpecialCases() {
double x;
x = FastMath.atan2(Double.NaN, 0.0);
if (x == x)
throw new RuntimeException("atan2(NaN, 0.0) should be NaN");
x = FastMath.atan2(0.0, Double.NaN);
if (x == x)
throw new RuntimeException("atan2(0.0, NaN) should be NaN");
x = FastMath.atan2(0.0, 0.0);
if (x != 0.0 || 1 / x != Double.POSITIVE_INFINITY)
throw new RuntimeException("atan2(0.0, 0.0) should be 0.0");
x = FastMath.atan2(0.0, 0.001);
if (x != 0.0 || 1 / x != Double.POSITIVE_INFINITY)
throw new RuntimeException("atan2(0.0, 0.001) should be 0.0");
x = FastMath.atan2(0.1, Double.POSITIVE_INFINITY);
if (x != 0.0 || 1 / x != Double.POSITIVE_INFINITY)
throw new RuntimeException("atan2(0.1, +Inf) should be 0.0");
x = FastMath.atan2(-0.0, 0.0);
if (x != 0.0 || 1 / x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("atan2(-0.0, 0.0) should be -0.0");
x = FastMath.atan2(-0.0, 0.001);
if (x != 0.0 || 1 / x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("atan2(-0.0, 0.001) should be -0.0");
x = FastMath.atan2(-0.1, Double.POSITIVE_INFINITY);
if (x != 0.0 || 1 / x != Double.NEGATIVE_INFINITY)
throw new RuntimeException("atan2(-0.0, +Inf) should be -0.0");
x = FastMath.atan2(0.0, -0.0);
if (x != Math.PI)
throw new RuntimeException("atan2(0.0, -0.0) should be PI");
x = FastMath.atan2(0.1, Double.NEGATIVE_INFINITY);
if (x != Math.PI)
throw new RuntimeException("atan2(0.1, -Inf) should be PI");
x = FastMath.atan2(-0.0, -0.0);
if (x != -Math.PI)
throw new RuntimeException("atan2(-0.0, -0.0) should be -PI");
x = FastMath.atan2(-0.1, Double.NEGATIVE_INFINITY);
if (x != -Math.PI)
throw new RuntimeException("atan2(0.1, -Inf) should be -PI");
x = FastMath.atan2(0.1, 0.0);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(0.1, 0.0) should be PI/2");
x = FastMath.atan2(0.1, -0.0);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(0.1, -0.0) should be PI/2");
x = FastMath.atan2(Double.POSITIVE_INFINITY, 0.1);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(Inf, 0.1) should be PI/2");
x = FastMath.atan2(Double.POSITIVE_INFINITY, -0.1);
if (x != Math.PI / 2)
throw new RuntimeException("atan2(Inf, -0.1) should be PI/2");
x = FastMath.atan2(-0.1, 0.0);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-0.1, 0.0) should be -PI/2");
x = FastMath.atan2(-0.1, -0.0);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-0.1, -0.0) should be -PI/2");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, 0.1);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-Inf, 0.1) should be -PI/2");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, -0.1);
if (x != -Math.PI / 2)
throw new RuntimeException("atan2(-Inf, -0.1) should be -PI/2");
x = FastMath.atan2(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
if (x != Math.PI / 4)
throw new RuntimeException("atan2(Inf, Inf) should be PI/4");
x = FastMath.atan2(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
if (x != Math.PI * 3.0 / 4.0)
throw new RuntimeException("atan2(Inf, -Inf) should be PI * 3/4");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
if (x != -Math.PI / 4)
throw new RuntimeException("atan2(-Inf, Inf) should be -PI/4");
x = FastMath.atan2(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);
if (x != -Math.PI * 3.0 / 4.0)
throw new RuntimeException("atan2(-Inf, -Inf) should be -PI * 3/4");
}
@Test
public void testPowAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = (generator.nextDouble() * 2.0 + 0.25);
double y = (generator.nextDouble() * 1200.0 - 600.0) * generator.nextDouble();
/*
* double x = FastMath.floor(generator.nextDouble()*1024.0 - 512.0); double
* y; if (x != 0) y = FastMath.floor(512.0 / FastMath.abs(x)); else
* y = generator.nextDouble()*1200.0; y = y - y/2; x = FastMath.pow(2.0, x) *
* generator.nextDouble(); y = y * generator.nextDouble();
*/
// double x = generator.nextDouble()*2.0;
double tst = FastMath.pow(x, y);
double ref = DfpMath.pow(field.newDfp(x), field.newDfp(y)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.pow(field.newDfp(x), field.newDfp(y))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + y + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("pow() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testExpAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.exp(x);
double ref = DfpMath.exp(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("exp() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testSinAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = ((generator.nextDouble() * Math.PI) - Math.PI / 2.0) *
Math.pow(2, 21) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.sin(x);
double ref = DfpMath.sin(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.sin(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("sin() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testCosAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = ((generator.nextDouble() * Math.PI) - Math.PI / 2.0) *
Math.pow(2, 21) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.cos(x);
double ref = DfpMath.cos(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.cos(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("cos() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testTanAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = ((generator.nextDouble() * Math.PI) - Math.PI / 2.0) *
Math.pow(2, 12) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.tan(x);
double ref = DfpMath.tan(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.tan(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("tan() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAtanAccuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
// double x = ((generator.nextDouble() * Math.PI) - Math.PI/2.0) *
// generator.nextDouble();
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.atan(x);
double ref = DfpMath.atan(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.atan(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("atan() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAtan2Accuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = ((generator.nextDouble() * 1416.0) - 708.0) * generator.nextDouble();
double x = generator.nextDouble() - 0.5;
double y = generator.nextDouble() - 0.5;
// double x = (generator.nextDouble() * 20.0) - 10.0;
// double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.atan2(y, x);
Dfp refdfp = DfpMath.atan(field.newDfp(y)
.divide(field.newDfp(x)));
/* Make adjustments for sign */
if (x < 0.0) {
if (y > 0.0)
refdfp = field.getPi().add(refdfp);
else
refdfp = refdfp.subtract(field.getPi());
}
double ref = refdfp.toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(refdfp).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + y + "\t" + tst + "\t" + ref + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("atan2() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testExpm1Accuracy() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
/* double x = 1.0 + i/1024.0/2.0; */
// double x = (generator.nextDouble() * 20.0) - 10.0;
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
/* double x = 3.0 / 512.0 * i - 3.0; */
double tst = FastMath.expm1(x);
double ref = DfpMath.exp(field.newDfp(x)).subtract(field.getOne()).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x)).subtract(field.getOne())).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("expm1() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAsinAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
double tst = FastMath.asin(x);
double ref = DfpMath.asin(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.asin(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("asin() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testAcosAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 2.0) - 1.0) * generator.nextDouble();
double tst = FastMath.acos(x);
double ref = DfpMath.acos(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.acos(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("acos() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
private Dfp cosh(Dfp x) {
return DfpMath.exp(x).add(DfpMath.exp(x.negate())).divide(2);
}
private Dfp sinh(Dfp x) {
return DfpMath.exp(x).subtract(DfpMath.exp(x.negate())).divide(2);
}
private Dfp tanh(Dfp x) {
return sinh(x).divide(cosh(x));
}
@Test
public void testSinhAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = FastMath.sinh(x);
double ref = sinh(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(sinh(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("sinh() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testCoshAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = FastMath.cosh(x);
double ref = cosh(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(cosh(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("cosh() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testTanhAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 16.0) - 8.0) * generator.nextDouble();
double tst = FastMath.tanh(x);
double ref = tanh(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(tanh(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("tanh() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testCbrtAccuracy() {
double maxerrulp = 0.0;
for (int i=0; i<10000; i++) {
double x = ((generator.nextDouble() * 200.0) - 100.0) * generator.nextDouble();
double tst = FastMath.cbrt(x);
double ref = cbrt(field.newDfp(x)).toDouble();
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref - Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(cbrt(field.newDfp(x))).divide(field.newDfp(ulp)).toDouble();
//System.out.println(x+"\t"+tst+"\t"+ref+"\t"+err+"\t"+errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("cbrt() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
private Dfp cbrt(Dfp x) {
boolean negative=false;
if (x.lessThan(field.getZero())) {
negative = true;
x = x.negate();
}
Dfp y = DfpMath.pow(x, field.getOne().divide(3));
if (negative) {
y = y.negate();
}
return y;
}
@Test
public void testToDegrees() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = generator.nextDouble();
double tst = field.newDfp(x).multiply(180).divide(field.getPi()).toDouble();
double ref = FastMath.toDegrees(x);
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x)).subtract(field.getOne())).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("toDegrees() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Test
public void testToRadians() {
double maxerrulp = 0.0;
for (int i = 0; i < NUMBER_OF_TRIALS; i++) {
double x = generator.nextDouble();
double tst = field.newDfp(x).multiply(field.getPi()).divide(180).toDouble();
double ref = FastMath.toRadians(x);
double err = (tst - ref) / ref;
if (err != 0) {
double ulp = Math.abs(ref -
Double.longBitsToDouble((Double
.doubleToLongBits(ref) ^ 1)));
double errulp = field.newDfp(tst).subtract(DfpMath.exp(field.newDfp(x)).subtract(field.getOne())).divide(field.newDfp(ulp)).toDouble();
// System.out.println(x + "\t" + tst + "\t" + ref + "\t" + err + "\t" + errulp);
maxerrulp = Math.max(maxerrulp, Math.abs(errulp));
}
}
Assert.assertTrue("toRadians() had errors in excess of " + MAX_ERROR_ULP + " ULP", maxerrulp < MAX_ERROR_ULP);
}
@Ignore
@Test
public void testPerformance() {
final int numberOfRuns = 10000000;
for (int j = 0; j < 10; j++) {
double x = 0;
long time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.log(Math.PI + i/* 1.0 + i/1e9 */);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.log " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.log(Math.PI + i/* 1.0 + i/1e9 */);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.log " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.pow(Math.PI + i / 1e6, i / 1e6);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.pow " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.pow(Math.PI + i / 1e6, i / 1e6);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.pow " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.exp(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.exp " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.exp(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.exp " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.sin(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.sin " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.sin(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.sin " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.asin(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.asin " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.asin(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.asin " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.cos(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.cos " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.cos(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.cos " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.acos(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.acos " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.acos(i / 10000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.acos " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.tan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.tan " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.tan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.tan " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.atan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.atan " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.atan(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.atan " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.cbrt(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.cbrt " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.cbrt(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.cbrt " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.cosh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.cosh " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.cosh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.cosh " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.sinh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.sinh " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.sinh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.sinh " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.tanh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.tanh " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.tanh(i / 1000000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.tanh " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += StrictMath.expm1(-i / 100000.0);
time = System.currentTimeMillis() - time;
System.out.print("StrictMath.expm1 " + time + "\t" + x + "\t");
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.expm1(-i / 100000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.expm1 " + time + "\t" + x);
x = 0;
time = System.currentTimeMillis();
for (int i = 0; i < numberOfRuns; i++)
x += FastMath.expm1(-i / 100000.0);
time = System.currentTimeMillis() - time;
System.out.println("FastMath.expm1 " + time + "\t" + x);
}
}
} |
||
@Test
public void testYahooArticle() throws IOException {
File in = getFile("/htmltests/yahoo-article-1.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china");
Element p = doc.select("p:contains(Volt will be sold in the United States").first();
assertEquals("In July, GM said its electric Chevrolet Volt will be sold in the United States at $41,000 -- $8,000 more than its nearest competitor, the Nissan Leaf.", p.text());
} | org.jsoup.integration.ParseTest::testYahooArticle | src/test/java/org/jsoup/integration/ParseTest.java | 147 | src/test/java/org/jsoup/integration/ParseTest.java | testYahooArticle | package org.jsoup.integration;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import static org.junit.Assert.*;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Integration test: parses from real-world example HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class ParseTest {
@Test
public void testSmhBizArticle() throws IOException {
File in = getFile("/htmltests/smh-biz-article-1.html");
Document doc = Jsoup.parse(in, "UTF-8",
"http://www.smh.com.au/business/the-boards-next-fear-the-female-quota-20100106-lteq.html");
assertEquals("The board’s next fear: the female quota",
doc.title()); // note that the apos in the source is a literal ’ (8217), not escaped or '
assertEquals("en", doc.select("html").attr("xml:lang"));
Elements articleBody = doc.select(".articleBody > *");
assertEquals(17, articleBody.size());
// todo: more tests!
}
@Test
public void testNewsHomepage() throws IOException {
File in = getFile("/htmltests/news-com-au-home.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.news.com.au/");
assertEquals("News.com.au | News from Australia and around the world online | NewsComAu", doc.title());
assertEquals("Brace yourself for Metro meltdown", doc.select(".id1225817868581 h4").text().trim());
Element a = doc.select("a[href=/entertainment/horoscopes]").first();
assertEquals("/entertainment/horoscopes", a.attr("href"));
assertEquals("http://www.news.com.au/entertainment/horoscopes", a.attr("abs:href"));
Element hs = doc.select("a[href*=naughty-corners-are-a-bad-idea]").first();
assertEquals(
"http://www.heraldsun.com.au/news/naughty-corners-are-a-bad-idea-for-kids/story-e6frf7jo-1225817899003",
hs.attr("href"));
assertEquals(hs.attr("href"), hs.attr("abs:href"));
}
@Test
public void testGoogleSearchIpod() throws IOException {
File in = getFile("/htmltests/google-ipod.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.google.com/search?hl=en&q=ipod&aq=f&oq=&aqi=g10");
assertEquals("ipod - Google Search", doc.title());
Elements results = doc.select("h3.r > a");
assertEquals(12, results.size());
assertEquals(
"http://news.google.com/news?hl=en&q=ipod&um=1&ie=UTF-8&ei=uYlKS4SbBoGg6gPf-5XXCw&sa=X&oi=news_group&ct=title&resnum=1&ved=0CCIQsQQwAA",
results.get(0).attr("href"));
assertEquals("http://www.apple.com/itunes/",
results.get(1).attr("href"));
}
@Test
public void testBinary() throws IOException {
File in = getFile("/htmltests/thumb.jpg");
Document doc = Jsoup.parse(in, "UTF-8");
// nothing useful, but did not blow up
assertTrue(doc.text().contains("gd-jpeg"));
}
@Test
public void testYahooJp() throws IOException {
File in = getFile("/htmltests/yahoo-jp.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.yahoo.co.jp/index.html"); // http charset is utf-8.
assertEquals("Yahoo! JAPAN", doc.title());
Element a = doc.select("a[href=t/2322m2]").first();
assertEquals("http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/t/2322m2",
a.attr("abs:href")); // session put into <base>
assertEquals("全国、人気の駅ランキング", a.text());
}
@Test
public void testBaidu() throws IOException {
// tests <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
File in = getFile("/htmltests/baidu-cn-home.html");
Document doc = Jsoup.parse(in, null,
"http://www.baidu.com/"); // http charset is gb2312, but NOT specifying it, to test http-equiv parse
Element submit = doc.select("#su").first();
assertEquals("百度一下", submit.attr("value"));
// test from attribute match
submit = doc.select("input[value=百度一下]").first();
assertEquals("su", submit.id());
Element newsLink = doc.select("a:contains(新)").first();
assertEquals("http://news.baidu.com", newsLink.absUrl("href"));
// check auto-detect from meta
assertEquals("GB2312", doc.outputSettings().charset().displayName());
assertEquals("\n<title>百度一下,你就知道 </title>", doc.select("title").outerHtml());
doc.outputSettings().charset("ascii");
assertEquals("\n<title>百度一下,你就知道 </title>",
doc.select("title").outerHtml());
}
@Test
public void testHtml5Charset() throws IOException {
// test that <meta charset="gb2312"> works
File in = getFile("/htmltests/meta-charset-1.html");
Document doc = Jsoup.parse(in, null, "http://example.com/"); //gb2312, has html5 <meta charset>
assertEquals("新", doc.text());
assertEquals("GB2312", doc.outputSettings().charset().displayName());
// double check, no charset, falls back to utf8 which is incorrect
in = getFile("/htmltests/meta-charset-2.html"); //
doc = Jsoup.parse(in, null, "http://example.com"); // gb2312, no charset
assertEquals("UTF-8", doc.outputSettings().charset().displayName());
assertFalse("新".equals(doc.text()));
// confirm fallback to utf8
in = getFile("/htmltests/meta-charset-3.html");
doc = Jsoup.parse(in, null, "http://example.com/"); // utf8, no charset
assertEquals("UTF-8", doc.outputSettings().charset().displayName());
assertEquals("新", doc.text());
}
@Test
public void testNytArticle() throws IOException {
// has tags like <nyt_text>
File in = getFile("/htmltests/nyt-article-1.html");
Document doc = Jsoup.parse(in, null, "http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp");
Element headline = doc.select("nyt_headline[version=1.0]").first();
assertEquals("As BP Lays Out Future, It Will Not Include Hayward", headline.text());
}
@Test
public void testYahooArticle() throws IOException {
File in = getFile("/htmltests/yahoo-article-1.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china");
Element p = doc.select("p:contains(Volt will be sold in the United States").first();
assertEquals("In July, GM said its electric Chevrolet Volt will be sold in the United States at $41,000 -- $8,000 more than its nearest competitor, the Nissan Leaf.", p.text());
}
File getFile(String resourceName) {
try {
File file = new File(ParseTest.class.getResource(resourceName).toURI());
return file;
}
catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
} | // You are a professional Java test case writer, please create a test case named `testYahooArticle` for the issue `Jsoup-34`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-34
//
// ## Issue-Title:
// StringIndexOutOfBoundsException when parsing link http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china
//
// ## Issue-Description:
// java.lang.StringIndexOutOfBoundsException: String index out of range: 1
//
// at java.lang.String.charAt(String.java:686)
//
// at java.util.regex.Matcher.appendReplacement(Matcher.java:711)
//
// at org.jsoup.nodes.Entities.unescape(Entities.java:69)
//
// at org.jsoup.nodes.TextNode.createFromEncoded(TextNode.java:95)
//
// at org.jsoup.parser.Parser.parseTextNode(Parser.java:222)
//
// at org.jsoup.parser.Parser.parse(Parser.java:94)
//
// at org.jsoup.parser.Parser.parse(Parser.java:54)
//
// at org.jsoup.Jsoup.parse(Jsoup.java:30)
//
//
//
//
@Test
public void testYahooArticle() throws IOException {
| 147 | 6 | 141 | src/test/java/org/jsoup/integration/ParseTest.java | src/test/java | ```markdown
## Issue-ID: Jsoup-34
## Issue-Title:
StringIndexOutOfBoundsException when parsing link http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china
## Issue-Description:
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:686)
at java.util.regex.Matcher.appendReplacement(Matcher.java:711)
at org.jsoup.nodes.Entities.unescape(Entities.java:69)
at org.jsoup.nodes.TextNode.createFromEncoded(TextNode.java:95)
at org.jsoup.parser.Parser.parseTextNode(Parser.java:222)
at org.jsoup.parser.Parser.parse(Parser.java:94)
at org.jsoup.parser.Parser.parse(Parser.java:54)
at org.jsoup.Jsoup.parse(Jsoup.java:30)
```
You are a professional Java test case writer, please create a test case named `testYahooArticle` for the issue `Jsoup-34`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testYahooArticle() throws IOException {
```
| 141 | [
"org.jsoup.nodes.Entities"
] | 3ee9e8febb901c4757264c53cb30c7341810b2d22f56fff2682021ff47745b24 | @Test
public void testYahooArticle() throws IOException | // You are a professional Java test case writer, please create a test case named `testYahooArticle` for the issue `Jsoup-34`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-34
//
// ## Issue-Title:
// StringIndexOutOfBoundsException when parsing link http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china
//
// ## Issue-Description:
// java.lang.StringIndexOutOfBoundsException: String index out of range: 1
//
// at java.lang.String.charAt(String.java:686)
//
// at java.util.regex.Matcher.appendReplacement(Matcher.java:711)
//
// at org.jsoup.nodes.Entities.unescape(Entities.java:69)
//
// at org.jsoup.nodes.TextNode.createFromEncoded(TextNode.java:95)
//
// at org.jsoup.parser.Parser.parseTextNode(Parser.java:222)
//
// at org.jsoup.parser.Parser.parse(Parser.java:94)
//
// at org.jsoup.parser.Parser.parse(Parser.java:54)
//
// at org.jsoup.Jsoup.parse(Jsoup.java:30)
//
//
//
//
| Jsoup | package org.jsoup.integration;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import static org.junit.Assert.*;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Integration test: parses from real-world example HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class ParseTest {
@Test
public void testSmhBizArticle() throws IOException {
File in = getFile("/htmltests/smh-biz-article-1.html");
Document doc = Jsoup.parse(in, "UTF-8",
"http://www.smh.com.au/business/the-boards-next-fear-the-female-quota-20100106-lteq.html");
assertEquals("The board’s next fear: the female quota",
doc.title()); // note that the apos in the source is a literal ’ (8217), not escaped or '
assertEquals("en", doc.select("html").attr("xml:lang"));
Elements articleBody = doc.select(".articleBody > *");
assertEquals(17, articleBody.size());
// todo: more tests!
}
@Test
public void testNewsHomepage() throws IOException {
File in = getFile("/htmltests/news-com-au-home.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.news.com.au/");
assertEquals("News.com.au | News from Australia and around the world online | NewsComAu", doc.title());
assertEquals("Brace yourself for Metro meltdown", doc.select(".id1225817868581 h4").text().trim());
Element a = doc.select("a[href=/entertainment/horoscopes]").first();
assertEquals("/entertainment/horoscopes", a.attr("href"));
assertEquals("http://www.news.com.au/entertainment/horoscopes", a.attr("abs:href"));
Element hs = doc.select("a[href*=naughty-corners-are-a-bad-idea]").first();
assertEquals(
"http://www.heraldsun.com.au/news/naughty-corners-are-a-bad-idea-for-kids/story-e6frf7jo-1225817899003",
hs.attr("href"));
assertEquals(hs.attr("href"), hs.attr("abs:href"));
}
@Test
public void testGoogleSearchIpod() throws IOException {
File in = getFile("/htmltests/google-ipod.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.google.com/search?hl=en&q=ipod&aq=f&oq=&aqi=g10");
assertEquals("ipod - Google Search", doc.title());
Elements results = doc.select("h3.r > a");
assertEquals(12, results.size());
assertEquals(
"http://news.google.com/news?hl=en&q=ipod&um=1&ie=UTF-8&ei=uYlKS4SbBoGg6gPf-5XXCw&sa=X&oi=news_group&ct=title&resnum=1&ved=0CCIQsQQwAA",
results.get(0).attr("href"));
assertEquals("http://www.apple.com/itunes/",
results.get(1).attr("href"));
}
@Test
public void testBinary() throws IOException {
File in = getFile("/htmltests/thumb.jpg");
Document doc = Jsoup.parse(in, "UTF-8");
// nothing useful, but did not blow up
assertTrue(doc.text().contains("gd-jpeg"));
}
@Test
public void testYahooJp() throws IOException {
File in = getFile("/htmltests/yahoo-jp.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://www.yahoo.co.jp/index.html"); // http charset is utf-8.
assertEquals("Yahoo! JAPAN", doc.title());
Element a = doc.select("a[href=t/2322m2]").first();
assertEquals("http://www.yahoo.co.jp/_ylh=X3oDMTB0NWxnaGxsBF9TAzIwNzcyOTYyNjUEdGlkAzEyBHRtcGwDZ2Ex/t/2322m2",
a.attr("abs:href")); // session put into <base>
assertEquals("全国、人気の駅ランキング", a.text());
}
@Test
public void testBaidu() throws IOException {
// tests <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
File in = getFile("/htmltests/baidu-cn-home.html");
Document doc = Jsoup.parse(in, null,
"http://www.baidu.com/"); // http charset is gb2312, but NOT specifying it, to test http-equiv parse
Element submit = doc.select("#su").first();
assertEquals("百度一下", submit.attr("value"));
// test from attribute match
submit = doc.select("input[value=百度一下]").first();
assertEquals("su", submit.id());
Element newsLink = doc.select("a:contains(新)").first();
assertEquals("http://news.baidu.com", newsLink.absUrl("href"));
// check auto-detect from meta
assertEquals("GB2312", doc.outputSettings().charset().displayName());
assertEquals("\n<title>百度一下,你就知道 </title>", doc.select("title").outerHtml());
doc.outputSettings().charset("ascii");
assertEquals("\n<title>百度一下,你就知道 </title>",
doc.select("title").outerHtml());
}
@Test
public void testHtml5Charset() throws IOException {
// test that <meta charset="gb2312"> works
File in = getFile("/htmltests/meta-charset-1.html");
Document doc = Jsoup.parse(in, null, "http://example.com/"); //gb2312, has html5 <meta charset>
assertEquals("新", doc.text());
assertEquals("GB2312", doc.outputSettings().charset().displayName());
// double check, no charset, falls back to utf8 which is incorrect
in = getFile("/htmltests/meta-charset-2.html"); //
doc = Jsoup.parse(in, null, "http://example.com"); // gb2312, no charset
assertEquals("UTF-8", doc.outputSettings().charset().displayName());
assertFalse("新".equals(doc.text()));
// confirm fallback to utf8
in = getFile("/htmltests/meta-charset-3.html");
doc = Jsoup.parse(in, null, "http://example.com/"); // utf8, no charset
assertEquals("UTF-8", doc.outputSettings().charset().displayName());
assertEquals("新", doc.text());
}
@Test
public void testNytArticle() throws IOException {
// has tags like <nyt_text>
File in = getFile("/htmltests/nyt-article-1.html");
Document doc = Jsoup.parse(in, null, "http://www.nytimes.com/2010/07/26/business/global/26bp.html?hp");
Element headline = doc.select("nyt_headline[version=1.0]").first();
assertEquals("As BP Lays Out Future, It Will Not Include Hayward", headline.text());
}
@Test
public void testYahooArticle() throws IOException {
File in = getFile("/htmltests/yahoo-article-1.html");
Document doc = Jsoup.parse(in, "UTF-8", "http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china");
Element p = doc.select("p:contains(Volt will be sold in the United States").first();
assertEquals("In July, GM said its electric Chevrolet Volt will be sold in the United States at $41,000 -- $8,000 more than its nearest competitor, the Nissan Leaf.", p.text());
}
File getFile(String resourceName) {
try {
File file = new File(ParseTest.class.getResource(resourceName).toURI());
return file;
}
catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
} |
||
public void testNegativeZero() throws Exception {
JsonReader reader = new JsonReader(reader("[-0]"));
reader.setLenient(false);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals("-0", reader.nextString());
} | com.google.gson.stream.JsonReaderTest::testNegativeZero | gson/src/test/java/com/google/gson/stream/JsonReaderTest.java | 573 | gson/src/test/java/com/google/gson/stream/JsonReaderTest.java | testNegativeZero | /*
* Copyright (C) 2010 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.stream;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import junit.framework.TestCase;
import static com.google.gson.stream.JsonToken.BEGIN_ARRAY;
import static com.google.gson.stream.JsonToken.BEGIN_OBJECT;
import static com.google.gson.stream.JsonToken.BOOLEAN;
import static com.google.gson.stream.JsonToken.END_ARRAY;
import static com.google.gson.stream.JsonToken.END_OBJECT;
import static com.google.gson.stream.JsonToken.NAME;
import static com.google.gson.stream.JsonToken.NULL;
import static com.google.gson.stream.JsonToken.NUMBER;
import static com.google.gson.stream.JsonToken.STRING;
@SuppressWarnings("resource")
public final class JsonReaderTest extends TestCase {
public void testReadArray() throws IOException {
JsonReader reader = new JsonReader(reader("[true, true]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(true, reader.nextBoolean());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testReadEmptyArray() throws IOException {
JsonReader reader = new JsonReader(reader("[]"));
reader.beginArray();
assertFalse(reader.hasNext());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testReadObject() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\": \"android\", \"b\": \"banana\"}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("android", reader.nextString());
assertEquals("b", reader.nextName());
assertEquals("banana", reader.nextString());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testReadEmptyObject() throws IOException {
JsonReader reader = new JsonReader(reader("{}"));
reader.beginObject();
assertFalse(reader.hasNext());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipArray() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
assertEquals(123, reader.nextInt());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipArrayAfterPeek() throws Exception {
JsonReader reader = new JsonReader(reader(
"{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(BEGIN_ARRAY, reader.peek());
reader.skipValue();
assertEquals("b", reader.nextName());
assertEquals(123, reader.nextInt());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipTopLevelObject() throws Exception {
JsonReader reader = new JsonReader(reader(
"{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipObject() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipObjectAfterPeek() throws Exception {
String json = "{" + " \"one\": { \"num\": 1 }"
+ ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}";
JsonReader reader = new JsonReader(reader(json));
reader.beginObject();
assertEquals("one", reader.nextName());
assertEquals(BEGIN_OBJECT, reader.peek());
reader.skipValue();
assertEquals("two", reader.nextName());
assertEquals(BEGIN_OBJECT, reader.peek());
reader.skipValue();
assertEquals("three", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipInteger() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\":123456789,\"b\":-123456789}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipDouble() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\":-123.456e-789,\"b\":123456789.0}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testHelloWorld() throws IOException {
String json = "{\n" +
" \"hello\": true,\n" +
" \"foo\": [\"world\"]\n" +
"}";
JsonReader reader = new JsonReader(reader(json));
reader.beginObject();
assertEquals("hello", reader.nextName());
assertEquals(true, reader.nextBoolean());
assertEquals("foo", reader.nextName());
reader.beginArray();
assertEquals("world", reader.nextString());
reader.endArray();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testInvalidJsonInput() throws IOException {
String json = "{\n"
+ " \"h\\ello\": true,\n"
+ " \"foo\": [\"world\"]\n"
+ "}";
JsonReader reader = new JsonReader(reader(json));
reader.beginObject();
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testNulls() {
try {
new JsonReader(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testEmptyString() {
try {
new JsonReader(reader("")).beginArray();
fail();
} catch (IOException expected) {
}
try {
new JsonReader(reader("")).beginObject();
fail();
} catch (IOException expected) {
}
}
public void testCharacterUnescaping() throws IOException {
String json = "[\"a\","
+ "\"a\\\"\","
+ "\"\\\"\","
+ "\":\","
+ "\",\","
+ "\"\\b\","
+ "\"\\f\","
+ "\"\\n\","
+ "\"\\r\","
+ "\"\\t\","
+ "\" \","
+ "\"\\\\\","
+ "\"{\","
+ "\"}\","
+ "\"[\","
+ "\"]\","
+ "\"\\u0000\","
+ "\"\\u0019\","
+ "\"\\u20AC\""
+ "]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals("a", reader.nextString());
assertEquals("a\"", reader.nextString());
assertEquals("\"", reader.nextString());
assertEquals(":", reader.nextString());
assertEquals(",", reader.nextString());
assertEquals("\b", reader.nextString());
assertEquals("\f", reader.nextString());
assertEquals("\n", reader.nextString());
assertEquals("\r", reader.nextString());
assertEquals("\t", reader.nextString());
assertEquals(" ", reader.nextString());
assertEquals("\\", reader.nextString());
assertEquals("{", reader.nextString());
assertEquals("}", reader.nextString());
assertEquals("[", reader.nextString());
assertEquals("]", reader.nextString());
assertEquals("\0", reader.nextString());
assertEquals("\u0019", reader.nextString());
assertEquals("\u20AC", reader.nextString());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testUnescapingInvalidCharacters() throws IOException {
String json = "[\"\\u000g\"]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (NumberFormatException expected) {
}
}
public void testUnescapingTruncatedCharacters() throws IOException {
String json = "[\"\\u000";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testUnescapingTruncatedSequence() throws IOException {
String json = "[\"\\";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testIntegersWithFractionalPartSpecified() throws IOException {
JsonReader reader = new JsonReader(reader("[1.0,1.0,1.0]"));
reader.beginArray();
assertEquals(1.0, reader.nextDouble());
assertEquals(1, reader.nextInt());
assertEquals(1L, reader.nextLong());
}
public void testDoubles() throws IOException {
String json = "[-0.0,"
+ "1.0,"
+ "1.7976931348623157E308,"
+ "4.9E-324,"
+ "0.0,"
+ "-0.5,"
+ "2.2250738585072014E-308,"
+ "3.141592653589793,"
+ "2.718281828459045]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(-0.0, reader.nextDouble());
assertEquals(1.0, reader.nextDouble());
assertEquals(1.7976931348623157E308, reader.nextDouble());
assertEquals(4.9E-324, reader.nextDouble());
assertEquals(0.0, reader.nextDouble());
assertEquals(-0.5, reader.nextDouble());
assertEquals(2.2250738585072014E-308, reader.nextDouble());
assertEquals(3.141592653589793, reader.nextDouble());
assertEquals(2.718281828459045, reader.nextDouble());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictNonFiniteDoubles() throws IOException {
String json = "[NaN]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextDouble();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testStrictQuotedNonFiniteDoubles() throws IOException {
String json = "[\"NaN\"]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextDouble();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLenientNonFiniteDoubles() throws IOException {
String json = "[NaN, -Infinity, Infinity]";
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertTrue(Double.isNaN(reader.nextDouble()));
assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
reader.endArray();
}
public void testLenientQuotedNonFiniteDoubles() throws IOException {
String json = "[\"NaN\", \"-Infinity\", \"Infinity\"]";
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertTrue(Double.isNaN(reader.nextDouble()));
assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
reader.endArray();
}
public void testStrictNonFiniteDoublesWithSkipValue() throws IOException {
String json = "[NaN]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLongs() throws IOException {
String json = "[0,0,0,"
+ "1,1,1,"
+ "-1,-1,-1,"
+ "-9223372036854775808,"
+ "9223372036854775807]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(0L, reader.nextLong());
assertEquals(0, reader.nextInt());
assertEquals(0.0, reader.nextDouble());
assertEquals(1L, reader.nextLong());
assertEquals(1, reader.nextInt());
assertEquals(1.0, reader.nextDouble());
assertEquals(-1L, reader.nextLong());
assertEquals(-1, reader.nextInt());
assertEquals(-1.0, reader.nextDouble());
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(Long.MIN_VALUE, reader.nextLong());
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(Long.MAX_VALUE, reader.nextLong());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void disabled_testNumberWithOctalPrefix() throws IOException {
String json = "[01]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
try {
reader.nextInt();
fail();
} catch (MalformedJsonException expected) {
}
try {
reader.nextLong();
fail();
} catch (MalformedJsonException expected) {
}
try {
reader.nextDouble();
fail();
} catch (MalformedJsonException expected) {
}
assertEquals("01", reader.nextString());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testBooleans() throws IOException {
JsonReader reader = new JsonReader(reader("[true,false]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(false, reader.nextBoolean());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException {
JsonReader reader = new JsonReader(reader("[truey]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
try {
reader.nextBoolean();
fail();
} catch (IllegalStateException expected) {
}
assertEquals("truey", reader.nextString());
reader.endArray();
}
public void testMalformedNumbers() throws IOException {
assertNotANumber("-");
assertNotANumber(".");
// exponent lacks digit
assertNotANumber("e");
assertNotANumber("0e");
assertNotANumber(".e");
assertNotANumber("0.e");
assertNotANumber("-.0e");
// no integer
assertNotANumber("e1");
assertNotANumber(".e1");
assertNotANumber("-e1");
// trailing characters
assertNotANumber("1x");
assertNotANumber("1.1x");
assertNotANumber("1e1x");
assertNotANumber("1ex");
assertNotANumber("1.1ex");
assertNotANumber("1.1e1x");
// fraction has no digit
assertNotANumber("0.");
assertNotANumber("-0.");
assertNotANumber("0.e1");
assertNotANumber("-0.e1");
// no leading digit
assertNotANumber(".0");
assertNotANumber("-.0");
assertNotANumber(".0e1");
assertNotANumber("-.0e1");
}
private void assertNotANumber(String s) throws IOException {
JsonReader reader = new JsonReader(reader("[" + s + "]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(JsonToken.STRING, reader.peek());
assertEquals(s, reader.nextString());
reader.endArray();
}
public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException {
JsonReader reader = new JsonReader(reader("[12.34e5x]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals("12.34e5x", reader.nextString());
}
public void testPeekLongMinValue() throws IOException {
JsonReader reader = new JsonReader(reader("[-9223372036854775808]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals(-9223372036854775808L, reader.nextLong());
}
public void testPeekLongMaxValue() throws IOException {
JsonReader reader = new JsonReader(reader("[9223372036854775807]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals(9223372036854775807L, reader.nextLong());
}
public void testLongLargerThanMaxLongThatWrapsAround() throws IOException {
JsonReader reader = new JsonReader(reader("[22233720368547758070]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
}
public void testLongLargerThanMinLongThatWrapsAround() throws IOException {
JsonReader reader = new JsonReader(reader("[-22233720368547758070]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
}
/**
* Issue 1053, negative zero.
* @throws Exception
*/
public void testNegativeZero() throws Exception {
JsonReader reader = new JsonReader(reader("[-0]"));
reader.setLenient(false);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals("-0", reader.nextString());
}
/**
* This test fails because there's no double for 9223372036854775808, and our
* long parsing uses Double.parseDouble() for fractional values.
*/
public void disabled_testPeekLargerThanLongMaxValue() throws IOException {
JsonReader reader = new JsonReader(reader("[9223372036854775808]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException e) {
}
}
/**
* This test fails because there's no double for -9223372036854775809, and our
* long parsing uses Double.parseDouble() for fractional values.
*/
public void disabled_testPeekLargerThanLongMinValue() throws IOException {
JsonReader reader = new JsonReader(reader("[-9223372036854775809]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(-9223372036854775809d, reader.nextDouble());
}
/**
* This test fails because there's no double for 9223372036854775806, and
* our long parsing uses Double.parseDouble() for fractional values.
*/
public void disabled_testHighPrecisionLong() throws IOException {
String json = "[9223372036854775806.000]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(9223372036854775806L, reader.nextLong());
reader.endArray();
}
public void testPeekMuchLargerThanLongMinValue() throws IOException {
JsonReader reader = new JsonReader(reader("[-92233720368547758080]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(-92233720368547758080d, reader.nextDouble());
}
public void testQuotedNumberWithEscape() throws IOException {
JsonReader reader = new JsonReader(reader("[\"12\u00334\"]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
assertEquals(1234, reader.nextInt());
}
public void testMixedCaseLiterals() throws IOException {
JsonReader reader = new JsonReader(reader("[True,TruE,False,FALSE,NULL,nulL]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(true, reader.nextBoolean());
assertEquals(false, reader.nextBoolean());
assertEquals(false, reader.nextBoolean());
reader.nextNull();
reader.nextNull();
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testMissingValue() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testPrematureEndOfInput() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true,"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testPrematurelyClosed() throws IOException {
try {
JsonReader reader = new JsonReader(reader("{\"a\":[]}"));
reader.beginObject();
reader.close();
reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
try {
JsonReader reader = new JsonReader(reader("{\"a\":[]}"));
reader.close();
reader.beginObject();
fail();
} catch (IllegalStateException expected) {
}
try {
JsonReader reader = new JsonReader(reader("{\"a\":true}"));
reader.beginObject();
reader.nextName();
reader.peek();
reader.close();
reader.nextBoolean();
fail();
} catch (IllegalStateException expected) {
}
}
public void testNextFailuresDoNotAdvance() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true}"));
reader.beginObject();
try {
reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
assertEquals("a", reader.nextName());
try {
reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.beginArray();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.endArray();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.beginObject();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.endObject();
fail();
} catch (IllegalStateException expected) {
}
assertEquals(true, reader.nextBoolean());
try {
reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.beginArray();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.endArray();
fail();
} catch (IllegalStateException expected) {
}
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
reader.close();
}
public void testIntegerMismatchFailuresDoNotAdvance() throws IOException {
JsonReader reader = new JsonReader(reader("[1.5]"));
reader.beginArray();
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(1.5d, reader.nextDouble());
reader.endArray();
}
public void testStringNullIsNotNull() throws IOException {
JsonReader reader = new JsonReader(reader("[\"null\"]"));
reader.beginArray();
try {
reader.nextNull();
fail();
} catch (IllegalStateException expected) {
}
}
public void testNullLiteralIsNotAString() throws IOException {
JsonReader reader = new JsonReader(reader("[null]"));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
}
public void testStrictNameValueSeparator() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("{\"a\"=>true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
}
public void testLenientNameValueSeparator() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
reader = new JsonReader(reader("{\"a\"=>true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
}
public void testStrictNameValueSeparatorWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("{\"a\"=>true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testCommentsInStringValue() throws Exception {
JsonReader reader = new JsonReader(reader("[\"// comment\"]"));
reader.beginArray();
assertEquals("// comment", reader.nextString());
reader.endArray();
reader = new JsonReader(reader("{\"a\":\"#someComment\"}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("#someComment", reader.nextString());
reader.endObject();
reader = new JsonReader(reader("{\"#//a\":\"#some //Comment\"}"));
reader.beginObject();
assertEquals("#//a", reader.nextName());
assertEquals("#some //Comment", reader.nextString());
reader.endObject();
}
public void testStrictComments() throws IOException {
JsonReader reader = new JsonReader(reader("[// comment \n true]"));
reader.beginArray();
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[# comment \n true]"));
reader.beginArray();
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[/* comment */ true]"));
reader.beginArray();
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
}
public void testLenientComments() throws IOException {
JsonReader reader = new JsonReader(reader("[// comment \n true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader = new JsonReader(reader("[# comment \n true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader = new JsonReader(reader("[/* comment */ true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
}
public void testStrictCommentsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[// comment \n true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[# comment \n true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[/* comment */ true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictUnquotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{a:true}"));
reader.beginObject();
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testLenientUnquotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{a:true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
}
public void testStrictUnquotedNamesWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{a:true}"));
reader.beginObject();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictSingleQuotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{'a':true}"));
reader.beginObject();
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testLenientSingleQuotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{'a':true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
}
public void testStrictSingleQuotedNamesWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{'a':true}"));
reader.beginObject();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictUnquotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("[a]"));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testStrictUnquotedStringsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[a]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLenientUnquotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("[a]"));
reader.setLenient(true);
reader.beginArray();
assertEquals("a", reader.nextString());
}
public void testStrictSingleQuotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("['a']"));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testLenientSingleQuotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("['a']"));
reader.setLenient(true);
reader.beginArray();
assertEquals("a", reader.nextString());
}
public void testStrictSingleQuotedStringsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("['a']"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictSemicolonDelimitedArray() throws IOException {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.beginArray();
try {
reader.nextBoolean();
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
}
public void testLenientSemicolonDelimitedArray() throws IOException {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(true, reader.nextBoolean());
}
public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.beginArray();
try {
reader.skipValue();
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictSemicolonDelimitedNameValuePair() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextBoolean();
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testLenientSemicolonDelimitedNameValuePair() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
assertEquals("b", reader.nextName());
}
public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.skipValue();
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictUnnecessaryArraySeparators() throws IOException {
JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,true]"));
reader.beginArray();
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[true,]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,]"));
reader.beginArray();
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
}
public void testLenientUnnecessaryArraySeparators() throws IOException {
JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader.nextNull();
assertEquals(true, reader.nextBoolean());
reader.endArray();
reader = new JsonReader(reader("[,true]"));
reader.setLenient(true);
reader.beginArray();
reader.nextNull();
assertEquals(true, reader.nextBoolean());
reader.endArray();
reader = new JsonReader(reader("[true,]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader.nextNull();
reader.endArray();
reader = new JsonReader(reader("[,]"));
reader.setLenient(true);
reader.beginArray();
reader.nextNull();
reader.nextNull();
reader.endArray();
}
public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[true,]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictMultipleTopLevelValues() throws IOException {
JsonReader reader = new JsonReader(reader("[] []"));
reader.beginArray();
reader.endArray();
try {
reader.peek();
fail();
} catch (IOException expected) {
}
}
public void testLenientMultipleTopLevelValues() throws IOException {
JsonReader reader = new JsonReader(reader("[] true {}"));
reader.setLenient(true);
reader.beginArray();
reader.endArray();
assertEquals(true, reader.nextBoolean());
reader.beginObject();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[] []"));
reader.beginArray();
reader.endArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testTopLevelValueTypes() throws IOException {
JsonReader reader1 = new JsonReader(reader("true"));
assertTrue(reader1.nextBoolean());
assertEquals(JsonToken.END_DOCUMENT, reader1.peek());
JsonReader reader2 = new JsonReader(reader("false"));
assertFalse(reader2.nextBoolean());
assertEquals(JsonToken.END_DOCUMENT, reader2.peek());
JsonReader reader3 = new JsonReader(reader("null"));
assertEquals(JsonToken.NULL, reader3.peek());
reader3.nextNull();
assertEquals(JsonToken.END_DOCUMENT, reader3.peek());
JsonReader reader4 = new JsonReader(reader("123"));
assertEquals(123, reader4.nextInt());
assertEquals(JsonToken.END_DOCUMENT, reader4.peek());
JsonReader reader5 = new JsonReader(reader("123.4"));
assertEquals(123.4, reader5.nextDouble());
assertEquals(JsonToken.END_DOCUMENT, reader5.peek());
JsonReader reader6 = new JsonReader(reader("\"a\""));
assertEquals("a", reader6.nextString());
assertEquals(JsonToken.END_DOCUMENT, reader6.peek());
}
public void testTopLevelValueTypeWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("true"));
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictNonExecutePrefix() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
try {
reader.beginArray();
fail();
} catch (IOException expected) {
}
}
public void testStrictNonExecutePrefixWithSkipValue() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testLenientNonExecutePrefix() throws IOException {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
reader.setLenient(true);
reader.beginArray();
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException {
JsonReader reader = new JsonReader(reader("\r\n \t)]}'\n []"));
reader.setLenient(true);
reader.beginArray();
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testLenientPartialNonExecutePrefix() {
JsonReader reader = new JsonReader(reader(")]}' []"));
reader.setLenient(true);
try {
assertEquals(")", reader.nextString());
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException {
JsonReader reader = new JsonReader(reader("\ufeff[]"));
reader.beginArray();
reader.endArray();
}
public void testBomForbiddenAsOtherCharacterInDocument() throws IOException {
JsonReader reader = new JsonReader(reader("[\ufeff]"));
reader.beginArray();
try {
reader.endArray();
fail();
} catch (IOException expected) {
}
}
public void testFailWithPosition() throws IOException {
testFailWithPosition("Expected value at line 6 column 5 path $[1]",
"[\n\n\n\n\n\"a\",}]");
}
public void testFailWithPositionGreaterThanBufferSize() throws IOException {
String spaces = repeat(' ', 8192);
testFailWithPosition("Expected value at line 6 column 5 path $[1]",
"[\n\n" + spaces + "\n\n\n\"a\",}]");
}
public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException {
testFailWithPosition("Expected value at line 5 column 6 path $[1]",
"\n// foo\n\n//bar\r\n[\"a\",}");
}
public void testFailWithPositionOverHashEndOfLineComment() throws IOException {
testFailWithPosition("Expected value at line 5 column 6 path $[1]",
"\n# foo\n\n#bar\r\n[\"a\",}");
}
public void testFailWithPositionOverCStyleComment() throws IOException {
testFailWithPosition("Expected value at line 6 column 12 path $[1]",
"\n\n/* foo\n*\n*\r\nbar */[\"a\",}");
}
public void testFailWithPositionOverQuotedString() throws IOException {
testFailWithPosition("Expected value at line 5 column 3 path $[1]",
"[\"foo\nbar\r\nbaz\n\",\n }");
}
public void testFailWithPositionOverUnquotedString() throws IOException {
testFailWithPosition("Expected value at line 5 column 2 path $[1]", "[\n\nabcd\n\n,}");
}
public void testFailWithEscapedNewlineCharacter() throws IOException {
testFailWithPosition("Expected value at line 5 column 3 path $[1]", "[\n\n\"\\\n\n\",}");
}
public void testFailWithPositionIsOffsetByBom() throws IOException {
testFailWithPosition("Expected value at line 1 column 6 path $[1]",
"\ufeff[\"a\",}]");
}
private void testFailWithPosition(String message, String json) throws IOException {
// Validate that it works reading the string normally.
JsonReader reader1 = new JsonReader(reader(json));
reader1.setLenient(true);
reader1.beginArray();
reader1.nextString();
try {
reader1.peek();
fail();
} catch (IOException expected) {
assertEquals(message, expected.getMessage());
}
// Also validate that it works when skipping.
JsonReader reader2 = new JsonReader(reader(json));
reader2.setLenient(true);
reader2.beginArray();
reader2.skipValue();
try {
reader2.peek();
fail();
} catch (IOException expected) {
assertEquals(message, expected.getMessage());
}
}
public void testFailWithPositionDeepPath() throws IOException {
JsonReader reader = new JsonReader(reader("[1,{\"a\":[2,3,}"));
reader.beginArray();
reader.nextInt();
reader.beginObject();
reader.nextName();
reader.beginArray();
reader.nextInt();
reader.nextInt();
try {
reader.peek();
fail();
} catch (IOException expected) {
assertEquals("Expected value at line 1 column 14 path $[1].a[2]", expected.getMessage());
}
}
public void testStrictVeryLongNumber() throws IOException {
JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]"));
reader.beginArray();
try {
assertEquals(1d, reader.nextDouble());
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLenientVeryLongNumber() throws IOException {
JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(JsonToken.STRING, reader.peek());
assertEquals(1d, reader.nextDouble());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testVeryLongUnquotedLiteral() throws IOException {
String literal = "a" + repeat('b', 8192) + "c";
JsonReader reader = new JsonReader(reader("[" + literal + "]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(literal, reader.nextString());
reader.endArray();
}
public void testDeeplyNestedArrays() throws IOException {
// this is nested 40 levels deep; Gson is tuned for nesting is 30 levels deep or fewer
JsonReader reader = new JsonReader(reader(
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"));
for (int i = 0; i < 40; i++) {
reader.beginArray();
}
assertEquals("$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]"
+ "[0][0][0][0][0][0][0][0][0][0][0][0][0][0]", reader.getPath());
for (int i = 0; i < 40; i++) {
reader.endArray();
}
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testDeeplyNestedObjects() throws IOException {
// Build a JSON document structured like {"a":{"a":{"a":{"a":true}}}}, but 40 levels deep
String array = "{\"a\":%s}";
String json = "true";
for (int i = 0; i < 40; i++) {
json = String.format(array, json);
}
JsonReader reader = new JsonReader(reader(json));
for (int i = 0; i < 40; i++) {
reader.beginObject();
assertEquals("a", reader.nextName());
}
assertEquals("$.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a"
+ ".a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", reader.getPath());
assertEquals(true, reader.nextBoolean());
for (int i = 0; i < 40; i++) {
reader.endObject();
}
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
// http://code.google.com/p/google-gson/issues/detail?id=409
public void testStringEndingInSlash() throws IOException {
JsonReader reader = new JsonReader(reader("/"));
reader.setLenient(true);
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testDocumentWithCommentEndingInSlash() throws IOException {
JsonReader reader = new JsonReader(reader("/* foo *//"));
reader.setLenient(true);
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testStringWithLeadingSlash() throws IOException {
JsonReader reader = new JsonReader(reader("/x"));
reader.setLenient(true);
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testUnterminatedObject() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":\"android\"x"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("android", reader.nextString());
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testVeryLongQuotedString() throws IOException {
char[] stringChars = new char[1024 * 16];
Arrays.fill(stringChars, 'x');
String string = new String(stringChars);
String json = "[\"" + string + "\"]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(string, reader.nextString());
reader.endArray();
}
public void testVeryLongUnquotedString() throws IOException {
char[] stringChars = new char[1024 * 16];
Arrays.fill(stringChars, 'x');
String string = new String(stringChars);
String json = "[" + string + "]";
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertEquals(string, reader.nextString());
reader.endArray();
}
public void testVeryLongUnterminatedString() throws IOException {
char[] stringChars = new char[1024 * 16];
Arrays.fill(stringChars, 'x');
String string = new String(stringChars);
String json = "[" + string;
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertEquals(string, reader.nextString());
try {
reader.peek();
fail();
} catch (EOFException expected) {
}
}
public void testSkipVeryLongUnquotedString() throws IOException {
JsonReader reader = new JsonReader(reader("[" + repeat('x', 8192) + "]"));
reader.setLenient(true);
reader.beginArray();
reader.skipValue();
reader.endArray();
}
public void testSkipTopLevelUnquotedString() throws IOException {
JsonReader reader = new JsonReader(reader(repeat('x', 8192)));
reader.setLenient(true);
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipVeryLongQuotedString() throws IOException {
JsonReader reader = new JsonReader(reader("[\"" + repeat('x', 8192) + "\"]"));
reader.beginArray();
reader.skipValue();
reader.endArray();
}
public void testSkipTopLevelQuotedString() throws IOException {
JsonReader reader = new JsonReader(reader("\"" + repeat('x', 8192) + "\""));
reader.setLenient(true);
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStringAsNumberWithTruncatedExponent() throws IOException {
JsonReader reader = new JsonReader(reader("[123e]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
}
public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException {
JsonReader reader = new JsonReader(reader("[123e4b]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
}
public void testStringAsNumberWithNonDigitExponent() throws IOException {
JsonReader reader = new JsonReader(reader("[123eb]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
}
public void testEmptyStringName() throws IOException {
JsonReader reader = new JsonReader(reader("{\"\":true}"));
reader.setLenient(true);
assertEquals(BEGIN_OBJECT, reader.peek());
reader.beginObject();
assertEquals(NAME, reader.peek());
assertEquals("", reader.nextName());
assertEquals(JsonToken.BOOLEAN, reader.peek());
assertEquals(true, reader.nextBoolean());
assertEquals(JsonToken.END_OBJECT, reader.peek());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictExtraCommasInMaps() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("b", reader.nextString());
try {
reader.peek();
fail();
} catch (IOException expected) {
}
}
public void testLenientExtraCommasInMaps() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("b", reader.nextString());
try {
reader.peek();
fail();
} catch (IOException expected) {
}
}
private String repeat(char c, int count) {
char[] array = new char[count];
Arrays.fill(array, c);
return new String(array);
}
public void testMalformedDocuments() throws IOException {
assertDocument("{]", BEGIN_OBJECT, IOException.class);
assertDocument("{,", BEGIN_OBJECT, IOException.class);
assertDocument("{{", BEGIN_OBJECT, IOException.class);
assertDocument("{[", BEGIN_OBJECT, IOException.class);
assertDocument("{:", BEGIN_OBJECT, IOException.class);
assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\":}", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"::", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\":,", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"=}", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"=>}", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"=>\"string\":", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\"=", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\"=>", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\",\"name\"", BEGIN_OBJECT, NAME, STRING, NAME);
assertDocument("[}", BEGIN_ARRAY, IOException.class);
assertDocument("[,]", BEGIN_ARRAY, NULL, NULL, END_ARRAY);
assertDocument("{", BEGIN_OBJECT, IOException.class);
assertDocument("{\"name\"", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{'name'", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{'name',", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{name", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("[", BEGIN_ARRAY, IOException.class);
assertDocument("[string", BEGIN_ARRAY, STRING, IOException.class);
assertDocument("[\"string\"", BEGIN_ARRAY, STRING, IOException.class);
assertDocument("['string'", BEGIN_ARRAY, STRING, IOException.class);
assertDocument("[123", BEGIN_ARRAY, NUMBER, IOException.class);
assertDocument("[123,", BEGIN_ARRAY, NUMBER, IOException.class);
assertDocument("{\"name\":123", BEGIN_OBJECT, NAME, NUMBER, IOException.class);
assertDocument("{\"name\":123,", BEGIN_OBJECT, NAME, NUMBER, IOException.class);
assertDocument("{\"name\":\"string\"", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":'string'", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":'string',", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":false", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class);
assertDocument("{\"name\":false,,", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class);
}
/**
* This test behave slightly differently in Gson 2.2 and earlier. It fails
* during peek rather than during nextString().
*/
public void testUnterminatedStringFailure() throws IOException {
JsonReader reader = new JsonReader(reader("[\"string"));
reader.setLenient(true);
reader.beginArray();
assertEquals(JsonToken.STRING, reader.peek());
try {
reader.nextString();
fail();
} catch (MalformedJsonException expected) {
}
}
private void assertDocument(String document, Object... expectations) throws IOException {
JsonReader reader = new JsonReader(reader(document));
reader.setLenient(true);
for (Object expectation : expectations) {
if (expectation == BEGIN_OBJECT) {
reader.beginObject();
} else if (expectation == BEGIN_ARRAY) {
reader.beginArray();
} else if (expectation == END_OBJECT) {
reader.endObject();
} else if (expectation == END_ARRAY) {
reader.endArray();
} else if (expectation == NAME) {
assertEquals("name", reader.nextName());
} else if (expectation == BOOLEAN) {
assertEquals(false, reader.nextBoolean());
} else if (expectation == STRING) {
assertEquals("string", reader.nextString());
} else if (expectation == NUMBER) {
assertEquals(123, reader.nextInt());
} else if (expectation == NULL) {
reader.nextNull();
} else if (expectation == IOException.class) {
try {
reader.peek();
fail();
} catch (IOException expected) {
}
} else {
throw new AssertionError();
}
}
}
/**
* Returns a reader that returns one character at a time.
*/
private Reader reader(final String s) {
/* if (true) */ return new StringReader(s);
/* return new Reader() {
int position = 0;
@Override public int read(char[] buffer, int offset, int count) throws IOException {
if (position == s.length()) {
return -1;
} else if (count > 0) {
buffer[offset] = s.charAt(position++);
return 1;
} else {
throw new IllegalArgumentException();
}
}
@Override public void close() throws IOException {
}
}; */
}
} | // You are a professional Java test case writer, please create a test case named `testNegativeZero` for the issue `Gson-1053`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Gson-1053
//
// ## Issue-Title:
// Negative zero
//
// ## Issue-Description:
// Hi,
//
//
// I have been cross testing various json parsers looking for those that expose the lexical of json numbers and not only their bound java.lang.Number. Because of the lazy parsing done by gson with `LazilyParsedNumber`, that keeps the lexical, all my roundtrip tests pass apart one: the lexical `-0` that is treated as it were `0`
//
//
// I read some threads about negative zero:
//
// <https://www.ietf.org/mail-archive/web/json/current/msg03668.html>
//
// <https://www.ietf.org/mail-archive/web/json/current/msg01520.html>
//
// <https://www.ietf.org/mail-archive/web/json/current/msg01523.html>
//
// <https://www.ietf.org/mail-archive/web/json/current/msg01525.html>
//
//
// I created this issue thinking that `-0` is a float, the same as `-0.0`, since a signed zero makes sense only in floating point numbers and also because in Java only Double/Float preserve sign of zero. This would have the implication that `-0` could not be validated by jsonschema `type` `integer` , and that a jsonschema implementation would have the need to know if a `-0` is present in json data, but probably this is not the case.
//
//
// After I started to (re)consider that `-0` could be an integer, only that seems that in no programming language there is an integer that preserves sign for zero.
//
//
// In any case, differentiating between `0` and `-0` at lexical level would allow a client of gson to be able to refuse the value `-0`.
//
//
// Gson could easily support differentiating between `0` and `-0`: in code `-0` is [treated as an integer (PEEKED\_LONG) in JsonReader](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/stream/JsonReader.java#L731) so its value is stored in a Java `long` that cannot represent negative zero. I noted that `-0.0` roundtrips correctly because is treated as a PEEKED\_NUMBER that is kept as a Java String. So the case of `-0` could be trapped and treated as `-0.0`, as a PEEKED\_NUMBER, in this way the `toString()` method of `LazilyParsedNumber` will return `-0` and gson will be able to roundtrip any valid number value found in source, only clients using `Number.toString()` will notice any difference.
//
//
// My proposal is to change [this code](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/stream/JsonReader.java#L731) from
//
//
//
// ```
// if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
//
// ```
//
// to
//
//
//
// ```
// if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value!=0 || false==negative) && (value != Long.MIN_VALUE || negative)) {
//
// ```
//
// Thanks,
//
// Michele
//
//
//
//
public void testNegativeZero() throws Exception {
| 573 | /**
* Issue 1053, negative zero.
* @throws Exception
*/ | 13 | 567 | gson/src/test/java/com/google/gson/stream/JsonReaderTest.java | gson/src/test/java | ```markdown
## Issue-ID: Gson-1053
## Issue-Title:
Negative zero
## Issue-Description:
Hi,
I have been cross testing various json parsers looking for those that expose the lexical of json numbers and not only their bound java.lang.Number. Because of the lazy parsing done by gson with `LazilyParsedNumber`, that keeps the lexical, all my roundtrip tests pass apart one: the lexical `-0` that is treated as it were `0`
I read some threads about negative zero:
<https://www.ietf.org/mail-archive/web/json/current/msg03668.html>
<https://www.ietf.org/mail-archive/web/json/current/msg01520.html>
<https://www.ietf.org/mail-archive/web/json/current/msg01523.html>
<https://www.ietf.org/mail-archive/web/json/current/msg01525.html>
I created this issue thinking that `-0` is a float, the same as `-0.0`, since a signed zero makes sense only in floating point numbers and also because in Java only Double/Float preserve sign of zero. This would have the implication that `-0` could not be validated by jsonschema `type` `integer` , and that a jsonschema implementation would have the need to know if a `-0` is present in json data, but probably this is not the case.
After I started to (re)consider that `-0` could be an integer, only that seems that in no programming language there is an integer that preserves sign for zero.
In any case, differentiating between `0` and `-0` at lexical level would allow a client of gson to be able to refuse the value `-0`.
Gson could easily support differentiating between `0` and `-0`: in code `-0` is [treated as an integer (PEEKED\_LONG) in JsonReader](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/stream/JsonReader.java#L731) so its value is stored in a Java `long` that cannot represent negative zero. I noted that `-0.0` roundtrips correctly because is treated as a PEEKED\_NUMBER that is kept as a Java String. So the case of `-0` could be trapped and treated as `-0.0`, as a PEEKED\_NUMBER, in this way the `toString()` method of `LazilyParsedNumber` will return `-0` and gson will be able to roundtrip any valid number value found in source, only clients using `Number.toString()` will notice any difference.
My proposal is to change [this code](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/stream/JsonReader.java#L731) from
```
if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
```
to
```
if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value!=0 || false==negative) && (value != Long.MIN_VALUE || negative)) {
```
Thanks,
Michele
```
You are a professional Java test case writer, please create a test case named `testNegativeZero` for the issue `Gson-1053`, utilizing the provided issue report information and the following function signature.
```java
public void testNegativeZero() throws Exception {
```
| 567 | [
"com.google.gson.stream.JsonReader"
] | 3f73827c671fb384282d90c15f4b6730e33bbc20b1690ef17ba4b18b0a74634c | public void testNegativeZero() throws Exception | // You are a professional Java test case writer, please create a test case named `testNegativeZero` for the issue `Gson-1053`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Gson-1053
//
// ## Issue-Title:
// Negative zero
//
// ## Issue-Description:
// Hi,
//
//
// I have been cross testing various json parsers looking for those that expose the lexical of json numbers and not only their bound java.lang.Number. Because of the lazy parsing done by gson with `LazilyParsedNumber`, that keeps the lexical, all my roundtrip tests pass apart one: the lexical `-0` that is treated as it were `0`
//
//
// I read some threads about negative zero:
//
// <https://www.ietf.org/mail-archive/web/json/current/msg03668.html>
//
// <https://www.ietf.org/mail-archive/web/json/current/msg01520.html>
//
// <https://www.ietf.org/mail-archive/web/json/current/msg01523.html>
//
// <https://www.ietf.org/mail-archive/web/json/current/msg01525.html>
//
//
// I created this issue thinking that `-0` is a float, the same as `-0.0`, since a signed zero makes sense only in floating point numbers and also because in Java only Double/Float preserve sign of zero. This would have the implication that `-0` could not be validated by jsonschema `type` `integer` , and that a jsonschema implementation would have the need to know if a `-0` is present in json data, but probably this is not the case.
//
//
// After I started to (re)consider that `-0` could be an integer, only that seems that in no programming language there is an integer that preserves sign for zero.
//
//
// In any case, differentiating between `0` and `-0` at lexical level would allow a client of gson to be able to refuse the value `-0`.
//
//
// Gson could easily support differentiating between `0` and `-0`: in code `-0` is [treated as an integer (PEEKED\_LONG) in JsonReader](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/stream/JsonReader.java#L731) so its value is stored in a Java `long` that cannot represent negative zero. I noted that `-0.0` roundtrips correctly because is treated as a PEEKED\_NUMBER that is kept as a Java String. So the case of `-0` could be trapped and treated as `-0.0`, as a PEEKED\_NUMBER, in this way the `toString()` method of `LazilyParsedNumber` will return `-0` and gson will be able to roundtrip any valid number value found in source, only clients using `Number.toString()` will notice any difference.
//
//
// My proposal is to change [this code](https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/stream/JsonReader.java#L731) from
//
//
//
// ```
// if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
//
// ```
//
// to
//
//
//
// ```
// if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value!=0 || false==negative) && (value != Long.MIN_VALUE || negative)) {
//
// ```
//
// Thanks,
//
// Michele
//
//
//
//
| Gson | /*
* Copyright (C) 2010 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.stream;
import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import junit.framework.TestCase;
import static com.google.gson.stream.JsonToken.BEGIN_ARRAY;
import static com.google.gson.stream.JsonToken.BEGIN_OBJECT;
import static com.google.gson.stream.JsonToken.BOOLEAN;
import static com.google.gson.stream.JsonToken.END_ARRAY;
import static com.google.gson.stream.JsonToken.END_OBJECT;
import static com.google.gson.stream.JsonToken.NAME;
import static com.google.gson.stream.JsonToken.NULL;
import static com.google.gson.stream.JsonToken.NUMBER;
import static com.google.gson.stream.JsonToken.STRING;
@SuppressWarnings("resource")
public final class JsonReaderTest extends TestCase {
public void testReadArray() throws IOException {
JsonReader reader = new JsonReader(reader("[true, true]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(true, reader.nextBoolean());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testReadEmptyArray() throws IOException {
JsonReader reader = new JsonReader(reader("[]"));
reader.beginArray();
assertFalse(reader.hasNext());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testReadObject() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\": \"android\", \"b\": \"banana\"}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("android", reader.nextString());
assertEquals("b", reader.nextName());
assertEquals("banana", reader.nextString());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testReadEmptyObject() throws IOException {
JsonReader reader = new JsonReader(reader("{}"));
reader.beginObject();
assertFalse(reader.hasNext());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipArray() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
assertEquals(123, reader.nextInt());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipArrayAfterPeek() throws Exception {
JsonReader reader = new JsonReader(reader(
"{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(BEGIN_ARRAY, reader.peek());
reader.skipValue();
assertEquals("b", reader.nextName());
assertEquals(123, reader.nextInt());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipTopLevelObject() throws Exception {
JsonReader reader = new JsonReader(reader(
"{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"));
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipObject() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipObjectAfterPeek() throws Exception {
String json = "{" + " \"one\": { \"num\": 1 }"
+ ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}";
JsonReader reader = new JsonReader(reader(json));
reader.beginObject();
assertEquals("one", reader.nextName());
assertEquals(BEGIN_OBJECT, reader.peek());
reader.skipValue();
assertEquals("two", reader.nextName());
assertEquals(BEGIN_OBJECT, reader.peek());
reader.skipValue();
assertEquals("three", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipInteger() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\":123456789,\"b\":-123456789}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipDouble() throws IOException {
JsonReader reader = new JsonReader(reader(
"{\"a\":-123.456e-789,\"b\":123456789.0}"));
reader.beginObject();
assertEquals("a", reader.nextName());
reader.skipValue();
assertEquals("b", reader.nextName());
reader.skipValue();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testHelloWorld() throws IOException {
String json = "{\n" +
" \"hello\": true,\n" +
" \"foo\": [\"world\"]\n" +
"}";
JsonReader reader = new JsonReader(reader(json));
reader.beginObject();
assertEquals("hello", reader.nextName());
assertEquals(true, reader.nextBoolean());
assertEquals("foo", reader.nextName());
reader.beginArray();
assertEquals("world", reader.nextString());
reader.endArray();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testInvalidJsonInput() throws IOException {
String json = "{\n"
+ " \"h\\ello\": true,\n"
+ " \"foo\": [\"world\"]\n"
+ "}";
JsonReader reader = new JsonReader(reader(json));
reader.beginObject();
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testNulls() {
try {
new JsonReader(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testEmptyString() {
try {
new JsonReader(reader("")).beginArray();
fail();
} catch (IOException expected) {
}
try {
new JsonReader(reader("")).beginObject();
fail();
} catch (IOException expected) {
}
}
public void testCharacterUnescaping() throws IOException {
String json = "[\"a\","
+ "\"a\\\"\","
+ "\"\\\"\","
+ "\":\","
+ "\",\","
+ "\"\\b\","
+ "\"\\f\","
+ "\"\\n\","
+ "\"\\r\","
+ "\"\\t\","
+ "\" \","
+ "\"\\\\\","
+ "\"{\","
+ "\"}\","
+ "\"[\","
+ "\"]\","
+ "\"\\u0000\","
+ "\"\\u0019\","
+ "\"\\u20AC\""
+ "]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals("a", reader.nextString());
assertEquals("a\"", reader.nextString());
assertEquals("\"", reader.nextString());
assertEquals(":", reader.nextString());
assertEquals(",", reader.nextString());
assertEquals("\b", reader.nextString());
assertEquals("\f", reader.nextString());
assertEquals("\n", reader.nextString());
assertEquals("\r", reader.nextString());
assertEquals("\t", reader.nextString());
assertEquals(" ", reader.nextString());
assertEquals("\\", reader.nextString());
assertEquals("{", reader.nextString());
assertEquals("}", reader.nextString());
assertEquals("[", reader.nextString());
assertEquals("]", reader.nextString());
assertEquals("\0", reader.nextString());
assertEquals("\u0019", reader.nextString());
assertEquals("\u20AC", reader.nextString());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testUnescapingInvalidCharacters() throws IOException {
String json = "[\"\\u000g\"]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (NumberFormatException expected) {
}
}
public void testUnescapingTruncatedCharacters() throws IOException {
String json = "[\"\\u000";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testUnescapingTruncatedSequence() throws IOException {
String json = "[\"\\";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testIntegersWithFractionalPartSpecified() throws IOException {
JsonReader reader = new JsonReader(reader("[1.0,1.0,1.0]"));
reader.beginArray();
assertEquals(1.0, reader.nextDouble());
assertEquals(1, reader.nextInt());
assertEquals(1L, reader.nextLong());
}
public void testDoubles() throws IOException {
String json = "[-0.0,"
+ "1.0,"
+ "1.7976931348623157E308,"
+ "4.9E-324,"
+ "0.0,"
+ "-0.5,"
+ "2.2250738585072014E-308,"
+ "3.141592653589793,"
+ "2.718281828459045]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(-0.0, reader.nextDouble());
assertEquals(1.0, reader.nextDouble());
assertEquals(1.7976931348623157E308, reader.nextDouble());
assertEquals(4.9E-324, reader.nextDouble());
assertEquals(0.0, reader.nextDouble());
assertEquals(-0.5, reader.nextDouble());
assertEquals(2.2250738585072014E-308, reader.nextDouble());
assertEquals(3.141592653589793, reader.nextDouble());
assertEquals(2.718281828459045, reader.nextDouble());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictNonFiniteDoubles() throws IOException {
String json = "[NaN]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextDouble();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testStrictQuotedNonFiniteDoubles() throws IOException {
String json = "[\"NaN\"]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.nextDouble();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLenientNonFiniteDoubles() throws IOException {
String json = "[NaN, -Infinity, Infinity]";
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertTrue(Double.isNaN(reader.nextDouble()));
assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
reader.endArray();
}
public void testLenientQuotedNonFiniteDoubles() throws IOException {
String json = "[\"NaN\", \"-Infinity\", \"Infinity\"]";
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertTrue(Double.isNaN(reader.nextDouble()));
assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble());
assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble());
reader.endArray();
}
public void testStrictNonFiniteDoublesWithSkipValue() throws IOException {
String json = "[NaN]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLongs() throws IOException {
String json = "[0,0,0,"
+ "1,1,1,"
+ "-1,-1,-1,"
+ "-9223372036854775808,"
+ "9223372036854775807]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(0L, reader.nextLong());
assertEquals(0, reader.nextInt());
assertEquals(0.0, reader.nextDouble());
assertEquals(1L, reader.nextLong());
assertEquals(1, reader.nextInt());
assertEquals(1.0, reader.nextDouble());
assertEquals(-1L, reader.nextLong());
assertEquals(-1, reader.nextInt());
assertEquals(-1.0, reader.nextDouble());
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(Long.MIN_VALUE, reader.nextLong());
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(Long.MAX_VALUE, reader.nextLong());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void disabled_testNumberWithOctalPrefix() throws IOException {
String json = "[01]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
try {
reader.nextInt();
fail();
} catch (MalformedJsonException expected) {
}
try {
reader.nextLong();
fail();
} catch (MalformedJsonException expected) {
}
try {
reader.nextDouble();
fail();
} catch (MalformedJsonException expected) {
}
assertEquals("01", reader.nextString());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testBooleans() throws IOException {
JsonReader reader = new JsonReader(reader("[true,false]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(false, reader.nextBoolean());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException {
JsonReader reader = new JsonReader(reader("[truey]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
try {
reader.nextBoolean();
fail();
} catch (IllegalStateException expected) {
}
assertEquals("truey", reader.nextString());
reader.endArray();
}
public void testMalformedNumbers() throws IOException {
assertNotANumber("-");
assertNotANumber(".");
// exponent lacks digit
assertNotANumber("e");
assertNotANumber("0e");
assertNotANumber(".e");
assertNotANumber("0.e");
assertNotANumber("-.0e");
// no integer
assertNotANumber("e1");
assertNotANumber(".e1");
assertNotANumber("-e1");
// trailing characters
assertNotANumber("1x");
assertNotANumber("1.1x");
assertNotANumber("1e1x");
assertNotANumber("1ex");
assertNotANumber("1.1ex");
assertNotANumber("1.1e1x");
// fraction has no digit
assertNotANumber("0.");
assertNotANumber("-0.");
assertNotANumber("0.e1");
assertNotANumber("-0.e1");
// no leading digit
assertNotANumber(".0");
assertNotANumber("-.0");
assertNotANumber(".0e1");
assertNotANumber("-.0e1");
}
private void assertNotANumber(String s) throws IOException {
JsonReader reader = new JsonReader(reader("[" + s + "]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(JsonToken.STRING, reader.peek());
assertEquals(s, reader.nextString());
reader.endArray();
}
public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException {
JsonReader reader = new JsonReader(reader("[12.34e5x]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals("12.34e5x", reader.nextString());
}
public void testPeekLongMinValue() throws IOException {
JsonReader reader = new JsonReader(reader("[-9223372036854775808]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals(-9223372036854775808L, reader.nextLong());
}
public void testPeekLongMaxValue() throws IOException {
JsonReader reader = new JsonReader(reader("[9223372036854775807]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals(9223372036854775807L, reader.nextLong());
}
public void testLongLargerThanMaxLongThatWrapsAround() throws IOException {
JsonReader reader = new JsonReader(reader("[22233720368547758070]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
}
public void testLongLargerThanMinLongThatWrapsAround() throws IOException {
JsonReader reader = new JsonReader(reader("[-22233720368547758070]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
}
/**
* Issue 1053, negative zero.
* @throws Exception
*/
public void testNegativeZero() throws Exception {
JsonReader reader = new JsonReader(reader("[-0]"));
reader.setLenient(false);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
assertEquals("-0", reader.nextString());
}
/**
* This test fails because there's no double for 9223372036854775808, and our
* long parsing uses Double.parseDouble() for fractional values.
*/
public void disabled_testPeekLargerThanLongMaxValue() throws IOException {
JsonReader reader = new JsonReader(reader("[9223372036854775808]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException e) {
}
}
/**
* This test fails because there's no double for -9223372036854775809, and our
* long parsing uses Double.parseDouble() for fractional values.
*/
public void disabled_testPeekLargerThanLongMinValue() throws IOException {
JsonReader reader = new JsonReader(reader("[-9223372036854775809]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(-9223372036854775809d, reader.nextDouble());
}
/**
* This test fails because there's no double for 9223372036854775806, and
* our long parsing uses Double.parseDouble() for fractional values.
*/
public void disabled_testHighPrecisionLong() throws IOException {
String json = "[9223372036854775806.000]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(9223372036854775806L, reader.nextLong());
reader.endArray();
}
public void testPeekMuchLargerThanLongMinValue() throws IOException {
JsonReader reader = new JsonReader(reader("[-92233720368547758080]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(NUMBER, reader.peek());
try {
reader.nextLong();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(-92233720368547758080d, reader.nextDouble());
}
public void testQuotedNumberWithEscape() throws IOException {
JsonReader reader = new JsonReader(reader("[\"12\u00334\"]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
assertEquals(1234, reader.nextInt());
}
public void testMixedCaseLiterals() throws IOException {
JsonReader reader = new JsonReader(reader("[True,TruE,False,FALSE,NULL,nulL]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(true, reader.nextBoolean());
assertEquals(false, reader.nextBoolean());
assertEquals(false, reader.nextBoolean());
reader.nextNull();
reader.nextNull();
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testMissingValue() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testPrematureEndOfInput() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true,"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testPrematurelyClosed() throws IOException {
try {
JsonReader reader = new JsonReader(reader("{\"a\":[]}"));
reader.beginObject();
reader.close();
reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
try {
JsonReader reader = new JsonReader(reader("{\"a\":[]}"));
reader.close();
reader.beginObject();
fail();
} catch (IllegalStateException expected) {
}
try {
JsonReader reader = new JsonReader(reader("{\"a\":true}"));
reader.beginObject();
reader.nextName();
reader.peek();
reader.close();
reader.nextBoolean();
fail();
} catch (IllegalStateException expected) {
}
}
public void testNextFailuresDoNotAdvance() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true}"));
reader.beginObject();
try {
reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
assertEquals("a", reader.nextName());
try {
reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.beginArray();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.endArray();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.beginObject();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.endObject();
fail();
} catch (IllegalStateException expected) {
}
assertEquals(true, reader.nextBoolean());
try {
reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.nextName();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.beginArray();
fail();
} catch (IllegalStateException expected) {
}
try {
reader.endArray();
fail();
} catch (IllegalStateException expected) {
}
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
reader.close();
}
public void testIntegerMismatchFailuresDoNotAdvance() throws IOException {
JsonReader reader = new JsonReader(reader("[1.5]"));
reader.beginArray();
try {
reader.nextInt();
fail();
} catch (NumberFormatException expected) {
}
assertEquals(1.5d, reader.nextDouble());
reader.endArray();
}
public void testStringNullIsNotNull() throws IOException {
JsonReader reader = new JsonReader(reader("[\"null\"]"));
reader.beginArray();
try {
reader.nextNull();
fail();
} catch (IllegalStateException expected) {
}
}
public void testNullLiteralIsNotAString() throws IOException {
JsonReader reader = new JsonReader(reader("[null]"));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IllegalStateException expected) {
}
}
public void testStrictNameValueSeparator() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("{\"a\"=>true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
}
public void testLenientNameValueSeparator() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
reader = new JsonReader(reader("{\"a\"=>true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
}
public void testStrictNameValueSeparatorWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\"=true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("{\"a\"=>true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testCommentsInStringValue() throws Exception {
JsonReader reader = new JsonReader(reader("[\"// comment\"]"));
reader.beginArray();
assertEquals("// comment", reader.nextString());
reader.endArray();
reader = new JsonReader(reader("{\"a\":\"#someComment\"}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("#someComment", reader.nextString());
reader.endObject();
reader = new JsonReader(reader("{\"#//a\":\"#some //Comment\"}"));
reader.beginObject();
assertEquals("#//a", reader.nextName());
assertEquals("#some //Comment", reader.nextString());
reader.endObject();
}
public void testStrictComments() throws IOException {
JsonReader reader = new JsonReader(reader("[// comment \n true]"));
reader.beginArray();
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[# comment \n true]"));
reader.beginArray();
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[/* comment */ true]"));
reader.beginArray();
try {
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
}
public void testLenientComments() throws IOException {
JsonReader reader = new JsonReader(reader("[// comment \n true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader = new JsonReader(reader("[# comment \n true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader = new JsonReader(reader("[/* comment */ true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
}
public void testStrictCommentsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[// comment \n true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[# comment \n true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[/* comment */ true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictUnquotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{a:true}"));
reader.beginObject();
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testLenientUnquotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{a:true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
}
public void testStrictUnquotedNamesWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{a:true}"));
reader.beginObject();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictSingleQuotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{'a':true}"));
reader.beginObject();
try {
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testLenientSingleQuotedNames() throws IOException {
JsonReader reader = new JsonReader(reader("{'a':true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
}
public void testStrictSingleQuotedNamesWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{'a':true}"));
reader.beginObject();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictUnquotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("[a]"));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testStrictUnquotedStringsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[a]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLenientUnquotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("[a]"));
reader.setLenient(true);
reader.beginArray();
assertEquals("a", reader.nextString());
}
public void testStrictSingleQuotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("['a']"));
reader.beginArray();
try {
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testLenientSingleQuotedStrings() throws IOException {
JsonReader reader = new JsonReader(reader("['a']"));
reader.setLenient(true);
reader.beginArray();
assertEquals("a", reader.nextString());
}
public void testStrictSingleQuotedStringsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("['a']"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictSemicolonDelimitedArray() throws IOException {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.beginArray();
try {
reader.nextBoolean();
reader.nextBoolean();
fail();
} catch (IOException expected) {
}
}
public void testLenientSemicolonDelimitedArray() throws IOException {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
assertEquals(true, reader.nextBoolean());
}
public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[true;true]"));
reader.beginArray();
try {
reader.skipValue();
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictSemicolonDelimitedNameValuePair() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.nextBoolean();
reader.nextName();
fail();
} catch (IOException expected) {
}
}
public void testLenientSemicolonDelimitedNameValuePair() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(true, reader.nextBoolean());
assertEquals("b", reader.nextName());
}
public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}"));
reader.beginObject();
assertEquals("a", reader.nextName());
try {
reader.skipValue();
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictUnnecessaryArraySeparators() throws IOException {
JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,true]"));
reader.beginArray();
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[true,]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,]"));
reader.beginArray();
try {
reader.nextNull();
fail();
} catch (IOException expected) {
}
}
public void testLenientUnnecessaryArraySeparators() throws IOException {
JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader.nextNull();
assertEquals(true, reader.nextBoolean());
reader.endArray();
reader = new JsonReader(reader("[,true]"));
reader.setLenient(true);
reader.beginArray();
reader.nextNull();
assertEquals(true, reader.nextBoolean());
reader.endArray();
reader = new JsonReader(reader("[true,]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(true, reader.nextBoolean());
reader.nextNull();
reader.endArray();
reader = new JsonReader(reader("[,]"));
reader.setLenient(true);
reader.beginArray();
reader.nextNull();
reader.nextNull();
reader.endArray();
}
public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[true,,true]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,true]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[true,]"));
reader.beginArray();
assertEquals(true, reader.nextBoolean());
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
reader = new JsonReader(reader("[,]"));
reader.beginArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testStrictMultipleTopLevelValues() throws IOException {
JsonReader reader = new JsonReader(reader("[] []"));
reader.beginArray();
reader.endArray();
try {
reader.peek();
fail();
} catch (IOException expected) {
}
}
public void testLenientMultipleTopLevelValues() throws IOException {
JsonReader reader = new JsonReader(reader("[] true {}"));
reader.setLenient(true);
reader.beginArray();
reader.endArray();
assertEquals(true, reader.nextBoolean());
reader.beginObject();
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("[] []"));
reader.beginArray();
reader.endArray();
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testTopLevelValueTypes() throws IOException {
JsonReader reader1 = new JsonReader(reader("true"));
assertTrue(reader1.nextBoolean());
assertEquals(JsonToken.END_DOCUMENT, reader1.peek());
JsonReader reader2 = new JsonReader(reader("false"));
assertFalse(reader2.nextBoolean());
assertEquals(JsonToken.END_DOCUMENT, reader2.peek());
JsonReader reader3 = new JsonReader(reader("null"));
assertEquals(JsonToken.NULL, reader3.peek());
reader3.nextNull();
assertEquals(JsonToken.END_DOCUMENT, reader3.peek());
JsonReader reader4 = new JsonReader(reader("123"));
assertEquals(123, reader4.nextInt());
assertEquals(JsonToken.END_DOCUMENT, reader4.peek());
JsonReader reader5 = new JsonReader(reader("123.4"));
assertEquals(123.4, reader5.nextDouble());
assertEquals(JsonToken.END_DOCUMENT, reader5.peek());
JsonReader reader6 = new JsonReader(reader("\"a\""));
assertEquals("a", reader6.nextString());
assertEquals(JsonToken.END_DOCUMENT, reader6.peek());
}
public void testTopLevelValueTypeWithSkipValue() throws IOException {
JsonReader reader = new JsonReader(reader("true"));
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictNonExecutePrefix() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
try {
reader.beginArray();
fail();
} catch (IOException expected) {
}
}
public void testStrictNonExecutePrefixWithSkipValue() {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
try {
reader.skipValue();
fail();
} catch (IOException expected) {
}
}
public void testLenientNonExecutePrefix() throws IOException {
JsonReader reader = new JsonReader(reader(")]}'\n []"));
reader.setLenient(true);
reader.beginArray();
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException {
JsonReader reader = new JsonReader(reader("\r\n \t)]}'\n []"));
reader.setLenient(true);
reader.beginArray();
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testLenientPartialNonExecutePrefix() {
JsonReader reader = new JsonReader(reader(")]}' []"));
reader.setLenient(true);
try {
assertEquals(")", reader.nextString());
reader.nextString();
fail();
} catch (IOException expected) {
}
}
public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException {
JsonReader reader = new JsonReader(reader("\ufeff[]"));
reader.beginArray();
reader.endArray();
}
public void testBomForbiddenAsOtherCharacterInDocument() throws IOException {
JsonReader reader = new JsonReader(reader("[\ufeff]"));
reader.beginArray();
try {
reader.endArray();
fail();
} catch (IOException expected) {
}
}
public void testFailWithPosition() throws IOException {
testFailWithPosition("Expected value at line 6 column 5 path $[1]",
"[\n\n\n\n\n\"a\",}]");
}
public void testFailWithPositionGreaterThanBufferSize() throws IOException {
String spaces = repeat(' ', 8192);
testFailWithPosition("Expected value at line 6 column 5 path $[1]",
"[\n\n" + spaces + "\n\n\n\"a\",}]");
}
public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException {
testFailWithPosition("Expected value at line 5 column 6 path $[1]",
"\n// foo\n\n//bar\r\n[\"a\",}");
}
public void testFailWithPositionOverHashEndOfLineComment() throws IOException {
testFailWithPosition("Expected value at line 5 column 6 path $[1]",
"\n# foo\n\n#bar\r\n[\"a\",}");
}
public void testFailWithPositionOverCStyleComment() throws IOException {
testFailWithPosition("Expected value at line 6 column 12 path $[1]",
"\n\n/* foo\n*\n*\r\nbar */[\"a\",}");
}
public void testFailWithPositionOverQuotedString() throws IOException {
testFailWithPosition("Expected value at line 5 column 3 path $[1]",
"[\"foo\nbar\r\nbaz\n\",\n }");
}
public void testFailWithPositionOverUnquotedString() throws IOException {
testFailWithPosition("Expected value at line 5 column 2 path $[1]", "[\n\nabcd\n\n,}");
}
public void testFailWithEscapedNewlineCharacter() throws IOException {
testFailWithPosition("Expected value at line 5 column 3 path $[1]", "[\n\n\"\\\n\n\",}");
}
public void testFailWithPositionIsOffsetByBom() throws IOException {
testFailWithPosition("Expected value at line 1 column 6 path $[1]",
"\ufeff[\"a\",}]");
}
private void testFailWithPosition(String message, String json) throws IOException {
// Validate that it works reading the string normally.
JsonReader reader1 = new JsonReader(reader(json));
reader1.setLenient(true);
reader1.beginArray();
reader1.nextString();
try {
reader1.peek();
fail();
} catch (IOException expected) {
assertEquals(message, expected.getMessage());
}
// Also validate that it works when skipping.
JsonReader reader2 = new JsonReader(reader(json));
reader2.setLenient(true);
reader2.beginArray();
reader2.skipValue();
try {
reader2.peek();
fail();
} catch (IOException expected) {
assertEquals(message, expected.getMessage());
}
}
public void testFailWithPositionDeepPath() throws IOException {
JsonReader reader = new JsonReader(reader("[1,{\"a\":[2,3,}"));
reader.beginArray();
reader.nextInt();
reader.beginObject();
reader.nextName();
reader.beginArray();
reader.nextInt();
reader.nextInt();
try {
reader.peek();
fail();
} catch (IOException expected) {
assertEquals("Expected value at line 1 column 14 path $[1].a[2]", expected.getMessage());
}
}
public void testStrictVeryLongNumber() throws IOException {
JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]"));
reader.beginArray();
try {
assertEquals(1d, reader.nextDouble());
fail();
} catch (MalformedJsonException expected) {
}
}
public void testLenientVeryLongNumber() throws IOException {
JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(JsonToken.STRING, reader.peek());
assertEquals(1d, reader.nextDouble());
reader.endArray();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testVeryLongUnquotedLiteral() throws IOException {
String literal = "a" + repeat('b', 8192) + "c";
JsonReader reader = new JsonReader(reader("[" + literal + "]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(literal, reader.nextString());
reader.endArray();
}
public void testDeeplyNestedArrays() throws IOException {
// this is nested 40 levels deep; Gson is tuned for nesting is 30 levels deep or fewer
JsonReader reader = new JsonReader(reader(
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"));
for (int i = 0; i < 40; i++) {
reader.beginArray();
}
assertEquals("$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]"
+ "[0][0][0][0][0][0][0][0][0][0][0][0][0][0]", reader.getPath());
for (int i = 0; i < 40; i++) {
reader.endArray();
}
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testDeeplyNestedObjects() throws IOException {
// Build a JSON document structured like {"a":{"a":{"a":{"a":true}}}}, but 40 levels deep
String array = "{\"a\":%s}";
String json = "true";
for (int i = 0; i < 40; i++) {
json = String.format(array, json);
}
JsonReader reader = new JsonReader(reader(json));
for (int i = 0; i < 40; i++) {
reader.beginObject();
assertEquals("a", reader.nextName());
}
assertEquals("$.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a"
+ ".a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", reader.getPath());
assertEquals(true, reader.nextBoolean());
for (int i = 0; i < 40; i++) {
reader.endObject();
}
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
// http://code.google.com/p/google-gson/issues/detail?id=409
public void testStringEndingInSlash() throws IOException {
JsonReader reader = new JsonReader(reader("/"));
reader.setLenient(true);
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testDocumentWithCommentEndingInSlash() throws IOException {
JsonReader reader = new JsonReader(reader("/* foo *//"));
reader.setLenient(true);
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testStringWithLeadingSlash() throws IOException {
JsonReader reader = new JsonReader(reader("/x"));
reader.setLenient(true);
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testUnterminatedObject() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":\"android\"x"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("android", reader.nextString());
try {
reader.peek();
fail();
} catch (MalformedJsonException expected) {
}
}
public void testVeryLongQuotedString() throws IOException {
char[] stringChars = new char[1024 * 16];
Arrays.fill(stringChars, 'x');
String string = new String(stringChars);
String json = "[\"" + string + "\"]";
JsonReader reader = new JsonReader(reader(json));
reader.beginArray();
assertEquals(string, reader.nextString());
reader.endArray();
}
public void testVeryLongUnquotedString() throws IOException {
char[] stringChars = new char[1024 * 16];
Arrays.fill(stringChars, 'x');
String string = new String(stringChars);
String json = "[" + string + "]";
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertEquals(string, reader.nextString());
reader.endArray();
}
public void testVeryLongUnterminatedString() throws IOException {
char[] stringChars = new char[1024 * 16];
Arrays.fill(stringChars, 'x');
String string = new String(stringChars);
String json = "[" + string;
JsonReader reader = new JsonReader(reader(json));
reader.setLenient(true);
reader.beginArray();
assertEquals(string, reader.nextString());
try {
reader.peek();
fail();
} catch (EOFException expected) {
}
}
public void testSkipVeryLongUnquotedString() throws IOException {
JsonReader reader = new JsonReader(reader("[" + repeat('x', 8192) + "]"));
reader.setLenient(true);
reader.beginArray();
reader.skipValue();
reader.endArray();
}
public void testSkipTopLevelUnquotedString() throws IOException {
JsonReader reader = new JsonReader(reader(repeat('x', 8192)));
reader.setLenient(true);
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testSkipVeryLongQuotedString() throws IOException {
JsonReader reader = new JsonReader(reader("[\"" + repeat('x', 8192) + "\"]"));
reader.beginArray();
reader.skipValue();
reader.endArray();
}
public void testSkipTopLevelQuotedString() throws IOException {
JsonReader reader = new JsonReader(reader("\"" + repeat('x', 8192) + "\""));
reader.setLenient(true);
reader.skipValue();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStringAsNumberWithTruncatedExponent() throws IOException {
JsonReader reader = new JsonReader(reader("[123e]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
}
public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException {
JsonReader reader = new JsonReader(reader("[123e4b]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
}
public void testStringAsNumberWithNonDigitExponent() throws IOException {
JsonReader reader = new JsonReader(reader("[123eb]"));
reader.setLenient(true);
reader.beginArray();
assertEquals(STRING, reader.peek());
}
public void testEmptyStringName() throws IOException {
JsonReader reader = new JsonReader(reader("{\"\":true}"));
reader.setLenient(true);
assertEquals(BEGIN_OBJECT, reader.peek());
reader.beginObject();
assertEquals(NAME, reader.peek());
assertEquals("", reader.nextName());
assertEquals(JsonToken.BOOLEAN, reader.peek());
assertEquals(true, reader.nextBoolean());
assertEquals(JsonToken.END_OBJECT, reader.peek());
reader.endObject();
assertEquals(JsonToken.END_DOCUMENT, reader.peek());
}
public void testStrictExtraCommasInMaps() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}"));
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("b", reader.nextString());
try {
reader.peek();
fail();
} catch (IOException expected) {
}
}
public void testLenientExtraCommasInMaps() throws IOException {
JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}"));
reader.setLenient(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals("b", reader.nextString());
try {
reader.peek();
fail();
} catch (IOException expected) {
}
}
private String repeat(char c, int count) {
char[] array = new char[count];
Arrays.fill(array, c);
return new String(array);
}
public void testMalformedDocuments() throws IOException {
assertDocument("{]", BEGIN_OBJECT, IOException.class);
assertDocument("{,", BEGIN_OBJECT, IOException.class);
assertDocument("{{", BEGIN_OBJECT, IOException.class);
assertDocument("{[", BEGIN_OBJECT, IOException.class);
assertDocument("{:", BEGIN_OBJECT, IOException.class);
assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\":}", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"::", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\":,", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"=}", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"=>}", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\"=>\"string\":", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\"=", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\"=>", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\"=>\"string\",\"name\"", BEGIN_OBJECT, NAME, STRING, NAME);
assertDocument("[}", BEGIN_ARRAY, IOException.class);
assertDocument("[,]", BEGIN_ARRAY, NULL, NULL, END_ARRAY);
assertDocument("{", BEGIN_OBJECT, IOException.class);
assertDocument("{\"name\"", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{'name'", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{'name',", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("{name", BEGIN_OBJECT, NAME, IOException.class);
assertDocument("[", BEGIN_ARRAY, IOException.class);
assertDocument("[string", BEGIN_ARRAY, STRING, IOException.class);
assertDocument("[\"string\"", BEGIN_ARRAY, STRING, IOException.class);
assertDocument("['string'", BEGIN_ARRAY, STRING, IOException.class);
assertDocument("[123", BEGIN_ARRAY, NUMBER, IOException.class);
assertDocument("[123,", BEGIN_ARRAY, NUMBER, IOException.class);
assertDocument("{\"name\":123", BEGIN_OBJECT, NAME, NUMBER, IOException.class);
assertDocument("{\"name\":123,", BEGIN_OBJECT, NAME, NUMBER, IOException.class);
assertDocument("{\"name\":\"string\"", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":'string'", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":'string',", BEGIN_OBJECT, NAME, STRING, IOException.class);
assertDocument("{\"name\":false", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class);
assertDocument("{\"name\":false,,", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class);
}
/**
* This test behave slightly differently in Gson 2.2 and earlier. It fails
* during peek rather than during nextString().
*/
public void testUnterminatedStringFailure() throws IOException {
JsonReader reader = new JsonReader(reader("[\"string"));
reader.setLenient(true);
reader.beginArray();
assertEquals(JsonToken.STRING, reader.peek());
try {
reader.nextString();
fail();
} catch (MalformedJsonException expected) {
}
}
private void assertDocument(String document, Object... expectations) throws IOException {
JsonReader reader = new JsonReader(reader(document));
reader.setLenient(true);
for (Object expectation : expectations) {
if (expectation == BEGIN_OBJECT) {
reader.beginObject();
} else if (expectation == BEGIN_ARRAY) {
reader.beginArray();
} else if (expectation == END_OBJECT) {
reader.endObject();
} else if (expectation == END_ARRAY) {
reader.endArray();
} else if (expectation == NAME) {
assertEquals("name", reader.nextName());
} else if (expectation == BOOLEAN) {
assertEquals(false, reader.nextBoolean());
} else if (expectation == STRING) {
assertEquals("string", reader.nextString());
} else if (expectation == NUMBER) {
assertEquals(123, reader.nextInt());
} else if (expectation == NULL) {
reader.nextNull();
} else if (expectation == IOException.class) {
try {
reader.peek();
fail();
} catch (IOException expected) {
}
} else {
throw new AssertionError();
}
}
}
/**
* Returns a reader that returns one character at a time.
*/
private Reader reader(final String s) {
/* if (true) */ return new StringReader(s);
/* return new Reader() {
int position = 0;
@Override public int read(char[] buffer, int offset, int count) throws IOException {
if (position == s.length()) {
return -1;
} else if (count > 0) {
buffer[offset] = s.charAt(position++);
return 1;
} else {
throw new IllegalArgumentException();
}
}
@Override public void close() throws IOException {
}
}; */
}
} |
|
public void testTextExtents() {
parse("@return {@code foo} bar \n * baz. */",
true, "Bad type annotation. type not recognized due to syntax error");
} | com.google.javascript.jscomp.parsing.JsDocInfoParserTest::testTextExtents | test/com/google/javascript/jscomp/parsing/JsDocInfoParserTest.java | 2,757 | test/com/google/javascript/jscomp/parsing/JsDocInfoParserTest.java | testTextExtents | /*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.parsing;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.parsing.Config.LanguageMode;
import com.google.javascript.jscomp.testing.TestErrorReporter;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.head.CompilerEnvirons;
import com.google.javascript.rhino.head.Parser;
import com.google.javascript.rhino.head.Token.CommentType;
import com.google.javascript.rhino.head.ast.AstRoot;
import com.google.javascript.rhino.head.ast.Comment;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.SimpleSourceFile;
import com.google.javascript.rhino.jstype.StaticSourceFile;
import com.google.javascript.rhino.testing.BaseJSTypeTestCase;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class JsDocInfoParserTest extends BaseJSTypeTestCase {
private Set<String> extraAnnotations;
private Set<String> extraSuppressions;
private Node.FileLevelJsDocBuilder fileLevelJsDocBuilder = null;
@Override
public void setUp() throws Exception {
super.setUp();
extraAnnotations =
Sets.newHashSet(
ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false)
.annotationNames.keySet());
extraSuppressions =
Sets.newHashSet(
ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false)
.suppressionNames);
extraSuppressions.add("x");
extraSuppressions.add("y");
extraSuppressions.add("z");
}
public void testParseTypeViaStatic1() throws Exception {
Node typeNode = parseType("null");
assertTypeEquals(NULL_TYPE, typeNode);
}
public void testParseTypeViaStatic2() throws Exception {
Node typeNode = parseType("string");
assertTypeEquals(STRING_TYPE, typeNode);
}
public void testParseTypeViaStatic3() throws Exception {
Node typeNode = parseType("!Date");
assertTypeEquals(DATE_TYPE, typeNode);
}
public void testParseTypeViaStatic4() throws Exception {
Node typeNode = parseType("boolean|string");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, STRING_TYPE), typeNode);
}
public void testParseInvalidTypeViaStatic() throws Exception {
Node typeNode = parseType("sometype.<anothertype");
assertNull(typeNode);
}
public void testParseInvalidTypeViaStatic2() throws Exception {
Node typeNode = parseType("");
assertNull(typeNode);
}
public void testParseNamedType1() throws Exception {
assertNull(parse("@type null", "Unexpected end of file"));
}
public void testParseNamedType2() throws Exception {
JSDocInfo info = parse("@type null*/");
assertTypeEquals(NULL_TYPE, info.getType());
}
public void testParseNamedType3() throws Exception {
JSDocInfo info = parse("@type {string}*/");
assertTypeEquals(STRING_TYPE, info.getType());
}
public void testParseNamedType4() throws Exception {
// Multi-line @type.
JSDocInfo info = parse("@type \n {string}*/");
assertTypeEquals(STRING_TYPE, info.getType());
}
public void testParseNamedType5() throws Exception {
JSDocInfo info = parse("@type {!goog.\nBar}*/");
assertTypeEquals(
registry.createNamedType("goog.Bar", null, -1, -1),
info.getType());
}
public void testParseNamedType6() throws Exception {
JSDocInfo info = parse("@type {!goog.\n * Bar.\n * Baz}*/");
assertTypeEquals(
registry.createNamedType("goog.Bar.Baz", null, -1, -1),
info.getType());
}
public void testParseNamedTypeError1() throws Exception {
// To avoid parsing ambiguities, type names must end in a '.' to
// get the continuation behavior.
parse("@type {!goog\n * .Bar} */",
"Bad type annotation. expected closing }");
}
public void testParseNamedTypeError2() throws Exception {
parse("@type {!goog.\n * Bar\n * .Baz} */",
"Bad type annotation. expected closing }");
}
public void testTypedefType1() throws Exception {
JSDocInfo info = parse("@typedef string */");
assertTrue(info.hasTypedefType());
assertTypeEquals(STRING_TYPE, info.getTypedefType());
}
public void testTypedefType2() throws Exception {
JSDocInfo info = parse("@typedef \n {string}*/");
assertTrue(info.hasTypedefType());
assertTypeEquals(STRING_TYPE, info.getTypedefType());
}
public void testTypedefType3() throws Exception {
JSDocInfo info = parse("@typedef \n {(string|number)}*/");
assertTrue(info.hasTypedefType());
assertTypeEquals(
createUnionType(NUMBER_TYPE, STRING_TYPE),
info.getTypedefType());
}
public void testParseStringType1() throws Exception {
assertTypeEquals(STRING_TYPE, parse("@type {string}*/").getType());
}
public void testParseStringType2() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE, parse("@type {!String}*/").getType());
}
public void testParseBooleanType1() throws Exception {
assertTypeEquals(BOOLEAN_TYPE, parse("@type {boolean}*/").getType());
}
public void testParseBooleanType2() throws Exception {
assertTypeEquals(
BOOLEAN_OBJECT_TYPE, parse("@type {!Boolean}*/").getType());
}
public void testParseNumberType1() throws Exception {
assertTypeEquals(NUMBER_TYPE, parse("@type {number}*/").getType());
}
public void testParseNumberType2() throws Exception {
assertTypeEquals(NUMBER_OBJECT_TYPE, parse("@type {!Number}*/").getType());
}
public void testParseNullType1() throws Exception {
assertTypeEquals(NULL_TYPE, parse("@type {null}*/").getType());
}
public void testParseNullType2() throws Exception {
assertTypeEquals(NULL_TYPE, parse("@type {Null}*/").getType());
}
public void testParseAllType1() throws Exception {
testParseType("*");
}
public void testParseAllType2() throws Exception {
testParseType("*?", "*");
}
public void testParseObjectType() throws Exception {
assertTypeEquals(OBJECT_TYPE, parse("@type {!Object}*/").getType());
}
public void testParseDateType() throws Exception {
assertTypeEquals(DATE_TYPE, parse("@type {!Date}*/").getType());
}
public void testParseFunctionType() throws Exception {
assertTypeEquals(
createNullableType(U2U_CONSTRUCTOR_TYPE),
parse("@type {Function}*/").getType());
}
public void testParseRegExpType() throws Exception {
assertTypeEquals(REGEXP_TYPE, parse("@type {!RegExp}*/").getType());
}
public void testParseErrorTypes() throws Exception {
assertTypeEquals(ERROR_TYPE, parse("@type {!Error}*/").getType());
assertTypeEquals(URI_ERROR_TYPE, parse("@type {!URIError}*/").getType());
assertTypeEquals(EVAL_ERROR_TYPE, parse("@type {!EvalError}*/").getType());
assertTypeEquals(REFERENCE_ERROR_TYPE,
parse("@type {!ReferenceError}*/").getType());
assertTypeEquals(TYPE_ERROR_TYPE, parse("@type {!TypeError}*/").getType());
assertTypeEquals(
RANGE_ERROR_TYPE, parse("@type {!RangeError}*/").getType());
assertTypeEquals(
SYNTAX_ERROR_TYPE, parse("@type {!SyntaxError}*/").getType());
}
public void testParseUndefinedType1() throws Exception {
assertTypeEquals(VOID_TYPE, parse("@type {undefined}*/").getType());
}
public void testParseUndefinedType2() throws Exception {
assertTypeEquals(VOID_TYPE, parse("@type {Undefined}*/").getType());
}
public void testParseUndefinedType3() throws Exception {
assertTypeEquals(VOID_TYPE, parse("@type {void}*/").getType());
}
public void testParseTemplatizedType1() throws Exception {
JSDocInfo info = parse("@type !Array.<number> */");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType());
}
public void testParseTemplatizedType2() throws Exception {
JSDocInfo info = parse("@type {!Array.<number>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType());
}
public void testParseTemplatizedType3() throws Exception {
JSDocInfo info = parse("@type !Array.<(number,null)>*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType4() throws Exception {
JSDocInfo info = parse("@type {!Array.<(number|null)>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType5() throws Exception {
JSDocInfo info = parse("@type {!Array.<Array.<(number|null)>>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(NULL_TYPE,
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE)))),
info.getType());
}
public void testParseTemplatizedType6() throws Exception {
JSDocInfo info = parse("@type {!Array.<!Array.<(number|null)>>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE))),
info.getType());
}
public void testParseTemplatizedType7() throws Exception {
JSDocInfo info = parse("@type {!Array.<function():Date>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
registry.createFunctionType(
createUnionType(DATE_TYPE, NULL_TYPE))),
info.getType());
}
public void testParseTemplatizedType8() throws Exception {
JSDocInfo info = parse("@type {!Array.<function():!Date>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
registry.createFunctionType(DATE_TYPE)),
info.getType());
}
public void testParseTemplatizedType9() throws Exception {
JSDocInfo info = parse("@type {!Array.<Date|number>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(DATE_TYPE, NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType10() throws Exception {
JSDocInfo info = parse("@type {!Array.<Date|number|boolean>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(DATE_TYPE, NUMBER_TYPE, BOOLEAN_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType11() throws Exception {
JSDocInfo info = parse("@type {!Object.<number>}*/");
assertTypeEquals(
createTemplatizedType(
OBJECT_TYPE, ImmutableList.of(UNKNOWN_TYPE, NUMBER_TYPE)),
info.getType());
assertTemplatizedTypeEquals(
JSTypeRegistry.OBJECT_ELEMENT_TEMPLATE, NUMBER_TYPE, info.getType());
}
public void testParseTemplatizedType12() throws Exception {
JSDocInfo info = parse("@type {!Object.<string,number>}*/");
assertTypeEquals(
createTemplatizedType(
OBJECT_TYPE, ImmutableList.of(STRING_TYPE, NUMBER_TYPE)),
info.getType());
assertTemplatizedTypeEquals(
JSTypeRegistry.OBJECT_ELEMENT_TEMPLATE, NUMBER_TYPE, info.getType());
assertTemplatizedTypeEquals(
JSTypeRegistry.OBJECT_INDEX_TEMPLATE, STRING_TYPE, info.getType());
}
public void testParseTemplatizedType13() throws Exception {
JSDocInfo info = parse("@type !Array.<?> */");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, UNKNOWN_TYPE), info.getType());
}
public void testParseUnionType1() throws Exception {
JSDocInfo info = parse("@type {(boolean,null)}*/");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType());
}
public void testParseUnionType2() throws Exception {
JSDocInfo info = parse("@type {boolean|null}*/");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType());
}
public void testParseUnionType3() throws Exception {
JSDocInfo info = parse("@type {boolean||null}*/");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType());
}
public void testParseUnionType4() throws Exception {
JSDocInfo info = parse("@type {(Array.<boolean>,null)}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType5() throws Exception {
JSDocInfo info = parse("@type {(null, Array.<boolean>)}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType6() throws Exception {
JSDocInfo info = parse("@type {Array.<boolean>|null}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType7() throws Exception {
JSDocInfo info = parse("@type {null|Array.<boolean>}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType8() throws Exception {
JSDocInfo info = parse("@type {null||Array.<boolean>}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType9() throws Exception {
JSDocInfo info = parse("@type {Array.<boolean>||null}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType10() throws Exception {
parse("@type {string|}*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnionType11() throws Exception {
parse("@type {(string,)}*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnionType12() throws Exception {
parse("@type {()}*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnionType13() throws Exception {
testParseType(
"(function(this:Date),function(this:String):number)",
"Function");
}
public void testParseUnionType14() throws Exception {
testParseType(
"(function(...[function(number):boolean]):number)|" +
"function(this:String, string):number",
"Function");
}
public void testParseUnionType15() throws Exception {
testParseType("*|number", "*");
}
public void testParseUnionType16() throws Exception {
testParseType("number|*", "*");
}
public void testParseUnionType17() throws Exception {
testParseType("string|number|*", "*");
}
public void testParseUnionType18() throws Exception {
testParseType("(string,*,number)", "*");
}
public void testParseUnionTypeError1() throws Exception {
parse("@type {(string,|number)} */",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnknownType1() throws Exception {
testParseType("?");
}
public void testParseUnknownType2() throws Exception {
testParseType("(?|number)", "?");
}
public void testParseUnknownType3() throws Exception {
testParseType("(number|?)", "?");
}
public void testParseFunctionalType1() throws Exception {
testParseType("function (): number");
}
public void testParseFunctionalType2() throws Exception {
testParseType("function (number, string): boolean");
}
public void testParseFunctionalType3() throws Exception {
testParseType(
"function(this:Array)", "function (this:Array): ?");
}
public void testParseFunctionalType4() throws Exception {
testParseType("function (...[number]): boolean");
}
public void testParseFunctionalType5() throws Exception {
testParseType("function (number, ...[string]): boolean");
}
public void testParseFunctionalType6() throws Exception {
testParseType(
"function (this:Date, number): (boolean|number|string)");
}
public void testParseFunctionalType7() throws Exception {
testParseType("function()", "function (): ?");
}
public void testParseFunctionalType8() throws Exception {
testParseType(
"function(this:Array,...[boolean])",
"function (this:Array, ...[boolean]): ?");
}
public void testParseFunctionalType9() throws Exception {
testParseType(
"function(this:Array,!Date,...[boolean?])",
"function (this:Array, Date, ...[(boolean|null)]): ?");
}
public void testParseFunctionalType10() throws Exception {
testParseType(
"function(...[Object?]):boolean?",
"function (...[(Object|null)]): (boolean|null)");
}
public void testParseFunctionalType11() throws Exception {
testParseType(
"function(...[[number]]):[number?]",
"function (...[Array]): Array");
}
public void testParseFunctionalType12() throws Exception {
testParseType(
"function(...)",
"function (...[?]): ?");
}
public void testParseFunctionalType13() throws Exception {
testParseType(
"function(...): void",
"function (...[?]): undefined");
}
public void testParseFunctionalType14() throws Exception {
testParseType("function (*, string, number): boolean");
}
public void testParseFunctionalType15() throws Exception {
testParseType("function (?, string): boolean");
}
public void testParseFunctionalType16() throws Exception {
testParseType("function (string, ?): ?");
}
public void testParseFunctionalType17() throws Exception {
testParseType("(function (?): ?|number)");
}
public void testParseFunctionalType18() throws Exception {
testParseType("function (?): (?|number)", "function (?): ?");
}
public void testParseFunctionalType19() throws Exception {
testParseType(
"function(...[?]): void",
"function (...[?]): undefined");
}
public void testStructuralConstructor() throws Exception {
JSType type = testParseType(
"function (new:Object)", "function (new:Object): ?");
assertTrue(type.isConstructor());
assertFalse(type.isNominalConstructor());
}
public void testNominalConstructor() throws Exception {
ObjectType type = testParseType("Array", "(Array|null)").dereference();
assertTrue(type.getConstructor().isNominalConstructor());
}
public void testBug1419535() throws Exception {
parse("@type {function(Object, string, *)?} */");
parse("@type {function(Object, string, *)|null} */");
}
public void testIssue477() throws Exception {
parse("@type function */",
"Bad type annotation. missing opening (");
}
public void testMalformedThisAnnotation() throws Exception {
parse("@this */",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseFunctionalTypeError1() throws Exception {
parse("@type {function number):string}*/",
"Bad type annotation. missing opening (");
}
public void testParseFunctionalTypeError2() throws Exception {
parse("@type {function( number}*/",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError3() throws Exception {
parse("@type {function(...[number], string)}*/",
"Bad type annotation. variable length argument must be last");
}
public void testParseFunctionalTypeError4() throws Exception {
parse("@type {function(string, ...[number], boolean):string}*/",
"Bad type annotation. variable length argument must be last");
}
public void testParseFunctionalTypeError5() throws Exception {
parse("@type {function (thi:Array)}*/",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError6() throws Exception {
resolve(parse("@type {function (this:number)}*/").getType(),
"this type must be an object type");
}
public void testParseFunctionalTypeError7() throws Exception {
parse("@type {function(...[number)}*/",
"Bad type annotation. missing closing ]");
}
public void testParseFunctionalTypeError8() throws Exception {
parse("@type {function(...number])}*/",
"Bad type annotation. missing opening [");
}
public void testParseFunctionalTypeError9() throws Exception {
parse("@type {function (new:Array, this:Object)} */",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError10() throws Exception {
parse("@type {function (this:Array, new:Object)} */",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError11() throws Exception {
parse("@type {function (Array, new:Object)} */",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError12() throws Exception {
resolve(parse("@type {function (new:number)}*/").getType(),
"constructed type must be an object type");
}
public void testParseArrayType1() throws Exception {
testParseType("[number]", "Array");
}
public void testParseArrayType2() throws Exception {
testParseType("[(number,boolean,[Object?])]", "Array");
}
public void testParseArrayType3() throws Exception {
testParseType("[[number],[string]]?", "(Array|null)");
}
public void testParseArrayTypeError1() throws Exception {
parse("@type {[number}*/",
"Bad type annotation. missing closing ]");
}
public void testParseArrayTypeError2() throws Exception {
parse("@type {number]}*/",
"Bad type annotation. expected closing }");
}
public void testParseArrayTypeError3() throws Exception {
parse("@type {[(number,boolean,Object?])]}*/",
"Bad type annotation. missing closing )");
}
public void testParseArrayTypeError4() throws Exception {
parse("@type {(number,boolean,[Object?)]}*/",
"Bad type annotation. missing closing ]");
}
private JSType testParseType(String type) throws Exception {
return testParseType(type, type);
}
private JSType testParseType(
String type, String typeExpected) throws Exception {
JSDocInfo info = parse("@type {" + type + "}*/");
assertNotNull(info);
assertTrue(info.hasType());
JSType actual = resolve(info.getType());
assertEquals(typeExpected, actual.toString());
return actual;
}
public void testParseNullableModifiers1() throws Exception {
JSDocInfo info = parse("@type {string?}*/");
assertTypeEquals(createNullableType(STRING_TYPE), info.getType());
}
public void testParseNullableModifiers2() throws Exception {
JSDocInfo info = parse("@type {!Array.<string?>}*/");
assertTypeEquals(
createTemplatizedType(
ARRAY_TYPE, createUnionType(STRING_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseNullableModifiers3() throws Exception {
JSDocInfo info = parse("@type {Array.<boolean>?}*/");
assertTypeEquals(
createNullableType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers4() throws Exception {
JSDocInfo info = parse("@type {(string,boolean)?}*/");
assertTypeEquals(
createNullableType(createUnionType(STRING_TYPE, BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers5() throws Exception {
JSDocInfo info = parse("@type {(string?,boolean)}*/");
assertTypeEquals(
createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE),
info.getType());
}
public void testParseNullableModifiers6() throws Exception {
JSDocInfo info = parse("@type {(string,boolean?)}*/");
assertTypeEquals(
createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers7() throws Exception {
JSDocInfo info = parse("@type {string?|boolean}*/");
assertTypeEquals(
createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE),
info.getType());
}
public void testParseNullableModifiers8() throws Exception {
JSDocInfo info = parse("@type {string|boolean?}*/");
assertTypeEquals(
createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers9() throws Exception {
JSDocInfo info = parse("@type {foo.Hello.World?}*/");
assertTypeEquals(
createNullableType(
registry.createNamedType(
"foo.Hello.World", null, -1, -1)),
info.getType());
}
public void testParseOptionalModifier() throws Exception {
JSDocInfo info = parse("@type {function(number=)}*/");
assertTypeEquals(
registry.createFunctionType(
UNKNOWN_TYPE, registry.createOptionalParameters(NUMBER_TYPE)),
info.getType());
}
public void testParseNewline1() throws Exception {
JSDocInfo info = parse("@type {string\n* }\n*/");
assertTypeEquals(STRING_TYPE, info.getType());
}
public void testParseNewline2() throws Exception {
JSDocInfo info = parse("@type !Array.<\n* number\n* > */");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType());
}
public void testParseNewline3() throws Exception {
JSDocInfo info = parse("@type !Array.<(number,\n* null)>*/");
assertTypeEquals(
createTemplatizedType(
ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseNewline4() throws Exception {
JSDocInfo info = parse("@type !Array.<(number|\n* null)>*/");
assertTypeEquals(
createTemplatizedType(
ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseNewline5() throws Exception {
JSDocInfo info = parse("@type !Array.<function(\n* )\n* :\n* Date>*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
registry.createFunctionType(
createUnionType(DATE_TYPE, NULL_TYPE))),
info.getType());
}
public void testParseReturnType1() throws Exception {
JSDocInfo info =
parse("@return {null|string|Array.<boolean>}*/");
assertTypeEquals(
createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE),
NULL_TYPE, STRING_TYPE),
info.getReturnType());
}
public void testParseReturnType2() throws Exception {
JSDocInfo info =
parse("@returns {null|(string,Array.<boolean>)}*/");
assertTypeEquals(
createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE),
NULL_TYPE, STRING_TYPE),
info.getReturnType());
}
public void testParseReturnType3() throws Exception {
JSDocInfo info =
parse("@return {((null||Array.<boolean>,string),boolean)}*/");
assertTypeEquals(
createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE),
NULL_TYPE, STRING_TYPE, BOOLEAN_TYPE),
info.getReturnType());
}
public void testParseThisType1() throws Exception {
JSDocInfo info =
parse("@this {goog.foo.Bar}*/");
assertTypeEquals(
registry.createNamedType("goog.foo.Bar", null, -1, -1),
info.getThisType());
}
public void testParseThisType2() throws Exception {
JSDocInfo info =
parse("@this goog.foo.Bar*/");
assertTypeEquals(
registry.createNamedType("goog.foo.Bar", null, -1, -1),
info.getThisType());
}
public void testParseThisType3() throws Exception {
parse("@type {number}\n@this goog.foo.Bar*/",
"Bad type annotation. type annotation incompatible " +
"with other annotations");
}
public void testParseThisType4() throws Exception {
resolve(parse("@this number*/").getThisType(),
"@this must specify an object type");
}
public void testParseThisType5() throws Exception {
parse("@this {Date|Error}*/");
}
public void testParseThisType6() throws Exception {
resolve(parse("@this {Date|number}*/").getThisType(),
"@this must specify an object type");
}
public void testParseParam1() throws Exception {
JSDocInfo info = parse("@param {number} index*/");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam2() throws Exception {
JSDocInfo info = parse("@param index*/");
assertEquals(1, info.getParameterCount());
assertEquals(null, info.getParameterType("index"));
}
public void testParseParam3() throws Exception {
JSDocInfo info = parse("@param {number} index useful comments*/");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam4() throws Exception {
JSDocInfo info = parse("@param index useful comments*/");
assertEquals(1, info.getParameterCount());
assertEquals(null, info.getParameterType("index"));
}
public void testParseParam5() throws Exception {
// Test for multi-line @param.
JSDocInfo info = parse("@param {number} \n index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam6() throws Exception {
// Test for multi-line @param.
JSDocInfo info = parse("@param {number} \n * index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam7() throws Exception {
// Optional @param
JSDocInfo info = parse("@param {number=} index */");
assertTypeEquals(
registry.createOptionalType(NUMBER_TYPE),
info.getParameterType("index"));
}
public void testParseParam8() throws Exception {
// Var args @param
JSDocInfo info = parse("@param {...number} index */");
assertTypeEquals(
registry.createOptionalType(NUMBER_TYPE),
info.getParameterType("index"));
}
public void testParseParam9() throws Exception {
parse("@param {...number=} index */",
"Bad type annotation. expected closing }",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParam10() throws Exception {
parse("@param {...number index */",
"Bad type annotation. expected closing }");
}
public void testParseParam11() throws Exception {
parse("@param {number= index */",
"Bad type annotation. expected closing }");
}
public void testParseParam12() throws Exception {
JSDocInfo info = parse("@param {...number|string} index */");
assertTypeEquals(
registry.createOptionalType(
registry.createUnionType(STRING_TYPE, NUMBER_TYPE)),
info.getParameterType("index"));
}
public void testParseParam13() throws Exception {
JSDocInfo info = parse("@param {...(number|string)} index */");
assertTypeEquals(
registry.createOptionalType(
registry.createUnionType(STRING_TYPE, NUMBER_TYPE)),
info.getParameterType("index"));
}
public void testParseParam14() throws Exception {
JSDocInfo info = parse("@param {string} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("index"));
}
public void testParseParam15() throws Exception {
JSDocInfo info = parse("@param {string} [index */",
"Bad type annotation. missing closing ]");
assertEquals(1, info.getParameterCount());
assertTypeEquals(STRING_TYPE, info.getParameterType("index"));
}
public void testParseParam16() throws Exception {
JSDocInfo info = parse("@param {string} index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(STRING_TYPE, info.getParameterType("index"));
}
public void testParseParam17() throws Exception {
JSDocInfo info = parse("@param {string=} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("index"));
}
public void testParseParam18() throws Exception {
JSDocInfo info = parse("@param {...string} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("index"));
}
public void testParseParam19() throws Exception {
JSDocInfo info = parse("@param {...} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(UNKNOWN_TYPE),
info.getParameterType("index"));
assertTrue(info.getParameterType("index").isVarArgs());
}
public void testParseParam20() throws Exception {
JSDocInfo info = parse("@param {?=} index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
UNKNOWN_TYPE, info.getParameterType("index"));
}
public void testParseParam21() throws Exception {
JSDocInfo info = parse("@param {...?} index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
UNKNOWN_TYPE, info.getParameterType("index"));
assertTrue(info.getParameterType("index").isVarArgs());
}
public void testParseThrows1() throws Exception {
JSDocInfo info = parse("@throws {number} Some number */");
assertEquals(1, info.getThrownTypes().size());
assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0));
}
public void testParseThrows2() throws Exception {
JSDocInfo info = parse("@throws {number} Some number\n "
+ "*@throws {String} A string */");
assertEquals(2, info.getThrownTypes().size());
assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0));
}
public void testParseRecordType1() throws Exception {
parseFull("/** @param {{x}} n\n*/");
}
public void testParseRecordType2() throws Exception {
parseFull("/** @param {{z, y}} n\n*/");
}
public void testParseRecordType3() throws Exception {
parseFull("/** @param {{z, y, x, q, hello, thisisatest}} n\n*/");
}
public void testParseRecordType4() throws Exception {
parseFull("/** @param {{a, 'a', 'hello', 2, this, do, while, for}} n\n*/");
}
public void testParseRecordType5() throws Exception {
parseFull("/** @param {{x : hello}} n\n*/");
}
public void testParseRecordType6() throws Exception {
parseFull("/** @param {{'x' : hello}} n\n*/");
}
public void testParseRecordType7() throws Exception {
parseFull("/** @param {{'x' : !hello}} n\n*/");
}
public void testParseRecordType8() throws Exception {
parseFull("/** @param {{'x' : !hello, y : bar}} n\n*/");
}
public void testParseRecordType9() throws Exception {
parseFull("/** @param {{'x' : !hello, y : {z : bar, 3 : meh}}} n\n*/");
}
public void testParseRecordType10() throws Exception {
parseFull("/** @param {{__proto__ : moo}} n\n*/");
}
public void testParseRecordType11() throws Exception {
parseFull("/** @param {{a : b} n\n*/",
"Bad type annotation. expected closing }");
}
public void testParseRecordType12() throws Exception {
parseFull("/** @param {{!hello : hey}} n\n*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseRecordType13() throws Exception {
parseFull("/** @param {{x}|number} n\n*/");
}
public void testParseRecordType14() throws Exception {
parseFull("/** @param {{x : y}|number} n\n*/");
}
public void testParseRecordType15() throws Exception {
parseFull("/** @param {{'x' : y}|number} n\n*/");
}
public void testParseRecordType16() throws Exception {
parseFull("/** @param {{x, y}|number} n\n*/");
}
public void testParseRecordType17() throws Exception {
parseFull("/** @param {{x : hello, 'y'}|number} n\n*/");
}
public void testParseRecordType18() throws Exception {
parseFull("/** @param {number|{x : hello, 'y'}} n\n*/");
}
public void testParseRecordType19() throws Exception {
parseFull("/** @param {?{x : hello, 'y'}} n\n*/");
}
public void testParseRecordType20() throws Exception {
parseFull("/** @param {!{x : hello, 'y'}} n\n*/");
}
public void testParseRecordType21() throws Exception {
parseFull("/** @param {{x : hello, 'y'}|boolean} n\n*/");
}
public void testParseRecordType22() throws Exception {
parseFull("/** @param {{x : hello, 'y'}|function()} n\n*/");
}
public void testParseRecordType23() throws Exception {
parseFull("/** @param {{x : function(), 'y'}|function()} n\n*/");
}
public void testParseParamError1() throws Exception {
parseFull("/** @param\n*/",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError2() throws Exception {
parseFull("/** @param {Number}*/",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError3() throws Exception {
parseFull("/** @param {Number}\n*/",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError4() throws Exception {
parseFull("/** @param {Number}\n* * num */",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError5() throws Exception {
parse("@param {number} x \n * @param {string} x */",
"Bad type annotation. duplicate variable name \"x\"");
}
public void testParseExtends1() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends String*/").getBaseType());
}
public void testParseExtends2() throws Exception {
JSDocInfo info = parse("@extends com.google.Foo.Bar.Hello.World*/");
assertTypeEquals(
registry.createNamedType(
"com.google.Foo.Bar.Hello.World", null, -1, -1),
info.getBaseType());
}
public void testParseExtendsGenerics() throws Exception {
JSDocInfo info =
parse("@extends com.google.Foo.Bar.Hello.World.<Boolean,number>*/");
assertTypeEquals(
registry.createNamedType(
"com.google.Foo.Bar.Hello.World", null, -1, -1),
info.getBaseType());
}
public void testParseImplementsGenerics() throws Exception {
// For types that are not templatized, <> annotations are ignored.
List<JSTypeExpression> interfaces =
parse("@implements {SomeInterface.<*>} */")
.getImplementedInterfaces();
assertEquals(1, interfaces.size());
assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1),
interfaces.get(0));
}
public void testParseExtends4() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends {String}*/").getBaseType());
}
public void testParseExtends5() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends {String*/",
"Bad type annotation. expected closing }").getBaseType());
}
public void testParseExtends6() throws Exception {
// Multi-line extends
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends \n * {String}*/").getBaseType());
}
public void testParseExtendsInvalidName() throws Exception {
// This looks bad, but for the time being it should be OK, as
// we will not find a type with this name in the JS parsed tree.
// If this is fixed in the future, change this test to check for a
// warning/error message.
assertTypeEquals(
registry.createNamedType("some_++#%$%_UglyString", null, -1, -1),
parse("@extends {some_++#%$%_UglyString} */").getBaseType());
}
public void testParseExtendsNullable1() throws Exception {
parse("@extends {Base?} */", "Bad type annotation. expected closing }");
}
public void testParseExtendsNullable2() throws Exception {
parse("@extends Base? */",
"Bad type annotation. expected end of line or comment");
}
public void testParseEnum1() throws Exception {
assertTypeEquals(NUMBER_TYPE, parse("@enum*/").getEnumParameterType());
}
public void testParseEnum2() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@enum {string}*/").getEnumParameterType());
}
public void testParseEnum3() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@enum string*/").getEnumParameterType());
}
public void testParseDesc1() throws Exception {
assertEquals("hello world!",
parse("@desc hello world!*/").getDescription());
}
public void testParseDesc2() throws Exception {
assertEquals("hello world!",
parse("@desc hello world!\n*/").getDescription());
}
public void testParseDesc3() throws Exception {
assertEquals("", parse("@desc*/").getDescription());
}
public void testParseDesc4() throws Exception {
assertEquals("", parse("@desc\n*/").getDescription());
}
public void testParseDesc5() throws Exception {
assertEquals("hello world!",
parse("@desc hello\nworld!\n*/").getDescription());
}
public void testParseDesc6() throws Exception {
assertEquals("hello world!",
parse("@desc hello\n* world!\n*/").getDescription());
}
public void testParseDesc7() throws Exception {
assertEquals("a b c", parse("@desc a\n\nb\nc*/").getDescription());
}
public void testParseDesc8() throws Exception {
assertEquals("a b c d",
parse("@desc a\n *b\n\n *c\n\nd*/").getDescription());
}
public void testParseDesc9() throws Exception {
String comment = "@desc\n.\n,\n{\n)\n}\n|\n.<\n>\n<\n?\n~\n+\n-\n;\n:\n*/";
assertEquals(". , { ) } | .< > < ? ~ + - ; :",
parse(comment).getDescription());
}
public void testParseDesc10() throws Exception {
String comment = "@desc\n?\n?\n?\n?*/";
assertEquals("? ? ? ?", parse(comment).getDescription());
}
public void testParseDesc11() throws Exception {
String comment = "@desc :[]*/";
assertEquals(":[]", parse(comment).getDescription());
}
public void testParseDesc12() throws Exception {
String comment = "@desc\n:\n[\n]\n...*/";
assertEquals(": [ ] ...", parse(comment).getDescription());
}
public void testParseMeaning1() throws Exception {
assertEquals("tigers",
parse("@meaning tigers */").getMeaning());
}
public void testParseMeaning2() throws Exception {
assertEquals("tigers and lions and bears",
parse("@meaning tigers\n * and lions\n * and bears */").getMeaning());
}
public void testParseMeaning3() throws Exception {
JSDocInfo info =
parse("@meaning tigers\n * and lions\n * @desc and bears */");
assertEquals("tigers and lions", info.getMeaning());
assertEquals("and bears", info.getDescription());
}
public void testParseMeaning4() throws Exception {
parse("@meaning tigers\n * @meaning and lions */",
"extra @meaning tag");
}
public void testParseLends1() throws Exception {
JSDocInfo info = parse("@lends {name} */");
assertEquals("name", info.getLendsName());
}
public void testParseLends2() throws Exception {
JSDocInfo info = parse("@lends foo.bar */");
assertEquals("foo.bar", info.getLendsName());
}
public void testParseLends3() throws Exception {
parse("@lends {name */", "Bad type annotation. expected closing }");
}
public void testParseLends4() throws Exception {
parse("@lends {} */",
"Bad type annotation. missing object name in @lends tag");
}
public void testParseLends5() throws Exception {
parse("@lends } */",
"Bad type annotation. missing object name in @lends tag");
}
public void testParseLends6() throws Exception {
parse("@lends {string} \n * @lends {string} */",
"Bad type annotation. @lends tag incompatible with other annotations");
}
public void testParseLends7() throws Exception {
parse("@type {string} \n * @lends {string} */",
"Bad type annotation. @lends tag incompatible with other annotations");
}
public void testParsePreserve() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@preserve Foo\nBar\n\nBaz*/";
parse(comment);
assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense());
}
public void testParseLicense() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@license Foo\nBar\n\nBaz*/";
parse(comment);
assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense());
}
public void testParseLicenseAscii() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@license Foo\n * Bar\n\n Baz*/";
parse(comment);
assertEquals(" Foo\n Bar\n\n Baz", node.getJSDocInfo().getLicense());
}
public void testParseLicenseWithAnnotation() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@license Foo \n * @author Charlie Brown */";
parse(comment);
assertEquals(" Foo \n @author Charlie Brown ",
node.getJSDocInfo().getLicense());
}
public void testParseDefine1() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@define {string}*/").getType());
}
public void testParseDefine2() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@define {string*/",
"Bad type annotation. expected closing }").getType());
}
public void testParseDefine3() throws Exception {
JSDocInfo info = parse("@define {boolean}*/");
assertTrue(info.isConstant());
assertTrue(info.isDefine());
assertTypeEquals(BOOLEAN_TYPE, info.getType());
}
public void testParseDefine4() throws Exception {
assertTypeEquals(NUMBER_TYPE, parse("@define {number}*/").getType());
}
public void testParseDefine5() throws Exception {
assertTypeEquals(createUnionType(NUMBER_TYPE, BOOLEAN_TYPE),
parse("@define {number|boolean}*/").getType());
}
public void testParseDefineErrors1() throws Exception {
parse("@enum {string}\n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors2() throws Exception {
parse("@define {string}\n @enum {string} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testParseDefineErrors3() throws Exception {
parse("@const\n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors4() throws Exception {
parse("@type string \n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors5() throws Exception {
parse("@return {string}\n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors7() throws Exception {
parse("@define {string}\n @const */", "conflicting @const tag");
}
public void testParseDefineErrors8() throws Exception {
parse("@define {string}\n @type string */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testParseNoCheck1() throws Exception {
assertTrue(parse("@notypecheck*/").isNoTypeCheck());
}
public void testParseNoCheck2() throws Exception {
parse("@notypecheck\n@notypecheck*/", "extra @notypecheck tag");
}
public void testParseOverride1() throws Exception {
assertTrue(parse("@override*/").isOverride());
}
public void testParseOverride2() throws Exception {
parse("@override\n@override*/",
"Bad type annotation. extra @override/@inheritDoc tag");
}
public void testParseInheritDoc1() throws Exception {
assertTrue(parse("@inheritDoc*/").isOverride());
}
public void testParseInheritDoc2() throws Exception {
parse("@override\n@inheritDoc*/",
"Bad type annotation. extra @override/@inheritDoc tag");
}
public void testParseInheritDoc3() throws Exception {
parse("@inheritDoc\n@inheritDoc*/",
"Bad type annotation. extra @override/@inheritDoc tag");
}
public void testParseNoAlias1() throws Exception {
assertTrue(parse("@noalias*/").isNoAlias());
}
public void testParseNoAlias2() throws Exception {
parse("@noalias\n@noalias*/", "extra @noalias tag");
}
public void testParseDeprecated1() throws Exception {
assertTrue(parse("@deprecated*/").isDeprecated());
}
public void testParseDeprecated2() throws Exception {
parse("@deprecated\n@deprecated*/", "extra @deprecated tag");
}
public void testParseExport1() throws Exception {
assertTrue(parse("@export*/").isExport());
}
public void testParseExport2() throws Exception {
parse("@export\n@export*/", "extra @export tag");
}
public void testParseExpose1() throws Exception {
assertTrue(parse("@expose*/").isExpose());
}
public void testParseExpose2() throws Exception {
parse("@expose\n@expose*/", "extra @expose tag");
}
public void testParseExterns1() throws Exception {
assertTrue(parseFileOverview("@externs*/").isExterns());
}
public void testParseExterns2() throws Exception {
parseFileOverview("@externs\n@externs*/", "extra @externs tag");
}
public void testParseExterns3() throws Exception {
assertNull(parse("@externs*/"));
}
public void testParseJavaDispatch1() throws Exception {
assertTrue(parse("@javadispatch*/").isJavaDispatch());
}
public void testParseJavaDispatch2() throws Exception {
parse("@javadispatch\n@javadispatch*/",
"extra @javadispatch tag");
}
public void testParseJavaDispatch3() throws Exception {
assertNull(parseFileOverview("@javadispatch*/"));
}
public void testParseNoCompile1() throws Exception {
assertTrue(parseFileOverview("@nocompile*/").isNoCompile());
}
public void testParseNoCompile2() throws Exception {
parseFileOverview("@nocompile\n@nocompile*/", "extra @nocompile tag");
}
public void testBugAnnotation() throws Exception {
parse("@bug */");
}
public void testDescriptionAnnotation() throws Exception {
parse("@description */");
}
public void testRegression1() throws Exception {
String comment =
" * @param {number} index the index of blah\n" +
" * @return {boolean} whatever\n" +
" * @private\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
assertTypeEquals(BOOLEAN_TYPE, info.getReturnType());
assertEquals(Visibility.PRIVATE, info.getVisibility());
}
public void testRegression2() throws Exception {
String comment =
" * @return {boolean} whatever\n" +
" * but important\n" +
" *\n" +
" * @param {number} index the index of blah\n" +
" * some more comments here\n" +
" * @param name the name of the guy\n" +
" *\n" +
" * @protected\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(2, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
assertEquals(null, info.getParameterType("name"));
assertTypeEquals(BOOLEAN_TYPE, info.getReturnType());
assertEquals(Visibility.PROTECTED, info.getVisibility());
}
public void testRegression3() throws Exception {
String comment =
" * @param mediaTag this specified whether the @media tag is ....\n" +
" *\n" +
"\n" +
"@public\n" +
" *\n" +
"\n" +
" **********\n" +
" * @final\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertEquals(null, info.getParameterType("mediaTag"));
assertEquals(Visibility.PUBLIC, info.getVisibility());
assertTrue(info.isConstant());
}
public void testRegression4() throws Exception {
String comment =
" * @const\n" +
" * @hidden\n" +
" * @preserveTry\n" +
" * @constructor\n" +
" */";
JSDocInfo info = parse(comment);
assertTrue(info.isConstant());
assertFalse(info.isDefine());
assertTrue(info.isConstructor());
assertTrue(info.isHidden());
assertTrue(info.shouldPreserveTry());
}
public void testRegression5() throws Exception {
String comment = "@const\n@enum {string}\n@public*/";
JSDocInfo info = parse(comment);
assertTrue(info.isConstant());
assertFalse(info.isDefine());
assertTypeEquals(STRING_TYPE, info.getEnumParameterType());
assertEquals(Visibility.PUBLIC, info.getVisibility());
}
public void testRegression6() throws Exception {
String comment = "@hidden\n@enum\n@public*/";
JSDocInfo info = parse(comment);
assertTrue(info.isHidden());
assertTypeEquals(NUMBER_TYPE, info.getEnumParameterType());
assertEquals(Visibility.PUBLIC, info.getVisibility());
}
public void testRegression7() throws Exception {
String comment =
" * @desc description here\n" +
" * @param {boolean} flag and some more description\n" +
" * nicely formatted\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag"));
assertEquals("description here", info.getDescription());
}
public void testRegression8() throws Exception {
String comment =
" * @name random tag here\n" +
" * @desc description here\n" +
" *\n" +
" * @param {boolean} flag and some more description\n" +
" * nicely formatted\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag"));
assertEquals("description here", info.getDescription());
}
public void testRegression9() throws Exception {
JSDocInfo jsdoc = parse(
" * @param {string} p0 blah blah blah\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(1, jsdoc.getParameterCount());
assertTypeEquals(STRING_TYPE, jsdoc.getParameterType("p0"));
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression10() throws Exception {
JSDocInfo jsdoc = parse(
" * @param {!String} p0 blah blah blah\n" +
" * @param {boolean} p1 fobar\n" +
" * @return {!Date} jksjkash dshad\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(2, jsdoc.getParameterCount());
assertTypeEquals(STRING_OBJECT_TYPE, jsdoc.getParameterType("p0"));
assertTypeEquals(BOOLEAN_TYPE, jsdoc.getParameterType("p1"));
assertTypeEquals(DATE_TYPE, jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression11() throws Exception {
JSDocInfo jsdoc = parse(
" * @constructor\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression12() throws Exception {
JSDocInfo jsdoc = parse(
" * @extends FooBar\n" +
" */");
assertTypeEquals(registry.createNamedType("FooBar", null, 0, 0),
jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression13() throws Exception {
JSDocInfo jsdoc = parse(
" * @type {!RegExp}\n" +
" * @protected\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertTypeEquals(REGEXP_TYPE, jsdoc.getType());
assertEquals(Visibility.PROTECTED, jsdoc.getVisibility());
}
public void testRegression14() throws Exception {
JSDocInfo jsdoc = parse(
" * @const\n" +
" * @private\n" +
" */");
assertNull(jsdoc.getBaseType());
assertTrue(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.PRIVATE, jsdoc.getVisibility());
}
public void testRegression15() throws Exception {
JSDocInfo jsdoc = parse(
" * @desc Hello,\n" +
" * World!\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertEquals("Hello, World!", jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
assertFalse(jsdoc.isExport());
}
public void testRegression16() throws Exception {
JSDocInfo jsdoc = parse(
" Email is plp@foo.bar\n" +
" @type {string}\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertTypeEquals(STRING_TYPE, jsdoc.getType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression17() throws Exception {
// verifying that if no @desc is present the description is empty
assertNull(parse("@private*/").getDescription());
}
public void testFullRegression1() throws Exception {
parseFull("/** @param (string,number) foo*/function bar(foo){}",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testFullRegression2() throws Exception {
parseFull("/** @param {string,number) foo*/function bar(foo){}",
"Bad type annotation. expected closing }",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testFullRegression3() throws Exception {
parseFull("/**..\n*/");
}
public void testBug907488() throws Exception {
parse("@type {number,null} */",
"Bad type annotation. expected closing }");
}
public void testBug907494() throws Exception {
parse("@return {Object,undefined} */",
"Bad type annotation. expected closing }");
}
public void testBug909468() throws Exception {
parse("@extends {(x)}*/",
"Bad type annotation. expecting a type name");
}
public void testParseInterface() throws Exception {
assertTrue(parse("@interface*/").isInterface());
}
public void testParseImplicitCast1() throws Exception {
assertTrue(parse("@type {string} \n * @implicitCast*/").isImplicitCast());
}
public void testParseImplicitCast2() throws Exception {
assertFalse(parse("@type {string}*/").isImplicitCast());
}
public void testParseDuplicateImplicitCast() throws Exception {
parse("@type {string} \n * @implicitCast \n * @implicitCast*/",
"Bad type annotation. extra @implicitCast tag");
}
public void testParseInterfaceDoubled() throws Exception {
parse(
"* @interface\n" +
"* @interface\n" +
"*/",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testParseImplements() throws Exception {
List<JSTypeExpression> interfaces = parse("@implements {SomeInterface}*/")
.getImplementedInterfaces();
assertEquals(1, interfaces.size());
assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1),
interfaces.get(0));
}
public void testParseImplementsTwo() throws Exception {
List<JSTypeExpression> interfaces =
parse(
"* @implements {SomeInterface1}\n" +
"* @implements {SomeInterface2}\n" +
"*/")
.getImplementedInterfaces();
assertEquals(2, interfaces.size());
assertTypeEquals(registry.createNamedType("SomeInterface1", null, -1, -1),
interfaces.get(0));
assertTypeEquals(registry.createNamedType("SomeInterface2", null, -1, -1),
interfaces.get(1));
}
public void testParseImplementsSameTwice() throws Exception {
parse(
"* @implements {Smth}\n" +
"* @implements {Smth}\n" +
"*/",
"Bad type annotation. duplicate @implements tag");
}
public void testParseImplementsNoName() throws Exception {
parse("* @implements {} */",
"Bad type annotation. expecting a type name");
}
public void testParseImplementsMissingRC() throws Exception {
parse("* @implements {Smth */",
"Bad type annotation. expected closing }");
}
public void testParseImplementsNullable1() throws Exception {
parse("@implements {Base?} */", "Bad type annotation. expected closing }");
}
public void testParseImplementsNullable2() throws Exception {
parse("@implements Base? */",
"Bad type annotation. expected end of line or comment");
}
public void testInterfaceExtends() throws Exception {
JSDocInfo jsdoc = parse(
" * @interface \n" +
" * @extends {Extended} */");
assertTrue(jsdoc.isInterface());
assertEquals(1, jsdoc.getExtendedInterfacesCount());
List<JSTypeExpression> types = jsdoc.getExtendedInterfaces();
assertTypeEquals(registry.createNamedType("Extended", null, -1, -1),
types.get(0));
}
public void testInterfaceMultiExtends1() throws Exception {
JSDocInfo jsdoc = parse(
" * @interface \n" +
" * @extends {Extended1} \n" +
" * @extends {Extended2} */");
assertTrue(jsdoc.isInterface());
assertNull(jsdoc.getBaseType());
assertEquals(2, jsdoc.getExtendedInterfacesCount());
List<JSTypeExpression> types = jsdoc.getExtendedInterfaces();
assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1),
types.get(0));
assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1),
types.get(1));
}
public void testInterfaceMultiExtends2() throws Exception {
JSDocInfo jsdoc = parse(
" * @extends {Extended1} \n" +
" * @interface \n" +
" * @extends {Extended2} \n" +
" * @extends {Extended3} */");
assertTrue(jsdoc.isInterface());
assertNull(jsdoc.getBaseType());
assertEquals(3, jsdoc.getExtendedInterfacesCount());
List<JSTypeExpression> types = jsdoc.getExtendedInterfaces();
assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1),
types.get(0));
assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1),
types.get(1));
assertTypeEquals(registry.createNamedType("Extended3", null, -1, -1),
types.get(2));
}
public void testBadClassMultiExtends() throws Exception {
parse(" * @extends {Extended1} \n" +
" * @constructor \n" +
" * @extends {Extended2} */",
"Bad type annotation. type annotation incompatible with other " +
"annotations");
}
public void testBadExtendsWithNullable() throws Exception {
JSDocInfo jsdoc = parse("@constructor\n * @extends {Object?} */",
"Bad type annotation. expected closing }");
assertTrue(jsdoc.isConstructor());
assertTypeEquals(OBJECT_TYPE, jsdoc.getBaseType());
}
public void testBadImplementsWithNullable() throws Exception {
JSDocInfo jsdoc = parse("@implements {Disposable?}\n * @constructor */",
"Bad type annotation. expected closing }");
assertTrue(jsdoc.isConstructor());
assertTypeEquals(registry.createNamedType("Disposable", null, -1, -1),
jsdoc.getImplementedInterfaces().get(0));
}
public void testBadTypeDefInterfaceAndConstructor1() throws Exception {
JSDocInfo jsdoc = parse("@interface\n@constructor*/",
"Bad type annotation. cannot be both an interface and a constructor");
assertTrue(jsdoc.isInterface());
}
public void testBadTypeDefInterfaceAndConstructor2() throws Exception {
JSDocInfo jsdoc = parse("@constructor\n@interface*/",
"Bad type annotation. cannot be both an interface and a constructor");
assertTrue(jsdoc.isConstructor());
}
public void testDocumentationParameter() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description.*/", true);
assertTrue(jsdoc.hasDescriptionForParameter("number42"));
assertEquals("This is a description.",
jsdoc.getDescriptionForParameter("number42"));
}
public void testMultilineDocumentationParameter() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description"
+ "\n* on multiple \n* lines.*/", true);
assertTrue(jsdoc.hasDescriptionForParameter("number42"));
assertEquals("This is a description on multiple lines.",
jsdoc.getDescriptionForParameter("number42"));
}
public void testDocumentationMultipleParameter() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description."
+ "\n* @param {Integer} number87 This is another description.*/"
, true);
assertTrue(jsdoc.hasDescriptionForParameter("number42"));
assertEquals("This is a description.",
jsdoc.getDescriptionForParameter("number42"));
assertTrue(jsdoc.hasDescriptionForParameter("number87"));
assertEquals("This is another description.",
jsdoc.getDescriptionForParameter("number87"));
}
public void testDocumentationMultipleParameter2() throws Exception {
JSDocInfo jsdoc
= parse("@param {number} delta = 0 results in a redraw\n" +
" != 0 ..... */", true);
assertTrue(jsdoc.hasDescriptionForParameter("delta"));
assertEquals("= 0 results in a redraw != 0 .....",
jsdoc.getDescriptionForParameter("delta"));
}
public void testAuthors() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description."
+ "\n* @param {Integer} number87 This is another description."
+ "\n* @author a@google.com (A Person)"
+ "\n* @author b@google.com (B Person)"
+ "\n* @author c@google.com (C Person)*/"
, true);
Collection<String> authors = jsdoc.getAuthors();
assertTrue(authors != null);
assertTrue(authors.size() == 3);
assertContains(authors, "a@google.com (A Person)");
assertContains(authors, "b@google.com (B Person)");
assertContains(authors, "c@google.com (C Person)");
}
public void testSuppress1() throws Exception {
JSDocInfo info = parse("@suppress {x} */");
assertEquals(Sets.newHashSet("x"), info.getSuppressions());
}
public void testSuppress2() throws Exception {
JSDocInfo info = parse("@suppress {x|y|x|z} */");
assertEquals(Sets.newHashSet("x", "y", "z"), info.getSuppressions());
}
public void testBadSuppress1() throws Exception {
parse("@suppress {} */", "malformed @suppress tag");
}
public void testBadSuppress2() throws Exception {
parse("@suppress {x|} */", "malformed @suppress tag");
}
public void testBadSuppress3() throws Exception {
parse("@suppress {|x} */", "malformed @suppress tag");
}
public void testBadSuppress4() throws Exception {
parse("@suppress {x|y */", "malformed @suppress tag");
}
public void testBadSuppress5() throws Exception {
parse("@suppress {x,y} */", "malformed @suppress tag");
}
public void testBadSuppress6() throws Exception {
parse("@suppress {x} \n * @suppress {y} */", "duplicate @suppress tag");
}
public void testBadSuppress7() throws Exception {
parse("@suppress {impossible} */",
"unknown @suppress parameter: impossible");
}
public void testModifies1() throws Exception {
JSDocInfo info = parse("@modifies {this} */");
assertEquals(Sets.newHashSet("this"), info.getModifies());
}
public void testModifies2() throws Exception {
JSDocInfo info = parse("@modifies {arguments} */");
assertEquals(Sets.newHashSet("arguments"), info.getModifies());
}
public void testModifies3() throws Exception {
JSDocInfo info = parse("@modifies {this|arguments} */");
assertEquals(Sets.newHashSet("this", "arguments"), info.getModifies());
}
public void testModifies4() throws Exception {
JSDocInfo info = parse("@param {*} x\n * @modifies {x} */");
assertEquals(Sets.newHashSet("x"), info.getModifies());
}
public void testModifies5() throws Exception {
JSDocInfo info = parse(
"@param {*} x\n"
+ " * @param {*} y\n"
+ " * @modifies {x} */");
assertEquals(Sets.newHashSet("x"), info.getModifies());
}
public void testModifies6() throws Exception {
JSDocInfo info = parse(
"@param {*} x\n"
+ " * @param {*} y\n"
+ " * @modifies {x|y} */");
assertEquals(Sets.newHashSet("x", "y"), info.getModifies());
}
public void testBadModifies1() throws Exception {
parse("@modifies {} */", "malformed @modifies tag");
}
public void testBadModifies2() throws Exception {
parse("@modifies {this|} */", "malformed @modifies tag");
}
public void testBadModifies3() throws Exception {
parse("@modifies {|this} */", "malformed @modifies tag");
}
public void testBadModifies4() throws Exception {
parse("@modifies {this|arguments */", "malformed @modifies tag");
}
public void testBadModifies5() throws Exception {
parse("@modifies {this,arguments} */", "malformed @modifies tag");
}
public void testBadModifies6() throws Exception {
parse("@modifies {this} \n * @modifies {this} */",
"conflicting @modifies tag");
}
public void testBadModifies7() throws Exception {
parse("@modifies {impossible} */",
"unknown @modifies parameter: impossible");
}
public void testBadModifies8() throws Exception {
parse("@modifies {this}\n"
+ "@nosideeffects */", "conflicting @nosideeffects tag");
}
public void testBadModifies9() throws Exception {
parse("@nosideeffects\n"
+ "@modifies {this} */", "conflicting @modifies tag");
}
//public void testNoParseFileOverview() throws Exception {
// JSDocInfo jsdoc = parseFileOverviewWithoutDoc("@fileoverview Hi mom! */");
// assertNull(jsdoc.getFileOverview());
// assertTrue(jsdoc.hasFileOverview());
//}
public void testFileOverviewSingleLine() throws Exception {
JSDocInfo jsdoc = parseFileOverview("@fileoverview Hi mom! */");
assertEquals("Hi mom!", jsdoc.getFileOverview());
}
public void testFileOverviewMultiLine() throws Exception {
JSDocInfo jsdoc = parseFileOverview("@fileoverview Pie is \n * good! */");
assertEquals("Pie is\n good!", jsdoc.getFileOverview());
}
public void testFileOverviewDuplicate() throws Exception {
parseFileOverview(
"@fileoverview Pie \n * @fileoverview Cake */",
"extra @fileoverview tag");
}
public void testReferences() throws Exception {
JSDocInfo jsdoc
= parse("@see A cool place!"
+ "\n* @see The world."
+ "\n* @see SomeClass#SomeMember"
+ "\n* @see A boring test case*/"
, true);
Collection<String> references = jsdoc.getReferences();
assertTrue(references != null);
assertTrue(references.size() == 4);
assertContains(references, "A cool place!");
assertContains(references, "The world.");
assertContains(references, "SomeClass#SomeMember");
assertContains(references, "A boring test case");
}
public void testSingleTags() throws Exception {
JSDocInfo jsdoc
= parse("@version Some old version"
+ "\n* @deprecated In favor of the new one!"
+ "\n* @return {SomeType} The most important object :-)*/"
, true);
assertTrue(jsdoc.isDeprecated());
assertEquals("In favor of the new one!", jsdoc.getDeprecationReason());
assertEquals("Some old version", jsdoc.getVersion());
assertEquals("The most important object :-)", jsdoc.getReturnDescription());
}
public void testSingleTagsReordered() throws Exception {
JSDocInfo jsdoc
= parse("@deprecated In favor of the new one!"
+ "\n * @return {SomeType} The most important object :-)"
+ "\n * @version Some old version*/"
, true);
assertTrue(jsdoc.isDeprecated());
assertEquals("In favor of the new one!", jsdoc.getDeprecationReason());
assertEquals("Some old version", jsdoc.getVersion());
assertEquals("The most important object :-)", jsdoc.getReturnDescription());
}
public void testVersionDuplication() throws Exception {
parse("* @version Some old version"
+ "\n* @version Another version*/", true,
"conflicting @version tag");
}
public void testVersionMissing() throws Exception {
parse("* @version */", true,
"@version tag missing version information");
}
public void testAuthorMissing() throws Exception {
parse("* @author */", true,
"@author tag missing author");
}
public void testSeeMissing() throws Exception {
parse("* @see */", true,
"@see tag missing description");
}
public void testSourceName() throws Exception {
JSDocInfo jsdoc = parse("@deprecated */", true);
assertEquals("testcode", jsdoc.getAssociatedNode().getSourceFileName());
}
public void testParseBlockComment() throws Exception {
JSDocInfo jsdoc = parse("this is a nice comment\n "
+ "* that is multiline \n"
+ "* @author abc@google.com */", true);
assertEquals("this is a nice comment\nthat is multiline",
jsdoc.getBlockDescription());
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 2, 2),
"abc@google.com", 9, 2, 23);
}
public void testParseBlockComment2() throws Exception {
JSDocInfo jsdoc = parse("this is a nice comment\n "
+ "* that is *** multiline \n"
+ "* @author abc@google.com */", true);
assertEquals("this is a nice comment\nthat is *** multiline",
jsdoc.getBlockDescription());
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 2, 2),
"abc@google.com", 9, 2, 23);
}
public void testParseBlockComment3() throws Exception {
JSDocInfo jsdoc = parse("\n "
+ "* hello world \n"
+ "* @author abc@google.com */", true);
assertEquals("hello world", jsdoc.getBlockDescription());
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 2, 2),
"abc@google.com", 9, 2, 23);
}
public void testParseWithMarkers1() throws Exception {
JSDocInfo jsdoc = parse("@author abc@google.com */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 0, 0),
"abc@google.com", 7, 0, 21);
}
public void testParseWithMarkers2() throws Exception {
JSDocInfo jsdoc = parse("@param {Foo} somename abc@google.com */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0),
"abc@google.com", 21, 0, 37);
}
public void testParseWithMarkers3() throws Exception {
JSDocInfo jsdoc =
parse("@return {Foo} some long \n * multiline" +
" \n * description */", true);
JSDocInfo.Marker returnDoc =
assertAnnotationMarker(jsdoc, "return", 0, 0);
assertDocumentationInMarker(returnDoc,
"some long multiline description", 13, 2, 15);
assertEquals(8, returnDoc.getType().getPositionOnStartLine());
assertEquals(12, returnDoc.getType().getPositionOnEndLine());
}
public void testParseWithMarkers4() throws Exception {
JSDocInfo jsdoc =
parse("@author foobar \n * @param {Foo} somename abc@google.com */",
true);
assertAnnotationMarker(jsdoc, "author", 0, 0);
assertAnnotationMarker(jsdoc, "param", 1, 3);
}
public void testParseWithMarkers5() throws Exception {
JSDocInfo jsdoc =
parse("@return some long \n * multiline" +
" \n * description */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "return", 0, 0),
"some long multiline description", 8, 2, 15);
}
public void testParseWithMarkers6() throws Exception {
JSDocInfo jsdoc =
parse("@param x some long \n * multiline" +
" \n * description */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0),
"some long multiline description", 8, 2, 15);
}
public void testParseWithMarkerNames1() throws Exception {
JSDocInfo jsdoc = parse("@param {SomeType} name somedescription */", true);
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0),
"name", 0, 18);
}
public void testParseWithMarkerNames2() throws Exception {
JSDocInfo jsdoc = parse("@param {SomeType} name somedescription \n" +
"* @param {AnotherType} anothername des */", true);
assertTypeInMarker(
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0, 0),
"name", 0, 18),
"SomeType", 0, 7, 0, 16, true);
assertTypeInMarker(
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 1, 2, 1),
"anothername", 1, 23),
"AnotherType", 1, 9, 1, 21, true);
}
public void testParseWithMarkerNames3() throws Exception {
JSDocInfo jsdoc = parse(
"@param {Some.Long.Type.\n * Name} name somedescription */", true);
assertTypeInMarker(
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0, 0),
"name", 1, 10),
"Some.Long.Type.Name", 0, 7, 1, 8, true);
}
@SuppressWarnings("deprecation")
public void testParseWithoutMarkerName() throws Exception {
JSDocInfo jsdoc = parse("@author helloworld*/", true);
assertNull(assertAnnotationMarker(jsdoc, "author", 0, 0).getName());
}
public void testParseWithMarkerType() throws Exception {
JSDocInfo jsdoc = parse("@extends {FooBar}*/", true);
assertTypeInMarker(
assertAnnotationMarker(jsdoc, "extends", 0, 0),
"FooBar", 0, 9, 0, 16, true);
}
public void testParseWithMarkerType2() throws Exception {
JSDocInfo jsdoc = parse("@extends FooBar*/", true);
assertTypeInMarker(
assertAnnotationMarker(jsdoc, "extends", 0, 0),
"FooBar", 0, 9, 0, 15, false);
}
public void testTypeTagConflict1() throws Exception {
parse("@constructor \n * @constructor */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict2() throws Exception {
parse("@interface \n * @interface */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict3() throws Exception {
parse("@constructor \n * @interface */",
"Bad type annotation. cannot be both an interface and a constructor");
}
public void testTypeTagConflict4() throws Exception {
parse("@interface \n * @constructor */",
"Bad type annotation. cannot be both an interface and a constructor");
}
public void testTypeTagConflict5() throws Exception {
parse("@interface \n * @type {string} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict6() throws Exception {
parse("@typedef {string} \n * @type {string} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict7() throws Exception {
parse("@typedef {string} \n * @constructor */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict8() throws Exception {
parse("@typedef {string} \n * @return {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict9() throws Exception {
parse("@enum {string} \n * @return {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict10() throws Exception {
parse("@this {Object} \n * @enum {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict11() throws Exception {
parse("@param {Object} x \n * @type {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict12() throws Exception {
parse("@typedef {boolean} \n * @param {Object} x */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict13() throws Exception {
parse("@typedef {boolean} \n * @extends {Object} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict14() throws Exception {
parse("@return x \n * @return y */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict15() throws Exception {
parse("/**\n" +
" * @struct\n" +
" * @struct\n" +
" */\n" +
"function StrStr() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict16() throws Exception {
parse("/**\n" +
" * @struct\n" +
" * @interface\n" +
" */\n" +
"function StrIntf() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict17() throws Exception {
parse("/**\n" +
" * @interface\n" +
" * @struct\n" +
" */\n" +
"function StrIntf() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict18() throws Exception {
parse("/**\n" +
" * @dict\n" +
" * @dict\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict19() throws Exception {
parse("/**\n" +
" * @dict\n" +
" * @interface\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict20() throws Exception {
parse("/**\n" +
" * @interface\n" +
" * @dict\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict21() throws Exception {
parse("/**\n" +
" * @private {string}\n" +
" * @type {number}\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict22() throws Exception {
parse("/**\n" +
" * @protected {string}\n" +
" * @param {string} x\n" +
" */\n" +
"function DictDict(x) {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict23() throws Exception {
parse("/**\n" +
" * @public {string}\n" +
" * @return {string} x\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict24() throws Exception {
parse("/**\n" +
" * @const {string}\n" +
" * @return {string} x\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testPrivateType() throws Exception {
JSDocInfo jsdoc = parse("@private {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testProtectedType() throws Exception {
JSDocInfo jsdoc = parse("@protected {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testPublicType() throws Exception {
JSDocInfo jsdoc = parse("@public {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testConstType() throws Exception {
JSDocInfo jsdoc = parse("@const {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testStableIdGeneratorConflict() throws Exception {
parse("/**\n" +
" * @stableIdGenerator\n" +
" * @stableIdGenerator\n" +
" */\n" +
"function getId() {}",
"extra @stableIdGenerator tag");
}
public void testParserWithTemplateTypeNameMissing() {
parse("@template */",
"Bad type annotation. @template tag missing type name");
}
public void testParserWithTemplateDuplicated() {
parse("@template T\n@template V */",
"Bad type annotation. @template tag at most once");
}
public void testParserWithTwoTemplates() {
parse("@template T,V */");
}
public void testParserWithClassTemplateTypeNameMissing() {
parse("@classTemplate */",
"Bad type annotation. @classTemplate tag missing type name");
}
public void testParserWithClassTemplateDuplicated() {
parse("@classTemplate T\n@classTemplate V */",
"Bad type annotation. @classTemplate tag at most once");
}
public void testParserWithTwoClassTemplates() {
parse("@classTemplate T,V */");
}
public void testParserWithClassTemplatesAndTemplate() {
parse("@template T\n@classTemplate T,V */");
}
public void testWhitelistedNewAnnotations() {
parse("@foobar */",
"illegal use of unknown JSDoc tag \"foobar\"; ignoring it");
extraAnnotations.add("foobar");
parse("@foobar */");
}
public void testWhitelistedConflictingAnnotation() {
extraAnnotations.add("param");
JSDocInfo info = parse("@param {number} index */");
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testNonIdentifierAnnotation() {
// Try to whitelist an annotation that is not a valid JS identifier.
// It should not work.
extraAnnotations.add("123");
parse("@123 */", "illegal use of unknown JSDoc tag \"\"; ignoring it");
}
public void testUnsupportedJsDocSyntax1() {
JSDocInfo info =
parse("@param {string} [accessLevel=\"author\"] The user level */",
true);
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("accessLevel"));
assertEquals("The user level",
info.getDescriptionForParameter("accessLevel"));
}
public void testUnsupportedJsDocSyntax2() {
JSDocInfo info =
parse("@param userInfo The user info. \n" +
" * @param userInfo.name The name of the user */", true);
assertEquals(1, info.getParameterCount());
assertEquals("The user info.",
info.getDescriptionForParameter("userInfo"));
}
public void testWhitelistedAnnotations() {
parse(
"* @addon \n" +
"* @ngInject \n" +
"* @augments \n" +
"* @base \n" +
"* @borrows \n" +
"* @bug \n" +
"* @class \n" +
"* @config \n" +
"* @constructs \n" +
"* @default \n" +
"* @description \n" +
"* @event \n" +
"* @example \n" +
"* @exception \n" +
"* @exec \n" +
"* @externs \n" +
"* @field \n" +
"* @function \n" +
"* @id \n" +
"* @ignore \n" +
"* @inner \n" +
"* @lends {string} \n" +
"* @link \n" +
"* @member \n" +
"* @memberOf \n" +
"* @modName \n" +
"* @mods \n" +
"* @name \n" +
"* @namespace \n" +
"* @nocompile \n" +
"* @property \n" +
"* @requires \n" +
"* @since \n" +
"* @static \n" +
"* @supported */");
}
public void testGetOriginalCommentString() throws Exception {
String comment = "* @desc This is a comment */";
JSDocInfo info = parse(comment);
assertNull(info.getOriginalCommentString());
info = parse(comment, true /* parseDocumentation */);
assertEquals(comment, info.getOriginalCommentString());
}
public void testParseNgInject1() throws Exception {
assertTrue(parse("@ngInject*/").isNgInject());
}
public void testParseNgInject2() throws Exception {
parse("@ngInject \n@ngInject*/", "extra @ngInject tag");
}
public void testTextExtents() {
parse("@return {@code foo} bar \n * baz. */",
true, "Bad type annotation. type not recognized due to syntax error");
}
/**
* Asserts that a documentation field exists on the given marker.
*
* @param description The text of the documentation field expected.
* @param startCharno The starting character of the text.
* @param endLineno The ending line of the text.
* @param endCharno The ending character of the text.
* @return The marker, for chaining purposes.
*/
private JSDocInfo.Marker assertDocumentationInMarker(JSDocInfo.Marker marker,
String description,
int startCharno,
int endLineno,
int endCharno) {
assertTrue(marker.getDescription() != null);
assertEquals(description, marker.getDescription().getItem());
// Match positional information.
assertEquals(marker.getAnnotation().getStartLine(),
marker.getDescription().getStartLine());
assertEquals(startCharno, marker.getDescription().getPositionOnStartLine());
assertEquals(endLineno, marker.getDescription().getEndLine());
assertEquals(endCharno, marker.getDescription().getPositionOnEndLine());
return marker;
}
/**
* Asserts that a type field exists on the given marker.
*
* @param typeName The name of the type expected in the type field.
* @param startCharno The starting character of the type declaration.
* @param hasBrackets Whether the type in the type field is expected
* to have brackets.
* @return The marker, for chaining purposes.
*/
private JSDocInfo.Marker assertTypeInMarker(
JSDocInfo.Marker marker, String typeName,
int startLineno, int startCharno, int endLineno, int endCharno,
boolean hasBrackets) {
assertTrue(marker.getType() != null);
assertTrue(marker.getType().getItem().isString());
// Match the name and brackets information.
String foundName = marker.getType().getItem().getString();
assertEquals(typeName, foundName);
assertEquals(hasBrackets, marker.getType().hasBrackets());
// Match position information.
assertEquals(startCharno, marker.getType().getPositionOnStartLine());
assertEquals(endCharno, marker.getType().getPositionOnEndLine());
assertEquals(startLineno, marker.getType().getStartLine());
assertEquals(endLineno, marker.getType().getEndLine());
return marker;
}
/**
* Asserts that a name field exists on the given marker.
*
* @param name The name expected in the name field.
* @param startCharno The starting character of the text.
* @return The marker, for chaining purposes.
*/
@SuppressWarnings("deprecation")
private JSDocInfo.Marker assertNameInMarker(JSDocInfo.Marker marker,
String name, int startLine, int startCharno) {
assertTrue(marker.getName() != null);
assertEquals(name, marker.getName().getItem());
assertEquals(startCharno, marker.getName().getPositionOnStartLine());
assertEquals(startCharno + name.length(),
marker.getName().getPositionOnEndLine());
assertEquals(startLine, marker.getName().getStartLine());
assertEquals(startLine, marker.getName().getEndLine());
return marker;
}
/**
* Asserts that an annotation marker of a given annotation name
* is found in the given JSDocInfo.
*
* @param jsdoc The JSDocInfo in which to search for the annotation marker.
* @param annotationName The name/type of the annotation for which to
* search. Example: "author" for an "@author" annotation.
* @param startLineno The expected starting line number of the marker.
* @param startCharno The expected character on the starting line.
* @return The marker found, for further testing.
*/
private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc,
String annotationName,
int startLineno,
int startCharno) {
return assertAnnotationMarker(jsdoc, annotationName, startLineno,
startCharno, 0);
}
/**
* Asserts that the index-th annotation marker of a given annotation name
* is found in the given JSDocInfo.
*
* @param jsdoc The JSDocInfo in which to search for the annotation marker.
* @param annotationName The name/type of the annotation for which to
* search. Example: "author" for an "@author" annotation.
* @param startLineno The expected starting line number of the marker.
* @param startCharno The expected character on the starting line.
* @param index The index of the marker.
* @return The marker found, for further testing.
*/
private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc,
String annotationName,
int startLineno,
int startCharno,
int index) {
Collection<JSDocInfo.Marker> markers = jsdoc.getMarkers();
assertTrue(markers.size() > 0);
int counter = 0;
for (JSDocInfo.Marker marker : markers) {
if (marker.getAnnotation() != null) {
if (annotationName.equals(marker.getAnnotation().getItem())) {
if (counter == index) {
assertEquals(startLineno, marker.getAnnotation().getStartLine());
assertEquals(startCharno,
marker.getAnnotation().getPositionOnStartLine());
assertEquals(startLineno, marker.getAnnotation().getEndLine());
assertEquals(startCharno + annotationName.length(),
marker.getAnnotation().getPositionOnEndLine());
return marker;
}
counter++;
}
}
}
fail("No marker found");
return null;
}
private <T> void assertContains(Collection<T> collection, T item) {
assertTrue(collection.contains(item));
}
private void parseFull(String code, String... warnings) {
CompilerEnvirons environment = new CompilerEnvirons();
TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings);
environment.setErrorReporter(testErrorReporter);
environment.setRecordingComments(true);
environment.setRecordingLocalJsDocComments(true);
Parser p = new Parser(environment, testErrorReporter);
AstRoot script = p.parse(code, null, 0);
Config config =
new Config(extraAnnotations, extraSuppressions,
true, LanguageMode.ECMASCRIPT3, false);
for (Comment comment : script.getComments()) {
JsDocInfoParser jsdocParser =
new JsDocInfoParser(
new JsDocTokenStream(comment.getValue().substring(3),
comment.getLineno()),
comment,
null,
config,
testErrorReporter);
jsdocParser.parse();
jsdocParser.retrieveAndResetParsedJSDocInfo();
}
assertTrue("some expected warnings were not reported",
testErrorReporter.hasEncounteredAllWarnings());
}
@SuppressWarnings("unused")
private JSDocInfo parseFileOverviewWithoutDoc(String comment,
String... warnings) {
return parse(comment, false, true, warnings);
}
private JSDocInfo parseFileOverview(String comment, String... warnings) {
return parse(comment, true, true, warnings);
}
private JSDocInfo parse(String comment, String... warnings) {
return parse(comment, false, warnings);
}
private JSDocInfo parse(String comment, boolean parseDocumentation,
String... warnings) {
return parse(comment, parseDocumentation, false, warnings);
}
private JSDocInfo parse(String comment, boolean parseDocumentation,
boolean parseFileOverview, String... warnings) {
TestErrorReporter errorReporter = new TestErrorReporter(null, warnings);
Config config = new Config(extraAnnotations, extraSuppressions,
parseDocumentation, LanguageMode.ECMASCRIPT3, false);
StaticSourceFile file = new SimpleSourceFile("testcode", false);
Node associatedNode = new Node(Token.SCRIPT);
associatedNode.setInputId(new InputId(file.getName()));
associatedNode.setStaticSourceFile(file);
JsDocInfoParser jsdocParser = new JsDocInfoParser(
stream(comment),
new Comment(0, 0, CommentType.JSDOC, comment),
associatedNode,
config, errorReporter);
if (fileLevelJsDocBuilder != null) {
jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder);
}
jsdocParser.parse();
assertTrue("expected warnings were not reported",
errorReporter.hasEncounteredAllWarnings());
if (parseFileOverview) {
return jsdocParser.getFileOverviewJSDocInfo();
} else {
return jsdocParser.retrieveAndResetParsedJSDocInfo();
}
}
private Node parseType(String typeComment) {
return JsDocInfoParser.parseTypeString(typeComment);
}
private JsDocTokenStream stream(String source) {
return new JsDocTokenStream(source, 0);
}
private void assertTemplatizedTypeEquals(String key, JSType expected,
JSTypeExpression te) {
assertEquals(
expected, resolve(te).getTemplateTypeMap().getTemplateType(key));
}
} | // You are a professional Java test case writer, please create a test case named `testTextExtents` for the issue `Closure-919`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-919
//
// ## Issue-Title:
// Exception when parsing erroneous jsdoc: /**@return {@code foo} bar * baz. */
//
// ## Issue-Description:
// The following causes an exception in JSDocInfoParser.
//
// /\*\*
// \* @return {@code foo} bar
// \* baz. \*/
// var x;
//
//
//
// Fix to follow.
//
//
public void testTextExtents() {
| 2,757 | 133 | 2,754 | test/com/google/javascript/jscomp/parsing/JsDocInfoParserTest.java | test | ```markdown
## Issue-ID: Closure-919
## Issue-Title:
Exception when parsing erroneous jsdoc: /**@return {@code foo} bar * baz. */
## Issue-Description:
The following causes an exception in JSDocInfoParser.
/\*\*
\* @return {@code foo} bar
\* baz. \*/
var x;
Fix to follow.
```
You are a professional Java test case writer, please create a test case named `testTextExtents` for the issue `Closure-919`, utilizing the provided issue report information and the following function signature.
```java
public void testTextExtents() {
```
| 2,754 | [
"com.google.javascript.jscomp.parsing.JsDocInfoParser"
] | 3fa8a35fccba88a47754c261ff88138a95cd91771fd06788f60a83260c25a25f | public void testTextExtents() | // You are a professional Java test case writer, please create a test case named `testTextExtents` for the issue `Closure-919`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-919
//
// ## Issue-Title:
// Exception when parsing erroneous jsdoc: /**@return {@code foo} bar * baz. */
//
// ## Issue-Description:
// The following causes an exception in JSDocInfoParser.
//
// /\*\*
// \* @return {@code foo} bar
// \* baz. \*/
// var x;
//
//
//
// Fix to follow.
//
//
| Closure | /*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.parsing;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.parsing.Config.LanguageMode;
import com.google.javascript.jscomp.testing.TestErrorReporter;
import com.google.javascript.rhino.InputId;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.head.CompilerEnvirons;
import com.google.javascript.rhino.head.Parser;
import com.google.javascript.rhino.head.Token.CommentType;
import com.google.javascript.rhino.head.ast.AstRoot;
import com.google.javascript.rhino.head.ast.Comment;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.SimpleSourceFile;
import com.google.javascript.rhino.jstype.StaticSourceFile;
import com.google.javascript.rhino.testing.BaseJSTypeTestCase;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class JsDocInfoParserTest extends BaseJSTypeTestCase {
private Set<String> extraAnnotations;
private Set<String> extraSuppressions;
private Node.FileLevelJsDocBuilder fileLevelJsDocBuilder = null;
@Override
public void setUp() throws Exception {
super.setUp();
extraAnnotations =
Sets.newHashSet(
ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false)
.annotationNames.keySet());
extraSuppressions =
Sets.newHashSet(
ParserRunner.createConfig(true, LanguageMode.ECMASCRIPT3, false)
.suppressionNames);
extraSuppressions.add("x");
extraSuppressions.add("y");
extraSuppressions.add("z");
}
public void testParseTypeViaStatic1() throws Exception {
Node typeNode = parseType("null");
assertTypeEquals(NULL_TYPE, typeNode);
}
public void testParseTypeViaStatic2() throws Exception {
Node typeNode = parseType("string");
assertTypeEquals(STRING_TYPE, typeNode);
}
public void testParseTypeViaStatic3() throws Exception {
Node typeNode = parseType("!Date");
assertTypeEquals(DATE_TYPE, typeNode);
}
public void testParseTypeViaStatic4() throws Exception {
Node typeNode = parseType("boolean|string");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, STRING_TYPE), typeNode);
}
public void testParseInvalidTypeViaStatic() throws Exception {
Node typeNode = parseType("sometype.<anothertype");
assertNull(typeNode);
}
public void testParseInvalidTypeViaStatic2() throws Exception {
Node typeNode = parseType("");
assertNull(typeNode);
}
public void testParseNamedType1() throws Exception {
assertNull(parse("@type null", "Unexpected end of file"));
}
public void testParseNamedType2() throws Exception {
JSDocInfo info = parse("@type null*/");
assertTypeEquals(NULL_TYPE, info.getType());
}
public void testParseNamedType3() throws Exception {
JSDocInfo info = parse("@type {string}*/");
assertTypeEquals(STRING_TYPE, info.getType());
}
public void testParseNamedType4() throws Exception {
// Multi-line @type.
JSDocInfo info = parse("@type \n {string}*/");
assertTypeEquals(STRING_TYPE, info.getType());
}
public void testParseNamedType5() throws Exception {
JSDocInfo info = parse("@type {!goog.\nBar}*/");
assertTypeEquals(
registry.createNamedType("goog.Bar", null, -1, -1),
info.getType());
}
public void testParseNamedType6() throws Exception {
JSDocInfo info = parse("@type {!goog.\n * Bar.\n * Baz}*/");
assertTypeEquals(
registry.createNamedType("goog.Bar.Baz", null, -1, -1),
info.getType());
}
public void testParseNamedTypeError1() throws Exception {
// To avoid parsing ambiguities, type names must end in a '.' to
// get the continuation behavior.
parse("@type {!goog\n * .Bar} */",
"Bad type annotation. expected closing }");
}
public void testParseNamedTypeError2() throws Exception {
parse("@type {!goog.\n * Bar\n * .Baz} */",
"Bad type annotation. expected closing }");
}
public void testTypedefType1() throws Exception {
JSDocInfo info = parse("@typedef string */");
assertTrue(info.hasTypedefType());
assertTypeEquals(STRING_TYPE, info.getTypedefType());
}
public void testTypedefType2() throws Exception {
JSDocInfo info = parse("@typedef \n {string}*/");
assertTrue(info.hasTypedefType());
assertTypeEquals(STRING_TYPE, info.getTypedefType());
}
public void testTypedefType3() throws Exception {
JSDocInfo info = parse("@typedef \n {(string|number)}*/");
assertTrue(info.hasTypedefType());
assertTypeEquals(
createUnionType(NUMBER_TYPE, STRING_TYPE),
info.getTypedefType());
}
public void testParseStringType1() throws Exception {
assertTypeEquals(STRING_TYPE, parse("@type {string}*/").getType());
}
public void testParseStringType2() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE, parse("@type {!String}*/").getType());
}
public void testParseBooleanType1() throws Exception {
assertTypeEquals(BOOLEAN_TYPE, parse("@type {boolean}*/").getType());
}
public void testParseBooleanType2() throws Exception {
assertTypeEquals(
BOOLEAN_OBJECT_TYPE, parse("@type {!Boolean}*/").getType());
}
public void testParseNumberType1() throws Exception {
assertTypeEquals(NUMBER_TYPE, parse("@type {number}*/").getType());
}
public void testParseNumberType2() throws Exception {
assertTypeEquals(NUMBER_OBJECT_TYPE, parse("@type {!Number}*/").getType());
}
public void testParseNullType1() throws Exception {
assertTypeEquals(NULL_TYPE, parse("@type {null}*/").getType());
}
public void testParseNullType2() throws Exception {
assertTypeEquals(NULL_TYPE, parse("@type {Null}*/").getType());
}
public void testParseAllType1() throws Exception {
testParseType("*");
}
public void testParseAllType2() throws Exception {
testParseType("*?", "*");
}
public void testParseObjectType() throws Exception {
assertTypeEquals(OBJECT_TYPE, parse("@type {!Object}*/").getType());
}
public void testParseDateType() throws Exception {
assertTypeEquals(DATE_TYPE, parse("@type {!Date}*/").getType());
}
public void testParseFunctionType() throws Exception {
assertTypeEquals(
createNullableType(U2U_CONSTRUCTOR_TYPE),
parse("@type {Function}*/").getType());
}
public void testParseRegExpType() throws Exception {
assertTypeEquals(REGEXP_TYPE, parse("@type {!RegExp}*/").getType());
}
public void testParseErrorTypes() throws Exception {
assertTypeEquals(ERROR_TYPE, parse("@type {!Error}*/").getType());
assertTypeEquals(URI_ERROR_TYPE, parse("@type {!URIError}*/").getType());
assertTypeEquals(EVAL_ERROR_TYPE, parse("@type {!EvalError}*/").getType());
assertTypeEquals(REFERENCE_ERROR_TYPE,
parse("@type {!ReferenceError}*/").getType());
assertTypeEquals(TYPE_ERROR_TYPE, parse("@type {!TypeError}*/").getType());
assertTypeEquals(
RANGE_ERROR_TYPE, parse("@type {!RangeError}*/").getType());
assertTypeEquals(
SYNTAX_ERROR_TYPE, parse("@type {!SyntaxError}*/").getType());
}
public void testParseUndefinedType1() throws Exception {
assertTypeEquals(VOID_TYPE, parse("@type {undefined}*/").getType());
}
public void testParseUndefinedType2() throws Exception {
assertTypeEquals(VOID_TYPE, parse("@type {Undefined}*/").getType());
}
public void testParseUndefinedType3() throws Exception {
assertTypeEquals(VOID_TYPE, parse("@type {void}*/").getType());
}
public void testParseTemplatizedType1() throws Exception {
JSDocInfo info = parse("@type !Array.<number> */");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType());
}
public void testParseTemplatizedType2() throws Exception {
JSDocInfo info = parse("@type {!Array.<number>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType());
}
public void testParseTemplatizedType3() throws Exception {
JSDocInfo info = parse("@type !Array.<(number,null)>*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType4() throws Exception {
JSDocInfo info = parse("@type {!Array.<(number|null)>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType5() throws Exception {
JSDocInfo info = parse("@type {!Array.<Array.<(number|null)>>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(NULL_TYPE,
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE)))),
info.getType());
}
public void testParseTemplatizedType6() throws Exception {
JSDocInfo info = parse("@type {!Array.<!Array.<(number|null)>>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createTemplatizedType(ARRAY_TYPE,
createUnionType(NUMBER_TYPE, NULL_TYPE))),
info.getType());
}
public void testParseTemplatizedType7() throws Exception {
JSDocInfo info = parse("@type {!Array.<function():Date>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
registry.createFunctionType(
createUnionType(DATE_TYPE, NULL_TYPE))),
info.getType());
}
public void testParseTemplatizedType8() throws Exception {
JSDocInfo info = parse("@type {!Array.<function():!Date>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
registry.createFunctionType(DATE_TYPE)),
info.getType());
}
public void testParseTemplatizedType9() throws Exception {
JSDocInfo info = parse("@type {!Array.<Date|number>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(DATE_TYPE, NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType10() throws Exception {
JSDocInfo info = parse("@type {!Array.<Date|number|boolean>}*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
createUnionType(DATE_TYPE, NUMBER_TYPE, BOOLEAN_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseTemplatizedType11() throws Exception {
JSDocInfo info = parse("@type {!Object.<number>}*/");
assertTypeEquals(
createTemplatizedType(
OBJECT_TYPE, ImmutableList.of(UNKNOWN_TYPE, NUMBER_TYPE)),
info.getType());
assertTemplatizedTypeEquals(
JSTypeRegistry.OBJECT_ELEMENT_TEMPLATE, NUMBER_TYPE, info.getType());
}
public void testParseTemplatizedType12() throws Exception {
JSDocInfo info = parse("@type {!Object.<string,number>}*/");
assertTypeEquals(
createTemplatizedType(
OBJECT_TYPE, ImmutableList.of(STRING_TYPE, NUMBER_TYPE)),
info.getType());
assertTemplatizedTypeEquals(
JSTypeRegistry.OBJECT_ELEMENT_TEMPLATE, NUMBER_TYPE, info.getType());
assertTemplatizedTypeEquals(
JSTypeRegistry.OBJECT_INDEX_TEMPLATE, STRING_TYPE, info.getType());
}
public void testParseTemplatizedType13() throws Exception {
JSDocInfo info = parse("@type !Array.<?> */");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, UNKNOWN_TYPE), info.getType());
}
public void testParseUnionType1() throws Exception {
JSDocInfo info = parse("@type {(boolean,null)}*/");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType());
}
public void testParseUnionType2() throws Exception {
JSDocInfo info = parse("@type {boolean|null}*/");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType());
}
public void testParseUnionType3() throws Exception {
JSDocInfo info = parse("@type {boolean||null}*/");
assertTypeEquals(createUnionType(BOOLEAN_TYPE, NULL_TYPE), info.getType());
}
public void testParseUnionType4() throws Exception {
JSDocInfo info = parse("@type {(Array.<boolean>,null)}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType5() throws Exception {
JSDocInfo info = parse("@type {(null, Array.<boolean>)}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType6() throws Exception {
JSDocInfo info = parse("@type {Array.<boolean>|null}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType7() throws Exception {
JSDocInfo info = parse("@type {null|Array.<boolean>}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType8() throws Exception {
JSDocInfo info = parse("@type {null||Array.<boolean>}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType9() throws Exception {
JSDocInfo info = parse("@type {Array.<boolean>||null}*/");
assertTypeEquals(createUnionType(
createTemplatizedType(
ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), info.getType());
}
public void testParseUnionType10() throws Exception {
parse("@type {string|}*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnionType11() throws Exception {
parse("@type {(string,)}*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnionType12() throws Exception {
parse("@type {()}*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnionType13() throws Exception {
testParseType(
"(function(this:Date),function(this:String):number)",
"Function");
}
public void testParseUnionType14() throws Exception {
testParseType(
"(function(...[function(number):boolean]):number)|" +
"function(this:String, string):number",
"Function");
}
public void testParseUnionType15() throws Exception {
testParseType("*|number", "*");
}
public void testParseUnionType16() throws Exception {
testParseType("number|*", "*");
}
public void testParseUnionType17() throws Exception {
testParseType("string|number|*", "*");
}
public void testParseUnionType18() throws Exception {
testParseType("(string,*,number)", "*");
}
public void testParseUnionTypeError1() throws Exception {
parse("@type {(string,|number)} */",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseUnknownType1() throws Exception {
testParseType("?");
}
public void testParseUnknownType2() throws Exception {
testParseType("(?|number)", "?");
}
public void testParseUnknownType3() throws Exception {
testParseType("(number|?)", "?");
}
public void testParseFunctionalType1() throws Exception {
testParseType("function (): number");
}
public void testParseFunctionalType2() throws Exception {
testParseType("function (number, string): boolean");
}
public void testParseFunctionalType3() throws Exception {
testParseType(
"function(this:Array)", "function (this:Array): ?");
}
public void testParseFunctionalType4() throws Exception {
testParseType("function (...[number]): boolean");
}
public void testParseFunctionalType5() throws Exception {
testParseType("function (number, ...[string]): boolean");
}
public void testParseFunctionalType6() throws Exception {
testParseType(
"function (this:Date, number): (boolean|number|string)");
}
public void testParseFunctionalType7() throws Exception {
testParseType("function()", "function (): ?");
}
public void testParseFunctionalType8() throws Exception {
testParseType(
"function(this:Array,...[boolean])",
"function (this:Array, ...[boolean]): ?");
}
public void testParseFunctionalType9() throws Exception {
testParseType(
"function(this:Array,!Date,...[boolean?])",
"function (this:Array, Date, ...[(boolean|null)]): ?");
}
public void testParseFunctionalType10() throws Exception {
testParseType(
"function(...[Object?]):boolean?",
"function (...[(Object|null)]): (boolean|null)");
}
public void testParseFunctionalType11() throws Exception {
testParseType(
"function(...[[number]]):[number?]",
"function (...[Array]): Array");
}
public void testParseFunctionalType12() throws Exception {
testParseType(
"function(...)",
"function (...[?]): ?");
}
public void testParseFunctionalType13() throws Exception {
testParseType(
"function(...): void",
"function (...[?]): undefined");
}
public void testParseFunctionalType14() throws Exception {
testParseType("function (*, string, number): boolean");
}
public void testParseFunctionalType15() throws Exception {
testParseType("function (?, string): boolean");
}
public void testParseFunctionalType16() throws Exception {
testParseType("function (string, ?): ?");
}
public void testParseFunctionalType17() throws Exception {
testParseType("(function (?): ?|number)");
}
public void testParseFunctionalType18() throws Exception {
testParseType("function (?): (?|number)", "function (?): ?");
}
public void testParseFunctionalType19() throws Exception {
testParseType(
"function(...[?]): void",
"function (...[?]): undefined");
}
public void testStructuralConstructor() throws Exception {
JSType type = testParseType(
"function (new:Object)", "function (new:Object): ?");
assertTrue(type.isConstructor());
assertFalse(type.isNominalConstructor());
}
public void testNominalConstructor() throws Exception {
ObjectType type = testParseType("Array", "(Array|null)").dereference();
assertTrue(type.getConstructor().isNominalConstructor());
}
public void testBug1419535() throws Exception {
parse("@type {function(Object, string, *)?} */");
parse("@type {function(Object, string, *)|null} */");
}
public void testIssue477() throws Exception {
parse("@type function */",
"Bad type annotation. missing opening (");
}
public void testMalformedThisAnnotation() throws Exception {
parse("@this */",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseFunctionalTypeError1() throws Exception {
parse("@type {function number):string}*/",
"Bad type annotation. missing opening (");
}
public void testParseFunctionalTypeError2() throws Exception {
parse("@type {function( number}*/",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError3() throws Exception {
parse("@type {function(...[number], string)}*/",
"Bad type annotation. variable length argument must be last");
}
public void testParseFunctionalTypeError4() throws Exception {
parse("@type {function(string, ...[number], boolean):string}*/",
"Bad type annotation. variable length argument must be last");
}
public void testParseFunctionalTypeError5() throws Exception {
parse("@type {function (thi:Array)}*/",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError6() throws Exception {
resolve(parse("@type {function (this:number)}*/").getType(),
"this type must be an object type");
}
public void testParseFunctionalTypeError7() throws Exception {
parse("@type {function(...[number)}*/",
"Bad type annotation. missing closing ]");
}
public void testParseFunctionalTypeError8() throws Exception {
parse("@type {function(...number])}*/",
"Bad type annotation. missing opening [");
}
public void testParseFunctionalTypeError9() throws Exception {
parse("@type {function (new:Array, this:Object)} */",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError10() throws Exception {
parse("@type {function (this:Array, new:Object)} */",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError11() throws Exception {
parse("@type {function (Array, new:Object)} */",
"Bad type annotation. missing closing )");
}
public void testParseFunctionalTypeError12() throws Exception {
resolve(parse("@type {function (new:number)}*/").getType(),
"constructed type must be an object type");
}
public void testParseArrayType1() throws Exception {
testParseType("[number]", "Array");
}
public void testParseArrayType2() throws Exception {
testParseType("[(number,boolean,[Object?])]", "Array");
}
public void testParseArrayType3() throws Exception {
testParseType("[[number],[string]]?", "(Array|null)");
}
public void testParseArrayTypeError1() throws Exception {
parse("@type {[number}*/",
"Bad type annotation. missing closing ]");
}
public void testParseArrayTypeError2() throws Exception {
parse("@type {number]}*/",
"Bad type annotation. expected closing }");
}
public void testParseArrayTypeError3() throws Exception {
parse("@type {[(number,boolean,Object?])]}*/",
"Bad type annotation. missing closing )");
}
public void testParseArrayTypeError4() throws Exception {
parse("@type {(number,boolean,[Object?)]}*/",
"Bad type annotation. missing closing ]");
}
private JSType testParseType(String type) throws Exception {
return testParseType(type, type);
}
private JSType testParseType(
String type, String typeExpected) throws Exception {
JSDocInfo info = parse("@type {" + type + "}*/");
assertNotNull(info);
assertTrue(info.hasType());
JSType actual = resolve(info.getType());
assertEquals(typeExpected, actual.toString());
return actual;
}
public void testParseNullableModifiers1() throws Exception {
JSDocInfo info = parse("@type {string?}*/");
assertTypeEquals(createNullableType(STRING_TYPE), info.getType());
}
public void testParseNullableModifiers2() throws Exception {
JSDocInfo info = parse("@type {!Array.<string?>}*/");
assertTypeEquals(
createTemplatizedType(
ARRAY_TYPE, createUnionType(STRING_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseNullableModifiers3() throws Exception {
JSDocInfo info = parse("@type {Array.<boolean>?}*/");
assertTypeEquals(
createNullableType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers4() throws Exception {
JSDocInfo info = parse("@type {(string,boolean)?}*/");
assertTypeEquals(
createNullableType(createUnionType(STRING_TYPE, BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers5() throws Exception {
JSDocInfo info = parse("@type {(string?,boolean)}*/");
assertTypeEquals(
createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE),
info.getType());
}
public void testParseNullableModifiers6() throws Exception {
JSDocInfo info = parse("@type {(string,boolean?)}*/");
assertTypeEquals(
createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers7() throws Exception {
JSDocInfo info = parse("@type {string?|boolean}*/");
assertTypeEquals(
createUnionType(createNullableType(STRING_TYPE), BOOLEAN_TYPE),
info.getType());
}
public void testParseNullableModifiers8() throws Exception {
JSDocInfo info = parse("@type {string|boolean?}*/");
assertTypeEquals(
createUnionType(STRING_TYPE, createNullableType(BOOLEAN_TYPE)),
info.getType());
}
public void testParseNullableModifiers9() throws Exception {
JSDocInfo info = parse("@type {foo.Hello.World?}*/");
assertTypeEquals(
createNullableType(
registry.createNamedType(
"foo.Hello.World", null, -1, -1)),
info.getType());
}
public void testParseOptionalModifier() throws Exception {
JSDocInfo info = parse("@type {function(number=)}*/");
assertTypeEquals(
registry.createFunctionType(
UNKNOWN_TYPE, registry.createOptionalParameters(NUMBER_TYPE)),
info.getType());
}
public void testParseNewline1() throws Exception {
JSDocInfo info = parse("@type {string\n* }\n*/");
assertTypeEquals(STRING_TYPE, info.getType());
}
public void testParseNewline2() throws Exception {
JSDocInfo info = parse("@type !Array.<\n* number\n* > */");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), info.getType());
}
public void testParseNewline3() throws Exception {
JSDocInfo info = parse("@type !Array.<(number,\n* null)>*/");
assertTypeEquals(
createTemplatizedType(
ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseNewline4() throws Exception {
JSDocInfo info = parse("@type !Array.<(number|\n* null)>*/");
assertTypeEquals(
createTemplatizedType(
ARRAY_TYPE, createUnionType(NUMBER_TYPE, NULL_TYPE)),
info.getType());
}
public void testParseNewline5() throws Exception {
JSDocInfo info = parse("@type !Array.<function(\n* )\n* :\n* Date>*/");
assertTypeEquals(
createTemplatizedType(ARRAY_TYPE,
registry.createFunctionType(
createUnionType(DATE_TYPE, NULL_TYPE))),
info.getType());
}
public void testParseReturnType1() throws Exception {
JSDocInfo info =
parse("@return {null|string|Array.<boolean>}*/");
assertTypeEquals(
createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE),
NULL_TYPE, STRING_TYPE),
info.getReturnType());
}
public void testParseReturnType2() throws Exception {
JSDocInfo info =
parse("@returns {null|(string,Array.<boolean>)}*/");
assertTypeEquals(
createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE),
NULL_TYPE, STRING_TYPE),
info.getReturnType());
}
public void testParseReturnType3() throws Exception {
JSDocInfo info =
parse("@return {((null||Array.<boolean>,string),boolean)}*/");
assertTypeEquals(
createUnionType(createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE),
NULL_TYPE, STRING_TYPE, BOOLEAN_TYPE),
info.getReturnType());
}
public void testParseThisType1() throws Exception {
JSDocInfo info =
parse("@this {goog.foo.Bar}*/");
assertTypeEquals(
registry.createNamedType("goog.foo.Bar", null, -1, -1),
info.getThisType());
}
public void testParseThisType2() throws Exception {
JSDocInfo info =
parse("@this goog.foo.Bar*/");
assertTypeEquals(
registry.createNamedType("goog.foo.Bar", null, -1, -1),
info.getThisType());
}
public void testParseThisType3() throws Exception {
parse("@type {number}\n@this goog.foo.Bar*/",
"Bad type annotation. type annotation incompatible " +
"with other annotations");
}
public void testParseThisType4() throws Exception {
resolve(parse("@this number*/").getThisType(),
"@this must specify an object type");
}
public void testParseThisType5() throws Exception {
parse("@this {Date|Error}*/");
}
public void testParseThisType6() throws Exception {
resolve(parse("@this {Date|number}*/").getThisType(),
"@this must specify an object type");
}
public void testParseParam1() throws Exception {
JSDocInfo info = parse("@param {number} index*/");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam2() throws Exception {
JSDocInfo info = parse("@param index*/");
assertEquals(1, info.getParameterCount());
assertEquals(null, info.getParameterType("index"));
}
public void testParseParam3() throws Exception {
JSDocInfo info = parse("@param {number} index useful comments*/");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam4() throws Exception {
JSDocInfo info = parse("@param index useful comments*/");
assertEquals(1, info.getParameterCount());
assertEquals(null, info.getParameterType("index"));
}
public void testParseParam5() throws Exception {
// Test for multi-line @param.
JSDocInfo info = parse("@param {number} \n index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam6() throws Exception {
// Test for multi-line @param.
JSDocInfo info = parse("@param {number} \n * index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testParseParam7() throws Exception {
// Optional @param
JSDocInfo info = parse("@param {number=} index */");
assertTypeEquals(
registry.createOptionalType(NUMBER_TYPE),
info.getParameterType("index"));
}
public void testParseParam8() throws Exception {
// Var args @param
JSDocInfo info = parse("@param {...number} index */");
assertTypeEquals(
registry.createOptionalType(NUMBER_TYPE),
info.getParameterType("index"));
}
public void testParseParam9() throws Exception {
parse("@param {...number=} index */",
"Bad type annotation. expected closing }",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParam10() throws Exception {
parse("@param {...number index */",
"Bad type annotation. expected closing }");
}
public void testParseParam11() throws Exception {
parse("@param {number= index */",
"Bad type annotation. expected closing }");
}
public void testParseParam12() throws Exception {
JSDocInfo info = parse("@param {...number|string} index */");
assertTypeEquals(
registry.createOptionalType(
registry.createUnionType(STRING_TYPE, NUMBER_TYPE)),
info.getParameterType("index"));
}
public void testParseParam13() throws Exception {
JSDocInfo info = parse("@param {...(number|string)} index */");
assertTypeEquals(
registry.createOptionalType(
registry.createUnionType(STRING_TYPE, NUMBER_TYPE)),
info.getParameterType("index"));
}
public void testParseParam14() throws Exception {
JSDocInfo info = parse("@param {string} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("index"));
}
public void testParseParam15() throws Exception {
JSDocInfo info = parse("@param {string} [index */",
"Bad type annotation. missing closing ]");
assertEquals(1, info.getParameterCount());
assertTypeEquals(STRING_TYPE, info.getParameterType("index"));
}
public void testParseParam16() throws Exception {
JSDocInfo info = parse("@param {string} index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(STRING_TYPE, info.getParameterType("index"));
}
public void testParseParam17() throws Exception {
JSDocInfo info = parse("@param {string=} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("index"));
}
public void testParseParam18() throws Exception {
JSDocInfo info = parse("@param {...string} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("index"));
}
public void testParseParam19() throws Exception {
JSDocInfo info = parse("@param {...} [index] */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(UNKNOWN_TYPE),
info.getParameterType("index"));
assertTrue(info.getParameterType("index").isVarArgs());
}
public void testParseParam20() throws Exception {
JSDocInfo info = parse("@param {?=} index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
UNKNOWN_TYPE, info.getParameterType("index"));
}
public void testParseParam21() throws Exception {
JSDocInfo info = parse("@param {...?} index */");
assertEquals(1, info.getParameterCount());
assertTypeEquals(
UNKNOWN_TYPE, info.getParameterType("index"));
assertTrue(info.getParameterType("index").isVarArgs());
}
public void testParseThrows1() throws Exception {
JSDocInfo info = parse("@throws {number} Some number */");
assertEquals(1, info.getThrownTypes().size());
assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0));
}
public void testParseThrows2() throws Exception {
JSDocInfo info = parse("@throws {number} Some number\n "
+ "*@throws {String} A string */");
assertEquals(2, info.getThrownTypes().size());
assertTypeEquals(NUMBER_TYPE, info.getThrownTypes().get(0));
}
public void testParseRecordType1() throws Exception {
parseFull("/** @param {{x}} n\n*/");
}
public void testParseRecordType2() throws Exception {
parseFull("/** @param {{z, y}} n\n*/");
}
public void testParseRecordType3() throws Exception {
parseFull("/** @param {{z, y, x, q, hello, thisisatest}} n\n*/");
}
public void testParseRecordType4() throws Exception {
parseFull("/** @param {{a, 'a', 'hello', 2, this, do, while, for}} n\n*/");
}
public void testParseRecordType5() throws Exception {
parseFull("/** @param {{x : hello}} n\n*/");
}
public void testParseRecordType6() throws Exception {
parseFull("/** @param {{'x' : hello}} n\n*/");
}
public void testParseRecordType7() throws Exception {
parseFull("/** @param {{'x' : !hello}} n\n*/");
}
public void testParseRecordType8() throws Exception {
parseFull("/** @param {{'x' : !hello, y : bar}} n\n*/");
}
public void testParseRecordType9() throws Exception {
parseFull("/** @param {{'x' : !hello, y : {z : bar, 3 : meh}}} n\n*/");
}
public void testParseRecordType10() throws Exception {
parseFull("/** @param {{__proto__ : moo}} n\n*/");
}
public void testParseRecordType11() throws Exception {
parseFull("/** @param {{a : b} n\n*/",
"Bad type annotation. expected closing }");
}
public void testParseRecordType12() throws Exception {
parseFull("/** @param {{!hello : hey}} n\n*/",
"Bad type annotation. type not recognized due to syntax error");
}
public void testParseRecordType13() throws Exception {
parseFull("/** @param {{x}|number} n\n*/");
}
public void testParseRecordType14() throws Exception {
parseFull("/** @param {{x : y}|number} n\n*/");
}
public void testParseRecordType15() throws Exception {
parseFull("/** @param {{'x' : y}|number} n\n*/");
}
public void testParseRecordType16() throws Exception {
parseFull("/** @param {{x, y}|number} n\n*/");
}
public void testParseRecordType17() throws Exception {
parseFull("/** @param {{x : hello, 'y'}|number} n\n*/");
}
public void testParseRecordType18() throws Exception {
parseFull("/** @param {number|{x : hello, 'y'}} n\n*/");
}
public void testParseRecordType19() throws Exception {
parseFull("/** @param {?{x : hello, 'y'}} n\n*/");
}
public void testParseRecordType20() throws Exception {
parseFull("/** @param {!{x : hello, 'y'}} n\n*/");
}
public void testParseRecordType21() throws Exception {
parseFull("/** @param {{x : hello, 'y'}|boolean} n\n*/");
}
public void testParseRecordType22() throws Exception {
parseFull("/** @param {{x : hello, 'y'}|function()} n\n*/");
}
public void testParseRecordType23() throws Exception {
parseFull("/** @param {{x : function(), 'y'}|function()} n\n*/");
}
public void testParseParamError1() throws Exception {
parseFull("/** @param\n*/",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError2() throws Exception {
parseFull("/** @param {Number}*/",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError3() throws Exception {
parseFull("/** @param {Number}\n*/",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError4() throws Exception {
parseFull("/** @param {Number}\n* * num */",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testParseParamError5() throws Exception {
parse("@param {number} x \n * @param {string} x */",
"Bad type annotation. duplicate variable name \"x\"");
}
public void testParseExtends1() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends String*/").getBaseType());
}
public void testParseExtends2() throws Exception {
JSDocInfo info = parse("@extends com.google.Foo.Bar.Hello.World*/");
assertTypeEquals(
registry.createNamedType(
"com.google.Foo.Bar.Hello.World", null, -1, -1),
info.getBaseType());
}
public void testParseExtendsGenerics() throws Exception {
JSDocInfo info =
parse("@extends com.google.Foo.Bar.Hello.World.<Boolean,number>*/");
assertTypeEquals(
registry.createNamedType(
"com.google.Foo.Bar.Hello.World", null, -1, -1),
info.getBaseType());
}
public void testParseImplementsGenerics() throws Exception {
// For types that are not templatized, <> annotations are ignored.
List<JSTypeExpression> interfaces =
parse("@implements {SomeInterface.<*>} */")
.getImplementedInterfaces();
assertEquals(1, interfaces.size());
assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1),
interfaces.get(0));
}
public void testParseExtends4() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends {String}*/").getBaseType());
}
public void testParseExtends5() throws Exception {
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends {String*/",
"Bad type annotation. expected closing }").getBaseType());
}
public void testParseExtends6() throws Exception {
// Multi-line extends
assertTypeEquals(STRING_OBJECT_TYPE,
parse("@extends \n * {String}*/").getBaseType());
}
public void testParseExtendsInvalidName() throws Exception {
// This looks bad, but for the time being it should be OK, as
// we will not find a type with this name in the JS parsed tree.
// If this is fixed in the future, change this test to check for a
// warning/error message.
assertTypeEquals(
registry.createNamedType("some_++#%$%_UglyString", null, -1, -1),
parse("@extends {some_++#%$%_UglyString} */").getBaseType());
}
public void testParseExtendsNullable1() throws Exception {
parse("@extends {Base?} */", "Bad type annotation. expected closing }");
}
public void testParseExtendsNullable2() throws Exception {
parse("@extends Base? */",
"Bad type annotation. expected end of line or comment");
}
public void testParseEnum1() throws Exception {
assertTypeEquals(NUMBER_TYPE, parse("@enum*/").getEnumParameterType());
}
public void testParseEnum2() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@enum {string}*/").getEnumParameterType());
}
public void testParseEnum3() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@enum string*/").getEnumParameterType());
}
public void testParseDesc1() throws Exception {
assertEquals("hello world!",
parse("@desc hello world!*/").getDescription());
}
public void testParseDesc2() throws Exception {
assertEquals("hello world!",
parse("@desc hello world!\n*/").getDescription());
}
public void testParseDesc3() throws Exception {
assertEquals("", parse("@desc*/").getDescription());
}
public void testParseDesc4() throws Exception {
assertEquals("", parse("@desc\n*/").getDescription());
}
public void testParseDesc5() throws Exception {
assertEquals("hello world!",
parse("@desc hello\nworld!\n*/").getDescription());
}
public void testParseDesc6() throws Exception {
assertEquals("hello world!",
parse("@desc hello\n* world!\n*/").getDescription());
}
public void testParseDesc7() throws Exception {
assertEquals("a b c", parse("@desc a\n\nb\nc*/").getDescription());
}
public void testParseDesc8() throws Exception {
assertEquals("a b c d",
parse("@desc a\n *b\n\n *c\n\nd*/").getDescription());
}
public void testParseDesc9() throws Exception {
String comment = "@desc\n.\n,\n{\n)\n}\n|\n.<\n>\n<\n?\n~\n+\n-\n;\n:\n*/";
assertEquals(". , { ) } | .< > < ? ~ + - ; :",
parse(comment).getDescription());
}
public void testParseDesc10() throws Exception {
String comment = "@desc\n?\n?\n?\n?*/";
assertEquals("? ? ? ?", parse(comment).getDescription());
}
public void testParseDesc11() throws Exception {
String comment = "@desc :[]*/";
assertEquals(":[]", parse(comment).getDescription());
}
public void testParseDesc12() throws Exception {
String comment = "@desc\n:\n[\n]\n...*/";
assertEquals(": [ ] ...", parse(comment).getDescription());
}
public void testParseMeaning1() throws Exception {
assertEquals("tigers",
parse("@meaning tigers */").getMeaning());
}
public void testParseMeaning2() throws Exception {
assertEquals("tigers and lions and bears",
parse("@meaning tigers\n * and lions\n * and bears */").getMeaning());
}
public void testParseMeaning3() throws Exception {
JSDocInfo info =
parse("@meaning tigers\n * and lions\n * @desc and bears */");
assertEquals("tigers and lions", info.getMeaning());
assertEquals("and bears", info.getDescription());
}
public void testParseMeaning4() throws Exception {
parse("@meaning tigers\n * @meaning and lions */",
"extra @meaning tag");
}
public void testParseLends1() throws Exception {
JSDocInfo info = parse("@lends {name} */");
assertEquals("name", info.getLendsName());
}
public void testParseLends2() throws Exception {
JSDocInfo info = parse("@lends foo.bar */");
assertEquals("foo.bar", info.getLendsName());
}
public void testParseLends3() throws Exception {
parse("@lends {name */", "Bad type annotation. expected closing }");
}
public void testParseLends4() throws Exception {
parse("@lends {} */",
"Bad type annotation. missing object name in @lends tag");
}
public void testParseLends5() throws Exception {
parse("@lends } */",
"Bad type annotation. missing object name in @lends tag");
}
public void testParseLends6() throws Exception {
parse("@lends {string} \n * @lends {string} */",
"Bad type annotation. @lends tag incompatible with other annotations");
}
public void testParseLends7() throws Exception {
parse("@type {string} \n * @lends {string} */",
"Bad type annotation. @lends tag incompatible with other annotations");
}
public void testParsePreserve() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@preserve Foo\nBar\n\nBaz*/";
parse(comment);
assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense());
}
public void testParseLicense() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@license Foo\nBar\n\nBaz*/";
parse(comment);
assertEquals(" Foo\nBar\n\nBaz", node.getJSDocInfo().getLicense());
}
public void testParseLicenseAscii() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@license Foo\n * Bar\n\n Baz*/";
parse(comment);
assertEquals(" Foo\n Bar\n\n Baz", node.getJSDocInfo().getLicense());
}
public void testParseLicenseWithAnnotation() throws Exception {
Node node = new Node(1);
this.fileLevelJsDocBuilder = node.getJsDocBuilderForNode();
String comment = "@license Foo \n * @author Charlie Brown */";
parse(comment);
assertEquals(" Foo \n @author Charlie Brown ",
node.getJSDocInfo().getLicense());
}
public void testParseDefine1() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@define {string}*/").getType());
}
public void testParseDefine2() throws Exception {
assertTypeEquals(STRING_TYPE,
parse("@define {string*/",
"Bad type annotation. expected closing }").getType());
}
public void testParseDefine3() throws Exception {
JSDocInfo info = parse("@define {boolean}*/");
assertTrue(info.isConstant());
assertTrue(info.isDefine());
assertTypeEquals(BOOLEAN_TYPE, info.getType());
}
public void testParseDefine4() throws Exception {
assertTypeEquals(NUMBER_TYPE, parse("@define {number}*/").getType());
}
public void testParseDefine5() throws Exception {
assertTypeEquals(createUnionType(NUMBER_TYPE, BOOLEAN_TYPE),
parse("@define {number|boolean}*/").getType());
}
public void testParseDefineErrors1() throws Exception {
parse("@enum {string}\n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors2() throws Exception {
parse("@define {string}\n @enum {string} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testParseDefineErrors3() throws Exception {
parse("@const\n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors4() throws Exception {
parse("@type string \n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors5() throws Exception {
parse("@return {string}\n @define {string} */", "conflicting @define tag");
}
public void testParseDefineErrors7() throws Exception {
parse("@define {string}\n @const */", "conflicting @const tag");
}
public void testParseDefineErrors8() throws Exception {
parse("@define {string}\n @type string */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testParseNoCheck1() throws Exception {
assertTrue(parse("@notypecheck*/").isNoTypeCheck());
}
public void testParseNoCheck2() throws Exception {
parse("@notypecheck\n@notypecheck*/", "extra @notypecheck tag");
}
public void testParseOverride1() throws Exception {
assertTrue(parse("@override*/").isOverride());
}
public void testParseOverride2() throws Exception {
parse("@override\n@override*/",
"Bad type annotation. extra @override/@inheritDoc tag");
}
public void testParseInheritDoc1() throws Exception {
assertTrue(parse("@inheritDoc*/").isOverride());
}
public void testParseInheritDoc2() throws Exception {
parse("@override\n@inheritDoc*/",
"Bad type annotation. extra @override/@inheritDoc tag");
}
public void testParseInheritDoc3() throws Exception {
parse("@inheritDoc\n@inheritDoc*/",
"Bad type annotation. extra @override/@inheritDoc tag");
}
public void testParseNoAlias1() throws Exception {
assertTrue(parse("@noalias*/").isNoAlias());
}
public void testParseNoAlias2() throws Exception {
parse("@noalias\n@noalias*/", "extra @noalias tag");
}
public void testParseDeprecated1() throws Exception {
assertTrue(parse("@deprecated*/").isDeprecated());
}
public void testParseDeprecated2() throws Exception {
parse("@deprecated\n@deprecated*/", "extra @deprecated tag");
}
public void testParseExport1() throws Exception {
assertTrue(parse("@export*/").isExport());
}
public void testParseExport2() throws Exception {
parse("@export\n@export*/", "extra @export tag");
}
public void testParseExpose1() throws Exception {
assertTrue(parse("@expose*/").isExpose());
}
public void testParseExpose2() throws Exception {
parse("@expose\n@expose*/", "extra @expose tag");
}
public void testParseExterns1() throws Exception {
assertTrue(parseFileOverview("@externs*/").isExterns());
}
public void testParseExterns2() throws Exception {
parseFileOverview("@externs\n@externs*/", "extra @externs tag");
}
public void testParseExterns3() throws Exception {
assertNull(parse("@externs*/"));
}
public void testParseJavaDispatch1() throws Exception {
assertTrue(parse("@javadispatch*/").isJavaDispatch());
}
public void testParseJavaDispatch2() throws Exception {
parse("@javadispatch\n@javadispatch*/",
"extra @javadispatch tag");
}
public void testParseJavaDispatch3() throws Exception {
assertNull(parseFileOverview("@javadispatch*/"));
}
public void testParseNoCompile1() throws Exception {
assertTrue(parseFileOverview("@nocompile*/").isNoCompile());
}
public void testParseNoCompile2() throws Exception {
parseFileOverview("@nocompile\n@nocompile*/", "extra @nocompile tag");
}
public void testBugAnnotation() throws Exception {
parse("@bug */");
}
public void testDescriptionAnnotation() throws Exception {
parse("@description */");
}
public void testRegression1() throws Exception {
String comment =
" * @param {number} index the index of blah\n" +
" * @return {boolean} whatever\n" +
" * @private\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
assertTypeEquals(BOOLEAN_TYPE, info.getReturnType());
assertEquals(Visibility.PRIVATE, info.getVisibility());
}
public void testRegression2() throws Exception {
String comment =
" * @return {boolean} whatever\n" +
" * but important\n" +
" *\n" +
" * @param {number} index the index of blah\n" +
" * some more comments here\n" +
" * @param name the name of the guy\n" +
" *\n" +
" * @protected\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(2, info.getParameterCount());
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
assertEquals(null, info.getParameterType("name"));
assertTypeEquals(BOOLEAN_TYPE, info.getReturnType());
assertEquals(Visibility.PROTECTED, info.getVisibility());
}
public void testRegression3() throws Exception {
String comment =
" * @param mediaTag this specified whether the @media tag is ....\n" +
" *\n" +
"\n" +
"@public\n" +
" *\n" +
"\n" +
" **********\n" +
" * @final\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertEquals(null, info.getParameterType("mediaTag"));
assertEquals(Visibility.PUBLIC, info.getVisibility());
assertTrue(info.isConstant());
}
public void testRegression4() throws Exception {
String comment =
" * @const\n" +
" * @hidden\n" +
" * @preserveTry\n" +
" * @constructor\n" +
" */";
JSDocInfo info = parse(comment);
assertTrue(info.isConstant());
assertFalse(info.isDefine());
assertTrue(info.isConstructor());
assertTrue(info.isHidden());
assertTrue(info.shouldPreserveTry());
}
public void testRegression5() throws Exception {
String comment = "@const\n@enum {string}\n@public*/";
JSDocInfo info = parse(comment);
assertTrue(info.isConstant());
assertFalse(info.isDefine());
assertTypeEquals(STRING_TYPE, info.getEnumParameterType());
assertEquals(Visibility.PUBLIC, info.getVisibility());
}
public void testRegression6() throws Exception {
String comment = "@hidden\n@enum\n@public*/";
JSDocInfo info = parse(comment);
assertTrue(info.isHidden());
assertTypeEquals(NUMBER_TYPE, info.getEnumParameterType());
assertEquals(Visibility.PUBLIC, info.getVisibility());
}
public void testRegression7() throws Exception {
String comment =
" * @desc description here\n" +
" * @param {boolean} flag and some more description\n" +
" * nicely formatted\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag"));
assertEquals("description here", info.getDescription());
}
public void testRegression8() throws Exception {
String comment =
" * @name random tag here\n" +
" * @desc description here\n" +
" *\n" +
" * @param {boolean} flag and some more description\n" +
" * nicely formatted\n" +
" */";
JSDocInfo info = parse(comment);
assertEquals(1, info.getParameterCount());
assertTypeEquals(BOOLEAN_TYPE, info.getParameterType("flag"));
assertEquals("description here", info.getDescription());
}
public void testRegression9() throws Exception {
JSDocInfo jsdoc = parse(
" * @param {string} p0 blah blah blah\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(1, jsdoc.getParameterCount());
assertTypeEquals(STRING_TYPE, jsdoc.getParameterType("p0"));
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression10() throws Exception {
JSDocInfo jsdoc = parse(
" * @param {!String} p0 blah blah blah\n" +
" * @param {boolean} p1 fobar\n" +
" * @return {!Date} jksjkash dshad\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(2, jsdoc.getParameterCount());
assertTypeEquals(STRING_OBJECT_TYPE, jsdoc.getParameterType("p0"));
assertTypeEquals(BOOLEAN_TYPE, jsdoc.getParameterType("p1"));
assertTypeEquals(DATE_TYPE, jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression11() throws Exception {
JSDocInfo jsdoc = parse(
" * @constructor\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression12() throws Exception {
JSDocInfo jsdoc = parse(
" * @extends FooBar\n" +
" */");
assertTypeEquals(registry.createNamedType("FooBar", null, 0, 0),
jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression13() throws Exception {
JSDocInfo jsdoc = parse(
" * @type {!RegExp}\n" +
" * @protected\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertTypeEquals(REGEXP_TYPE, jsdoc.getType());
assertEquals(Visibility.PROTECTED, jsdoc.getVisibility());
}
public void testRegression14() throws Exception {
JSDocInfo jsdoc = parse(
" * @const\n" +
" * @private\n" +
" */");
assertNull(jsdoc.getBaseType());
assertTrue(jsdoc.isConstant());
assertNull(jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.PRIVATE, jsdoc.getVisibility());
}
public void testRegression15() throws Exception {
JSDocInfo jsdoc = parse(
" * @desc Hello,\n" +
" * World!\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertEquals("Hello, World!", jsdoc.getDescription());
assertNull(jsdoc.getEnumParameterType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertNull(jsdoc.getType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
assertFalse(jsdoc.isExport());
}
public void testRegression16() throws Exception {
JSDocInfo jsdoc = parse(
" Email is plp@foo.bar\n" +
" @type {string}\n" +
" */");
assertNull(jsdoc.getBaseType());
assertFalse(jsdoc.isConstant());
assertTypeEquals(STRING_TYPE, jsdoc.getType());
assertFalse(jsdoc.isHidden());
assertEquals(0, jsdoc.getParameterCount());
assertNull(jsdoc.getReturnType());
assertEquals(Visibility.INHERITED, jsdoc.getVisibility());
}
public void testRegression17() throws Exception {
// verifying that if no @desc is present the description is empty
assertNull(parse("@private*/").getDescription());
}
public void testFullRegression1() throws Exception {
parseFull("/** @param (string,number) foo*/function bar(foo){}",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testFullRegression2() throws Exception {
parseFull("/** @param {string,number) foo*/function bar(foo){}",
"Bad type annotation. expected closing }",
"Bad type annotation. expecting a variable name in a @param tag");
}
public void testFullRegression3() throws Exception {
parseFull("/**..\n*/");
}
public void testBug907488() throws Exception {
parse("@type {number,null} */",
"Bad type annotation. expected closing }");
}
public void testBug907494() throws Exception {
parse("@return {Object,undefined} */",
"Bad type annotation. expected closing }");
}
public void testBug909468() throws Exception {
parse("@extends {(x)}*/",
"Bad type annotation. expecting a type name");
}
public void testParseInterface() throws Exception {
assertTrue(parse("@interface*/").isInterface());
}
public void testParseImplicitCast1() throws Exception {
assertTrue(parse("@type {string} \n * @implicitCast*/").isImplicitCast());
}
public void testParseImplicitCast2() throws Exception {
assertFalse(parse("@type {string}*/").isImplicitCast());
}
public void testParseDuplicateImplicitCast() throws Exception {
parse("@type {string} \n * @implicitCast \n * @implicitCast*/",
"Bad type annotation. extra @implicitCast tag");
}
public void testParseInterfaceDoubled() throws Exception {
parse(
"* @interface\n" +
"* @interface\n" +
"*/",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testParseImplements() throws Exception {
List<JSTypeExpression> interfaces = parse("@implements {SomeInterface}*/")
.getImplementedInterfaces();
assertEquals(1, interfaces.size());
assertTypeEquals(registry.createNamedType("SomeInterface", null, -1, -1),
interfaces.get(0));
}
public void testParseImplementsTwo() throws Exception {
List<JSTypeExpression> interfaces =
parse(
"* @implements {SomeInterface1}\n" +
"* @implements {SomeInterface2}\n" +
"*/")
.getImplementedInterfaces();
assertEquals(2, interfaces.size());
assertTypeEquals(registry.createNamedType("SomeInterface1", null, -1, -1),
interfaces.get(0));
assertTypeEquals(registry.createNamedType("SomeInterface2", null, -1, -1),
interfaces.get(1));
}
public void testParseImplementsSameTwice() throws Exception {
parse(
"* @implements {Smth}\n" +
"* @implements {Smth}\n" +
"*/",
"Bad type annotation. duplicate @implements tag");
}
public void testParseImplementsNoName() throws Exception {
parse("* @implements {} */",
"Bad type annotation. expecting a type name");
}
public void testParseImplementsMissingRC() throws Exception {
parse("* @implements {Smth */",
"Bad type annotation. expected closing }");
}
public void testParseImplementsNullable1() throws Exception {
parse("@implements {Base?} */", "Bad type annotation. expected closing }");
}
public void testParseImplementsNullable2() throws Exception {
parse("@implements Base? */",
"Bad type annotation. expected end of line or comment");
}
public void testInterfaceExtends() throws Exception {
JSDocInfo jsdoc = parse(
" * @interface \n" +
" * @extends {Extended} */");
assertTrue(jsdoc.isInterface());
assertEquals(1, jsdoc.getExtendedInterfacesCount());
List<JSTypeExpression> types = jsdoc.getExtendedInterfaces();
assertTypeEquals(registry.createNamedType("Extended", null, -1, -1),
types.get(0));
}
public void testInterfaceMultiExtends1() throws Exception {
JSDocInfo jsdoc = parse(
" * @interface \n" +
" * @extends {Extended1} \n" +
" * @extends {Extended2} */");
assertTrue(jsdoc.isInterface());
assertNull(jsdoc.getBaseType());
assertEquals(2, jsdoc.getExtendedInterfacesCount());
List<JSTypeExpression> types = jsdoc.getExtendedInterfaces();
assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1),
types.get(0));
assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1),
types.get(1));
}
public void testInterfaceMultiExtends2() throws Exception {
JSDocInfo jsdoc = parse(
" * @extends {Extended1} \n" +
" * @interface \n" +
" * @extends {Extended2} \n" +
" * @extends {Extended3} */");
assertTrue(jsdoc.isInterface());
assertNull(jsdoc.getBaseType());
assertEquals(3, jsdoc.getExtendedInterfacesCount());
List<JSTypeExpression> types = jsdoc.getExtendedInterfaces();
assertTypeEquals(registry.createNamedType("Extended1", null, -1, -1),
types.get(0));
assertTypeEquals(registry.createNamedType("Extended2", null, -1, -1),
types.get(1));
assertTypeEquals(registry.createNamedType("Extended3", null, -1, -1),
types.get(2));
}
public void testBadClassMultiExtends() throws Exception {
parse(" * @extends {Extended1} \n" +
" * @constructor \n" +
" * @extends {Extended2} */",
"Bad type annotation. type annotation incompatible with other " +
"annotations");
}
public void testBadExtendsWithNullable() throws Exception {
JSDocInfo jsdoc = parse("@constructor\n * @extends {Object?} */",
"Bad type annotation. expected closing }");
assertTrue(jsdoc.isConstructor());
assertTypeEquals(OBJECT_TYPE, jsdoc.getBaseType());
}
public void testBadImplementsWithNullable() throws Exception {
JSDocInfo jsdoc = parse("@implements {Disposable?}\n * @constructor */",
"Bad type annotation. expected closing }");
assertTrue(jsdoc.isConstructor());
assertTypeEquals(registry.createNamedType("Disposable", null, -1, -1),
jsdoc.getImplementedInterfaces().get(0));
}
public void testBadTypeDefInterfaceAndConstructor1() throws Exception {
JSDocInfo jsdoc = parse("@interface\n@constructor*/",
"Bad type annotation. cannot be both an interface and a constructor");
assertTrue(jsdoc.isInterface());
}
public void testBadTypeDefInterfaceAndConstructor2() throws Exception {
JSDocInfo jsdoc = parse("@constructor\n@interface*/",
"Bad type annotation. cannot be both an interface and a constructor");
assertTrue(jsdoc.isConstructor());
}
public void testDocumentationParameter() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description.*/", true);
assertTrue(jsdoc.hasDescriptionForParameter("number42"));
assertEquals("This is a description.",
jsdoc.getDescriptionForParameter("number42"));
}
public void testMultilineDocumentationParameter() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description"
+ "\n* on multiple \n* lines.*/", true);
assertTrue(jsdoc.hasDescriptionForParameter("number42"));
assertEquals("This is a description on multiple lines.",
jsdoc.getDescriptionForParameter("number42"));
}
public void testDocumentationMultipleParameter() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description."
+ "\n* @param {Integer} number87 This is another description.*/"
, true);
assertTrue(jsdoc.hasDescriptionForParameter("number42"));
assertEquals("This is a description.",
jsdoc.getDescriptionForParameter("number42"));
assertTrue(jsdoc.hasDescriptionForParameter("number87"));
assertEquals("This is another description.",
jsdoc.getDescriptionForParameter("number87"));
}
public void testDocumentationMultipleParameter2() throws Exception {
JSDocInfo jsdoc
= parse("@param {number} delta = 0 results in a redraw\n" +
" != 0 ..... */", true);
assertTrue(jsdoc.hasDescriptionForParameter("delta"));
assertEquals("= 0 results in a redraw != 0 .....",
jsdoc.getDescriptionForParameter("delta"));
}
public void testAuthors() throws Exception {
JSDocInfo jsdoc
= parse("@param {Number} number42 This is a description."
+ "\n* @param {Integer} number87 This is another description."
+ "\n* @author a@google.com (A Person)"
+ "\n* @author b@google.com (B Person)"
+ "\n* @author c@google.com (C Person)*/"
, true);
Collection<String> authors = jsdoc.getAuthors();
assertTrue(authors != null);
assertTrue(authors.size() == 3);
assertContains(authors, "a@google.com (A Person)");
assertContains(authors, "b@google.com (B Person)");
assertContains(authors, "c@google.com (C Person)");
}
public void testSuppress1() throws Exception {
JSDocInfo info = parse("@suppress {x} */");
assertEquals(Sets.newHashSet("x"), info.getSuppressions());
}
public void testSuppress2() throws Exception {
JSDocInfo info = parse("@suppress {x|y|x|z} */");
assertEquals(Sets.newHashSet("x", "y", "z"), info.getSuppressions());
}
public void testBadSuppress1() throws Exception {
parse("@suppress {} */", "malformed @suppress tag");
}
public void testBadSuppress2() throws Exception {
parse("@suppress {x|} */", "malformed @suppress tag");
}
public void testBadSuppress3() throws Exception {
parse("@suppress {|x} */", "malformed @suppress tag");
}
public void testBadSuppress4() throws Exception {
parse("@suppress {x|y */", "malformed @suppress tag");
}
public void testBadSuppress5() throws Exception {
parse("@suppress {x,y} */", "malformed @suppress tag");
}
public void testBadSuppress6() throws Exception {
parse("@suppress {x} \n * @suppress {y} */", "duplicate @suppress tag");
}
public void testBadSuppress7() throws Exception {
parse("@suppress {impossible} */",
"unknown @suppress parameter: impossible");
}
public void testModifies1() throws Exception {
JSDocInfo info = parse("@modifies {this} */");
assertEquals(Sets.newHashSet("this"), info.getModifies());
}
public void testModifies2() throws Exception {
JSDocInfo info = parse("@modifies {arguments} */");
assertEquals(Sets.newHashSet("arguments"), info.getModifies());
}
public void testModifies3() throws Exception {
JSDocInfo info = parse("@modifies {this|arguments} */");
assertEquals(Sets.newHashSet("this", "arguments"), info.getModifies());
}
public void testModifies4() throws Exception {
JSDocInfo info = parse("@param {*} x\n * @modifies {x} */");
assertEquals(Sets.newHashSet("x"), info.getModifies());
}
public void testModifies5() throws Exception {
JSDocInfo info = parse(
"@param {*} x\n"
+ " * @param {*} y\n"
+ " * @modifies {x} */");
assertEquals(Sets.newHashSet("x"), info.getModifies());
}
public void testModifies6() throws Exception {
JSDocInfo info = parse(
"@param {*} x\n"
+ " * @param {*} y\n"
+ " * @modifies {x|y} */");
assertEquals(Sets.newHashSet("x", "y"), info.getModifies());
}
public void testBadModifies1() throws Exception {
parse("@modifies {} */", "malformed @modifies tag");
}
public void testBadModifies2() throws Exception {
parse("@modifies {this|} */", "malformed @modifies tag");
}
public void testBadModifies3() throws Exception {
parse("@modifies {|this} */", "malformed @modifies tag");
}
public void testBadModifies4() throws Exception {
parse("@modifies {this|arguments */", "malformed @modifies tag");
}
public void testBadModifies5() throws Exception {
parse("@modifies {this,arguments} */", "malformed @modifies tag");
}
public void testBadModifies6() throws Exception {
parse("@modifies {this} \n * @modifies {this} */",
"conflicting @modifies tag");
}
public void testBadModifies7() throws Exception {
parse("@modifies {impossible} */",
"unknown @modifies parameter: impossible");
}
public void testBadModifies8() throws Exception {
parse("@modifies {this}\n"
+ "@nosideeffects */", "conflicting @nosideeffects tag");
}
public void testBadModifies9() throws Exception {
parse("@nosideeffects\n"
+ "@modifies {this} */", "conflicting @modifies tag");
}
//public void testNoParseFileOverview() throws Exception {
// JSDocInfo jsdoc = parseFileOverviewWithoutDoc("@fileoverview Hi mom! */");
// assertNull(jsdoc.getFileOverview());
// assertTrue(jsdoc.hasFileOverview());
//}
public void testFileOverviewSingleLine() throws Exception {
JSDocInfo jsdoc = parseFileOverview("@fileoverview Hi mom! */");
assertEquals("Hi mom!", jsdoc.getFileOverview());
}
public void testFileOverviewMultiLine() throws Exception {
JSDocInfo jsdoc = parseFileOverview("@fileoverview Pie is \n * good! */");
assertEquals("Pie is\n good!", jsdoc.getFileOverview());
}
public void testFileOverviewDuplicate() throws Exception {
parseFileOverview(
"@fileoverview Pie \n * @fileoverview Cake */",
"extra @fileoverview tag");
}
public void testReferences() throws Exception {
JSDocInfo jsdoc
= parse("@see A cool place!"
+ "\n* @see The world."
+ "\n* @see SomeClass#SomeMember"
+ "\n* @see A boring test case*/"
, true);
Collection<String> references = jsdoc.getReferences();
assertTrue(references != null);
assertTrue(references.size() == 4);
assertContains(references, "A cool place!");
assertContains(references, "The world.");
assertContains(references, "SomeClass#SomeMember");
assertContains(references, "A boring test case");
}
public void testSingleTags() throws Exception {
JSDocInfo jsdoc
= parse("@version Some old version"
+ "\n* @deprecated In favor of the new one!"
+ "\n* @return {SomeType} The most important object :-)*/"
, true);
assertTrue(jsdoc.isDeprecated());
assertEquals("In favor of the new one!", jsdoc.getDeprecationReason());
assertEquals("Some old version", jsdoc.getVersion());
assertEquals("The most important object :-)", jsdoc.getReturnDescription());
}
public void testSingleTagsReordered() throws Exception {
JSDocInfo jsdoc
= parse("@deprecated In favor of the new one!"
+ "\n * @return {SomeType} The most important object :-)"
+ "\n * @version Some old version*/"
, true);
assertTrue(jsdoc.isDeprecated());
assertEquals("In favor of the new one!", jsdoc.getDeprecationReason());
assertEquals("Some old version", jsdoc.getVersion());
assertEquals("The most important object :-)", jsdoc.getReturnDescription());
}
public void testVersionDuplication() throws Exception {
parse("* @version Some old version"
+ "\n* @version Another version*/", true,
"conflicting @version tag");
}
public void testVersionMissing() throws Exception {
parse("* @version */", true,
"@version tag missing version information");
}
public void testAuthorMissing() throws Exception {
parse("* @author */", true,
"@author tag missing author");
}
public void testSeeMissing() throws Exception {
parse("* @see */", true,
"@see tag missing description");
}
public void testSourceName() throws Exception {
JSDocInfo jsdoc = parse("@deprecated */", true);
assertEquals("testcode", jsdoc.getAssociatedNode().getSourceFileName());
}
public void testParseBlockComment() throws Exception {
JSDocInfo jsdoc = parse("this is a nice comment\n "
+ "* that is multiline \n"
+ "* @author abc@google.com */", true);
assertEquals("this is a nice comment\nthat is multiline",
jsdoc.getBlockDescription());
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 2, 2),
"abc@google.com", 9, 2, 23);
}
public void testParseBlockComment2() throws Exception {
JSDocInfo jsdoc = parse("this is a nice comment\n "
+ "* that is *** multiline \n"
+ "* @author abc@google.com */", true);
assertEquals("this is a nice comment\nthat is *** multiline",
jsdoc.getBlockDescription());
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 2, 2),
"abc@google.com", 9, 2, 23);
}
public void testParseBlockComment3() throws Exception {
JSDocInfo jsdoc = parse("\n "
+ "* hello world \n"
+ "* @author abc@google.com */", true);
assertEquals("hello world", jsdoc.getBlockDescription());
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 2, 2),
"abc@google.com", 9, 2, 23);
}
public void testParseWithMarkers1() throws Exception {
JSDocInfo jsdoc = parse("@author abc@google.com */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "author", 0, 0),
"abc@google.com", 7, 0, 21);
}
public void testParseWithMarkers2() throws Exception {
JSDocInfo jsdoc = parse("@param {Foo} somename abc@google.com */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0),
"abc@google.com", 21, 0, 37);
}
public void testParseWithMarkers3() throws Exception {
JSDocInfo jsdoc =
parse("@return {Foo} some long \n * multiline" +
" \n * description */", true);
JSDocInfo.Marker returnDoc =
assertAnnotationMarker(jsdoc, "return", 0, 0);
assertDocumentationInMarker(returnDoc,
"some long multiline description", 13, 2, 15);
assertEquals(8, returnDoc.getType().getPositionOnStartLine());
assertEquals(12, returnDoc.getType().getPositionOnEndLine());
}
public void testParseWithMarkers4() throws Exception {
JSDocInfo jsdoc =
parse("@author foobar \n * @param {Foo} somename abc@google.com */",
true);
assertAnnotationMarker(jsdoc, "author", 0, 0);
assertAnnotationMarker(jsdoc, "param", 1, 3);
}
public void testParseWithMarkers5() throws Exception {
JSDocInfo jsdoc =
parse("@return some long \n * multiline" +
" \n * description */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "return", 0, 0),
"some long multiline description", 8, 2, 15);
}
public void testParseWithMarkers6() throws Exception {
JSDocInfo jsdoc =
parse("@param x some long \n * multiline" +
" \n * description */", true);
assertDocumentationInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0),
"some long multiline description", 8, 2, 15);
}
public void testParseWithMarkerNames1() throws Exception {
JSDocInfo jsdoc = parse("@param {SomeType} name somedescription */", true);
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0),
"name", 0, 18);
}
public void testParseWithMarkerNames2() throws Exception {
JSDocInfo jsdoc = parse("@param {SomeType} name somedescription \n" +
"* @param {AnotherType} anothername des */", true);
assertTypeInMarker(
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0, 0),
"name", 0, 18),
"SomeType", 0, 7, 0, 16, true);
assertTypeInMarker(
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 1, 2, 1),
"anothername", 1, 23),
"AnotherType", 1, 9, 1, 21, true);
}
public void testParseWithMarkerNames3() throws Exception {
JSDocInfo jsdoc = parse(
"@param {Some.Long.Type.\n * Name} name somedescription */", true);
assertTypeInMarker(
assertNameInMarker(
assertAnnotationMarker(jsdoc, "param", 0, 0, 0),
"name", 1, 10),
"Some.Long.Type.Name", 0, 7, 1, 8, true);
}
@SuppressWarnings("deprecation")
public void testParseWithoutMarkerName() throws Exception {
JSDocInfo jsdoc = parse("@author helloworld*/", true);
assertNull(assertAnnotationMarker(jsdoc, "author", 0, 0).getName());
}
public void testParseWithMarkerType() throws Exception {
JSDocInfo jsdoc = parse("@extends {FooBar}*/", true);
assertTypeInMarker(
assertAnnotationMarker(jsdoc, "extends", 0, 0),
"FooBar", 0, 9, 0, 16, true);
}
public void testParseWithMarkerType2() throws Exception {
JSDocInfo jsdoc = parse("@extends FooBar*/", true);
assertTypeInMarker(
assertAnnotationMarker(jsdoc, "extends", 0, 0),
"FooBar", 0, 9, 0, 15, false);
}
public void testTypeTagConflict1() throws Exception {
parse("@constructor \n * @constructor */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict2() throws Exception {
parse("@interface \n * @interface */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict3() throws Exception {
parse("@constructor \n * @interface */",
"Bad type annotation. cannot be both an interface and a constructor");
}
public void testTypeTagConflict4() throws Exception {
parse("@interface \n * @constructor */",
"Bad type annotation. cannot be both an interface and a constructor");
}
public void testTypeTagConflict5() throws Exception {
parse("@interface \n * @type {string} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict6() throws Exception {
parse("@typedef {string} \n * @type {string} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict7() throws Exception {
parse("@typedef {string} \n * @constructor */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict8() throws Exception {
parse("@typedef {string} \n * @return {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict9() throws Exception {
parse("@enum {string} \n * @return {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict10() throws Exception {
parse("@this {Object} \n * @enum {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict11() throws Exception {
parse("@param {Object} x \n * @type {boolean} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict12() throws Exception {
parse("@typedef {boolean} \n * @param {Object} x */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict13() throws Exception {
parse("@typedef {boolean} \n * @extends {Object} */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict14() throws Exception {
parse("@return x \n * @return y */",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict15() throws Exception {
parse("/**\n" +
" * @struct\n" +
" * @struct\n" +
" */\n" +
"function StrStr() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict16() throws Exception {
parse("/**\n" +
" * @struct\n" +
" * @interface\n" +
" */\n" +
"function StrIntf() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict17() throws Exception {
parse("/**\n" +
" * @interface\n" +
" * @struct\n" +
" */\n" +
"function StrIntf() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict18() throws Exception {
parse("/**\n" +
" * @dict\n" +
" * @dict\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict19() throws Exception {
parse("/**\n" +
" * @dict\n" +
" * @interface\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict20() throws Exception {
parse("/**\n" +
" * @interface\n" +
" * @dict\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict21() throws Exception {
parse("/**\n" +
" * @private {string}\n" +
" * @type {number}\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict22() throws Exception {
parse("/**\n" +
" * @protected {string}\n" +
" * @param {string} x\n" +
" */\n" +
"function DictDict(x) {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict23() throws Exception {
parse("/**\n" +
" * @public {string}\n" +
" * @return {string} x\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testTypeTagConflict24() throws Exception {
parse("/**\n" +
" * @const {string}\n" +
" * @return {string} x\n" +
" */\n" +
"function DictDict() {}",
"Bad type annotation. " +
"type annotation incompatible with other annotations");
}
public void testPrivateType() throws Exception {
JSDocInfo jsdoc = parse("@private {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testProtectedType() throws Exception {
JSDocInfo jsdoc = parse("@protected {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testPublicType() throws Exception {
JSDocInfo jsdoc = parse("@public {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testConstType() throws Exception {
JSDocInfo jsdoc = parse("@const {string} */");
assertTypeEquals(STRING_TYPE, jsdoc.getType());
}
public void testStableIdGeneratorConflict() throws Exception {
parse("/**\n" +
" * @stableIdGenerator\n" +
" * @stableIdGenerator\n" +
" */\n" +
"function getId() {}",
"extra @stableIdGenerator tag");
}
public void testParserWithTemplateTypeNameMissing() {
parse("@template */",
"Bad type annotation. @template tag missing type name");
}
public void testParserWithTemplateDuplicated() {
parse("@template T\n@template V */",
"Bad type annotation. @template tag at most once");
}
public void testParserWithTwoTemplates() {
parse("@template T,V */");
}
public void testParserWithClassTemplateTypeNameMissing() {
parse("@classTemplate */",
"Bad type annotation. @classTemplate tag missing type name");
}
public void testParserWithClassTemplateDuplicated() {
parse("@classTemplate T\n@classTemplate V */",
"Bad type annotation. @classTemplate tag at most once");
}
public void testParserWithTwoClassTemplates() {
parse("@classTemplate T,V */");
}
public void testParserWithClassTemplatesAndTemplate() {
parse("@template T\n@classTemplate T,V */");
}
public void testWhitelistedNewAnnotations() {
parse("@foobar */",
"illegal use of unknown JSDoc tag \"foobar\"; ignoring it");
extraAnnotations.add("foobar");
parse("@foobar */");
}
public void testWhitelistedConflictingAnnotation() {
extraAnnotations.add("param");
JSDocInfo info = parse("@param {number} index */");
assertTypeEquals(NUMBER_TYPE, info.getParameterType("index"));
}
public void testNonIdentifierAnnotation() {
// Try to whitelist an annotation that is not a valid JS identifier.
// It should not work.
extraAnnotations.add("123");
parse("@123 */", "illegal use of unknown JSDoc tag \"\"; ignoring it");
}
public void testUnsupportedJsDocSyntax1() {
JSDocInfo info =
parse("@param {string} [accessLevel=\"author\"] The user level */",
true);
assertEquals(1, info.getParameterCount());
assertTypeEquals(
registry.createOptionalType(STRING_TYPE),
info.getParameterType("accessLevel"));
assertEquals("The user level",
info.getDescriptionForParameter("accessLevel"));
}
public void testUnsupportedJsDocSyntax2() {
JSDocInfo info =
parse("@param userInfo The user info. \n" +
" * @param userInfo.name The name of the user */", true);
assertEquals(1, info.getParameterCount());
assertEquals("The user info.",
info.getDescriptionForParameter("userInfo"));
}
public void testWhitelistedAnnotations() {
parse(
"* @addon \n" +
"* @ngInject \n" +
"* @augments \n" +
"* @base \n" +
"* @borrows \n" +
"* @bug \n" +
"* @class \n" +
"* @config \n" +
"* @constructs \n" +
"* @default \n" +
"* @description \n" +
"* @event \n" +
"* @example \n" +
"* @exception \n" +
"* @exec \n" +
"* @externs \n" +
"* @field \n" +
"* @function \n" +
"* @id \n" +
"* @ignore \n" +
"* @inner \n" +
"* @lends {string} \n" +
"* @link \n" +
"* @member \n" +
"* @memberOf \n" +
"* @modName \n" +
"* @mods \n" +
"* @name \n" +
"* @namespace \n" +
"* @nocompile \n" +
"* @property \n" +
"* @requires \n" +
"* @since \n" +
"* @static \n" +
"* @supported */");
}
public void testGetOriginalCommentString() throws Exception {
String comment = "* @desc This is a comment */";
JSDocInfo info = parse(comment);
assertNull(info.getOriginalCommentString());
info = parse(comment, true /* parseDocumentation */);
assertEquals(comment, info.getOriginalCommentString());
}
public void testParseNgInject1() throws Exception {
assertTrue(parse("@ngInject*/").isNgInject());
}
public void testParseNgInject2() throws Exception {
parse("@ngInject \n@ngInject*/", "extra @ngInject tag");
}
public void testTextExtents() {
parse("@return {@code foo} bar \n * baz. */",
true, "Bad type annotation. type not recognized due to syntax error");
}
/**
* Asserts that a documentation field exists on the given marker.
*
* @param description The text of the documentation field expected.
* @param startCharno The starting character of the text.
* @param endLineno The ending line of the text.
* @param endCharno The ending character of the text.
* @return The marker, for chaining purposes.
*/
private JSDocInfo.Marker assertDocumentationInMarker(JSDocInfo.Marker marker,
String description,
int startCharno,
int endLineno,
int endCharno) {
assertTrue(marker.getDescription() != null);
assertEquals(description, marker.getDescription().getItem());
// Match positional information.
assertEquals(marker.getAnnotation().getStartLine(),
marker.getDescription().getStartLine());
assertEquals(startCharno, marker.getDescription().getPositionOnStartLine());
assertEquals(endLineno, marker.getDescription().getEndLine());
assertEquals(endCharno, marker.getDescription().getPositionOnEndLine());
return marker;
}
/**
* Asserts that a type field exists on the given marker.
*
* @param typeName The name of the type expected in the type field.
* @param startCharno The starting character of the type declaration.
* @param hasBrackets Whether the type in the type field is expected
* to have brackets.
* @return The marker, for chaining purposes.
*/
private JSDocInfo.Marker assertTypeInMarker(
JSDocInfo.Marker marker, String typeName,
int startLineno, int startCharno, int endLineno, int endCharno,
boolean hasBrackets) {
assertTrue(marker.getType() != null);
assertTrue(marker.getType().getItem().isString());
// Match the name and brackets information.
String foundName = marker.getType().getItem().getString();
assertEquals(typeName, foundName);
assertEquals(hasBrackets, marker.getType().hasBrackets());
// Match position information.
assertEquals(startCharno, marker.getType().getPositionOnStartLine());
assertEquals(endCharno, marker.getType().getPositionOnEndLine());
assertEquals(startLineno, marker.getType().getStartLine());
assertEquals(endLineno, marker.getType().getEndLine());
return marker;
}
/**
* Asserts that a name field exists on the given marker.
*
* @param name The name expected in the name field.
* @param startCharno The starting character of the text.
* @return The marker, for chaining purposes.
*/
@SuppressWarnings("deprecation")
private JSDocInfo.Marker assertNameInMarker(JSDocInfo.Marker marker,
String name, int startLine, int startCharno) {
assertTrue(marker.getName() != null);
assertEquals(name, marker.getName().getItem());
assertEquals(startCharno, marker.getName().getPositionOnStartLine());
assertEquals(startCharno + name.length(),
marker.getName().getPositionOnEndLine());
assertEquals(startLine, marker.getName().getStartLine());
assertEquals(startLine, marker.getName().getEndLine());
return marker;
}
/**
* Asserts that an annotation marker of a given annotation name
* is found in the given JSDocInfo.
*
* @param jsdoc The JSDocInfo in which to search for the annotation marker.
* @param annotationName The name/type of the annotation for which to
* search. Example: "author" for an "@author" annotation.
* @param startLineno The expected starting line number of the marker.
* @param startCharno The expected character on the starting line.
* @return The marker found, for further testing.
*/
private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc,
String annotationName,
int startLineno,
int startCharno) {
return assertAnnotationMarker(jsdoc, annotationName, startLineno,
startCharno, 0);
}
/**
* Asserts that the index-th annotation marker of a given annotation name
* is found in the given JSDocInfo.
*
* @param jsdoc The JSDocInfo in which to search for the annotation marker.
* @param annotationName The name/type of the annotation for which to
* search. Example: "author" for an "@author" annotation.
* @param startLineno The expected starting line number of the marker.
* @param startCharno The expected character on the starting line.
* @param index The index of the marker.
* @return The marker found, for further testing.
*/
private JSDocInfo.Marker assertAnnotationMarker(JSDocInfo jsdoc,
String annotationName,
int startLineno,
int startCharno,
int index) {
Collection<JSDocInfo.Marker> markers = jsdoc.getMarkers();
assertTrue(markers.size() > 0);
int counter = 0;
for (JSDocInfo.Marker marker : markers) {
if (marker.getAnnotation() != null) {
if (annotationName.equals(marker.getAnnotation().getItem())) {
if (counter == index) {
assertEquals(startLineno, marker.getAnnotation().getStartLine());
assertEquals(startCharno,
marker.getAnnotation().getPositionOnStartLine());
assertEquals(startLineno, marker.getAnnotation().getEndLine());
assertEquals(startCharno + annotationName.length(),
marker.getAnnotation().getPositionOnEndLine());
return marker;
}
counter++;
}
}
}
fail("No marker found");
return null;
}
private <T> void assertContains(Collection<T> collection, T item) {
assertTrue(collection.contains(item));
}
private void parseFull(String code, String... warnings) {
CompilerEnvirons environment = new CompilerEnvirons();
TestErrorReporter testErrorReporter = new TestErrorReporter(null, warnings);
environment.setErrorReporter(testErrorReporter);
environment.setRecordingComments(true);
environment.setRecordingLocalJsDocComments(true);
Parser p = new Parser(environment, testErrorReporter);
AstRoot script = p.parse(code, null, 0);
Config config =
new Config(extraAnnotations, extraSuppressions,
true, LanguageMode.ECMASCRIPT3, false);
for (Comment comment : script.getComments()) {
JsDocInfoParser jsdocParser =
new JsDocInfoParser(
new JsDocTokenStream(comment.getValue().substring(3),
comment.getLineno()),
comment,
null,
config,
testErrorReporter);
jsdocParser.parse();
jsdocParser.retrieveAndResetParsedJSDocInfo();
}
assertTrue("some expected warnings were not reported",
testErrorReporter.hasEncounteredAllWarnings());
}
@SuppressWarnings("unused")
private JSDocInfo parseFileOverviewWithoutDoc(String comment,
String... warnings) {
return parse(comment, false, true, warnings);
}
private JSDocInfo parseFileOverview(String comment, String... warnings) {
return parse(comment, true, true, warnings);
}
private JSDocInfo parse(String comment, String... warnings) {
return parse(comment, false, warnings);
}
private JSDocInfo parse(String comment, boolean parseDocumentation,
String... warnings) {
return parse(comment, parseDocumentation, false, warnings);
}
private JSDocInfo parse(String comment, boolean parseDocumentation,
boolean parseFileOverview, String... warnings) {
TestErrorReporter errorReporter = new TestErrorReporter(null, warnings);
Config config = new Config(extraAnnotations, extraSuppressions,
parseDocumentation, LanguageMode.ECMASCRIPT3, false);
StaticSourceFile file = new SimpleSourceFile("testcode", false);
Node associatedNode = new Node(Token.SCRIPT);
associatedNode.setInputId(new InputId(file.getName()));
associatedNode.setStaticSourceFile(file);
JsDocInfoParser jsdocParser = new JsDocInfoParser(
stream(comment),
new Comment(0, 0, CommentType.JSDOC, comment),
associatedNode,
config, errorReporter);
if (fileLevelJsDocBuilder != null) {
jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder);
}
jsdocParser.parse();
assertTrue("expected warnings were not reported",
errorReporter.hasEncounteredAllWarnings());
if (parseFileOverview) {
return jsdocParser.getFileOverviewJSDocInfo();
} else {
return jsdocParser.retrieveAndResetParsedJSDocInfo();
}
}
private Node parseType(String typeComment) {
return JsDocInfoParser.parseTypeString(typeComment);
}
private JsDocTokenStream stream(String source) {
return new JsDocTokenStream(source, 0);
}
private void assertTemplatizedTypeEquals(String key, JSType expected,
JSTypeExpression te) {
assertEquals(
expected, resolve(te).getTemplateTypeMap().getTemplateType(key));
}
} |
||
@Test
public void testMath781() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 6, 7 }, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 2, 1 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { -1, 1, 1 }, Relationship.LEQ, -1));
constraints.add(new LinearConstraint(new double[] { 2, -3, 1 }, Relationship.LEQ, -1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[2], 0.0d, epsilon) < 0);
Assert.assertEquals(2.0d, solution.getValue(), epsilon);
} | org.apache.commons.math3.optimization.linear.SimplexSolverTest::testMath781 | src/test/java/org/apache/commons/math3/optimization/linear/SimplexSolverTest.java | 48 | src/test/java/org/apache/commons/math3/optimization/linear/SimplexSolverTest.java | testMath781 | /*
* 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.linear;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.math3.optimization.GoalType;
import org.apache.commons.math3.optimization.PointValuePair;
import org.apache.commons.math3.util.Precision;
import org.junit.Test;
public class SimplexSolverTest {
@Test
public void testMath781() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 6, 7 }, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 2, 1 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { -1, 1, 1 }, Relationship.LEQ, -1));
constraints.add(new LinearConstraint(new double[] { 2, -3, 1 }, Relationship.LEQ, -1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[2], 0.0d, epsilon) < 0);
Assert.assertEquals(2.0d, solution.getValue(), epsilon);
}
@Test
public void testMath713NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {1, 0}, Relationship.EQ, 1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) >= 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) >= 0);
}
@Test
public void testMath434NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0, 0.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {1, 1, 0}, Relationship.EQ, 5));
constraints.add(new LinearConstraint(new double[] {0, 0, 1}, Relationship.GEQ, -10));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertEquals(5.0, solution.getPoint()[0] + solution.getPoint()[1], epsilon);
Assert.assertEquals(-10.0, solution.getPoint()[2], epsilon);
Assert.assertEquals(-10.0, solution.getValue(), epsilon);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testMath434UnfeasibleSolution() {
double epsilon = 1e-6;
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 0.0}, 0.0);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {epsilon/2, 0.5}, Relationship.EQ, 0));
constraints.add(new LinearConstraint(new double[] {1e-3, 0.1}, Relationship.EQ, 10));
SimplexSolver solver = new SimplexSolver();
// allowing only non-negative values, no feasible solution shall be found
solver.optimize(f, constraints, GoalType.MINIMIZE, true);
}
@Test
public void testMath434PivotRowSelection() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0}, 0.0);
double epsilon = 1e-6;
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {200}, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] {100}, Relationship.GEQ, 0.499900001));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0] * 200.d, 1.d, epsilon) >= 0);
Assert.assertEquals(0.0050, solution.getValue(), epsilon);
}
@Test
public void testMath434PivotRowSelection2() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {1.0d, -0.1d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.EQ, -0.1d));
constraints.add(new LinearConstraint(new double[] {1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, -1e-18d));
constraints.add(new LinearConstraint(new double[] {0.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 1.0d, 0.0d, -0.0128588d, 1e-5d}, Relationship.EQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 0.0d, 1.0d, 1e-5d, -0.0128586d}, Relationship.EQ, 1e-10d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, -1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, -1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, 1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
double epsilon = 1e-7;
SimplexSolver simplex = new SimplexSolver();
PointValuePair solution = simplex.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], -1e-18d, epsilon) >= 0);
Assert.assertEquals(1.0d, solution.getPoint()[1], epsilon);
Assert.assertEquals(0.0d, solution.getPoint()[2], epsilon);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
}
@Test
public void testMath272() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertEquals(0.0, solution.getPoint()[0], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[1], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(3.0, solution.getValue(), .0000001);
}
@Test
public void testMath286() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(25.8, solution.getValue(), .0000001);
Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001);
Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001);
Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001);
}
@Test
public void testDegeneracy() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0));
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(13.6, solution.getValue(), .0000001);
}
@Test
public void testMath288() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(10.0, solution.getValue(), .0000001);
}
@Test
public void testMath290GEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertEquals(0, solution.getValue(), .0000001);
Assert.assertEquals(0, solution.getPoint()[0], .0000001);
Assert.assertEquals(0, solution.getPoint()[1], .0000001);
}
@Test(expected=NoFeasibleSolutionException.class)
public void testMath290LEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MINIMIZE, true);
}
@Test
public void testMath293() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution1 = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[1], .0001);
Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[3], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[4], .0001);
Assert.assertEquals(30.0, solution1.getPoint()[5], .0001);
Assert.assertEquals(40.57143, solution1.getValue(), .0001);
double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1];
double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3];
double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5];
f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC));
PointValuePair solution2 = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(40.57143, solution2.getValue(), .0001);
}
@Test
public void testSimplexSolver() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 15, 10 }, 7);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(57.0, solution.getValue(), 0.0);
}
@Test
public void testSingleVariableAndConstraint() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(10.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(30.0, solution.getValue(), 0.0);
}
/**
* With no artificial variables needed (no equals and no greater than
* constraints) we can go straight to Phase 2.
*/
@Test
public void testModelWithNoArtificialVars() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(50.0, solution.getValue(), 0.0);
}
@Test
public void testMinimization() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6));
constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertEquals(4.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(-13.0, solution.getValue(), 0.0);
}
@Test
public void testSolutionWithNegativeDecisionVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6));
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(8.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(12.0, solution.getValue(), 0.0);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testInfeasibleSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
}
@Test(expected = UnboundedSolutionException.class)
public void testUnboundedSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
}
@Test
public void testRestrictVariablesToNonNegative() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456));
constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454));
constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421));
constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356));
constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001);
Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[3], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[4], .0000001);
Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001);
}
@Test
public void testEpsilon() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17));
constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7));
constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(1.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(1.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[2], 0.0);
Assert.assertEquals(15.0, solution.getValue(), 0.0);
}
@Test
public void testTrivialModel() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(0, solution.getValue(), .0000001);
}
@Test
public void testLargeModel() {
double[] objective = new double[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 12, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 12, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1};
LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49"));
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x192 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x205 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x206 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x207 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x208 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x209 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x211 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x212 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x213 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x214 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x215 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x192 = 0"));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertEquals(7518.0, solution.getValue(), .0000001);
}
/**
* Converts a test string to a {@link LinearConstraint}.
* Ex: x0 + x1 + x2 + x3 - x12 = 0
*/
private LinearConstraint equationFromString(int numCoefficients, String s) {
Relationship relationship;
if (s.contains(">=")) {
relationship = Relationship.GEQ;
} else if (s.contains("<=")) {
relationship = Relationship.LEQ;
} else if (s.contains("=")) {
relationship = Relationship.EQ;
} else {
throw new IllegalArgumentException();
}
String[] equationParts = s.split("[>|<]?=");
double rhs = Double.parseDouble(equationParts[1].trim());
double[] lhs = new double[numCoefficients];
String left = equationParts[0].replaceAll(" ?x", "");
String[] coefficients = left.split(" ");
for (String coefficient : coefficients) {
double value = coefficient.charAt(0) == '-' ? -1 : 1;
int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim());
lhs[index] = value;
}
return new LinearConstraint(lhs, relationship, rhs);
}
} | // You are a professional Java test case writer, please create a test case named `testMath781` for the issue `Math-MATH-781`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-781
//
// ## Issue-Title:
// SimplexSolver gives bad results
//
// ## Issue-Description:
//
// Methode SimplexSolver.optimeze(...) gives bad results with commons-math3-3.0
//
// in a simple test problem. It works well in commons-math-2.2.
//
//
//
//
//
@Test
public void testMath781() {
| 48 | 33 | 31 | src/test/java/org/apache/commons/math3/optimization/linear/SimplexSolverTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-781
## Issue-Title:
SimplexSolver gives bad results
## Issue-Description:
Methode SimplexSolver.optimeze(...) gives bad results with commons-math3-3.0
in a simple test problem. It works well in commons-math-2.2.
```
You are a professional Java test case writer, please create a test case named `testMath781` for the issue `Math-MATH-781`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testMath781() {
```
| 31 | [
"org.apache.commons.math3.optimization.linear.SimplexTableau"
] | 3fcc1fe2a0fa22f64543e84150c77d59747abcc3629e01ee88e56afa3a85daf4 | @Test
public void testMath781() | // You are a professional Java test case writer, please create a test case named `testMath781` for the issue `Math-MATH-781`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-781
//
// ## Issue-Title:
// SimplexSolver gives bad results
//
// ## Issue-Description:
//
// Methode SimplexSolver.optimeze(...) gives bad results with commons-math3-3.0
//
// in a simple test problem. It works well in commons-math-2.2.
//
//
//
//
//
| 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.linear;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.math3.optimization.GoalType;
import org.apache.commons.math3.optimization.PointValuePair;
import org.apache.commons.math3.util.Precision;
import org.junit.Test;
public class SimplexSolverTest {
@Test
public void testMath781() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 6, 7 }, 0);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 2, 1 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { -1, 1, 1 }, Relationship.LEQ, -1));
constraints.add(new LinearConstraint(new double[] { 2, -3, 1 }, Relationship.LEQ, -1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) > 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[2], 0.0d, epsilon) < 0);
Assert.assertEquals(2.0d, solution.getValue(), epsilon);
}
@Test
public void testMath713NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {1, 0}, Relationship.EQ, 1));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) >= 0);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) >= 0);
}
@Test
public void testMath434NegativeVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0, 0.0, 1.0}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {1, 1, 0}, Relationship.EQ, 5));
constraints.add(new LinearConstraint(new double[] {0, 0, 1}, Relationship.GEQ, -10));
double epsilon = 1e-6;
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertEquals(5.0, solution.getPoint()[0] + solution.getPoint()[1], epsilon);
Assert.assertEquals(-10.0, solution.getPoint()[2], epsilon);
Assert.assertEquals(-10.0, solution.getValue(), epsilon);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testMath434UnfeasibleSolution() {
double epsilon = 1e-6;
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 0.0}, 0.0);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {epsilon/2, 0.5}, Relationship.EQ, 0));
constraints.add(new LinearConstraint(new double[] {1e-3, 0.1}, Relationship.EQ, 10));
SimplexSolver solver = new SimplexSolver();
// allowing only non-negative values, no feasible solution shall be found
solver.optimize(f, constraints, GoalType.MINIMIZE, true);
}
@Test
public void testMath434PivotRowSelection() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0}, 0.0);
double epsilon = 1e-6;
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {200}, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] {100}, Relationship.GEQ, 0.499900001));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0] * 200.d, 1.d, epsilon) >= 0);
Assert.assertEquals(0.0050, solution.getValue(), epsilon);
}
@Test
public void testMath434PivotRowSelection2() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d}, 0.0d);
ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] {1.0d, -0.1d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.EQ, -0.1d));
constraints.add(new LinearConstraint(new double[] {1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, -1e-18d));
constraints.add(new LinearConstraint(new double[] {0.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 1.0d, 0.0d, -0.0128588d, 1e-5d}, Relationship.EQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 0.0d, 1.0d, 1e-5d, -0.0128586d}, Relationship.EQ, 1e-10d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, -1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, -1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, 1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d));
double epsilon = 1e-7;
SimplexSolver simplex = new SimplexSolver();
PointValuePair solution = simplex.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], -1e-18d, epsilon) >= 0);
Assert.assertEquals(1.0d, solution.getPoint()[1], epsilon);
Assert.assertEquals(0.0d, solution.getPoint()[2], epsilon);
Assert.assertEquals(1.0d, solution.getValue(), epsilon);
}
@Test
public void testMath272() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertEquals(0.0, solution.getPoint()[0], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[1], .0000001);
Assert.assertEquals(1.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(3.0, solution.getValue(), .0000001);
}
@Test
public void testMath286() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0));
constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(25.8, solution.getValue(), .0000001);
Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001);
Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001);
Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001);
Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001);
}
@Test
public void testDegeneracy() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0));
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(13.6, solution.getValue(), .0000001);
}
@Test
public void testMath288() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0));
constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(10.0, solution.getValue(), .0000001);
}
@Test
public void testMath290GEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertEquals(0, solution.getValue(), .0000001);
Assert.assertEquals(0, solution.getPoint()[0], .0000001);
Assert.assertEquals(0, solution.getPoint()[1], .0000001);
}
@Test(expected=NoFeasibleSolutionException.class)
public void testMath290LEQ() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MINIMIZE, true);
}
@Test
public void testMath293() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution1 = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[1], .0001);
Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[3], .0001);
Assert.assertEquals(0.0, solution1.getPoint()[4], .0001);
Assert.assertEquals(30.0, solution1.getPoint()[5], .0001);
Assert.assertEquals(40.57143, solution1.getValue(), .0001);
double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1];
double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3];
double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5];
f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 );
constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0));
constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB));
constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC));
PointValuePair solution2 = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(40.57143, solution2.getValue(), .0001);
}
@Test
public void testSimplexSolver() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 15, 10 }, 7);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(57.0, solution.getValue(), 0.0);
}
@Test
public void testSingleVariableAndConstraint() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(10.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(30.0, solution.getValue(), 0.0);
}
/**
* With no artificial variables needed (no equals and no greater than
* constraints) we can go straight to Phase 2.
*/
@Test
public void testModelWithNoArtificialVars() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3));
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(2.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(50.0, solution.getValue(), 0.0);
}
@Test
public void testMinimization() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6));
constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12));
constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, false);
Assert.assertEquals(4.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(-13.0, solution.getValue(), 0.0);
}
@Test
public void testSolutionWithNegativeDecisionVariable() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6));
constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(8.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(12.0, solution.getValue(), 0.0);
}
@Test(expected = NoFeasibleSolutionException.class)
public void testInfeasibleSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1));
constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
}
@Test(expected = UnboundedSolutionException.class)
public void testUnboundedSolution() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2));
SimplexSolver solver = new SimplexSolver();
solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
}
@Test
public void testRestrictVariablesToNonNegative() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456));
constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454));
constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421));
constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356));
constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001);
Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[2], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[3], .0000001);
Assert.assertEquals(0.0, solution.getPoint()[4], .0000001);
Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001);
}
@Test
public void testEpsilon() {
LinearObjectiveFunction f =
new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17));
constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7));
constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, false);
Assert.assertEquals(1.0, solution.getPoint()[0], 0.0);
Assert.assertEquals(1.0, solution.getPoint()[1], 0.0);
Assert.assertEquals(0.0, solution.getPoint()[2], 0.0);
Assert.assertEquals(15.0, solution.getValue(), 0.0);
}
@Test
public void testTrivialModel() {
LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MAXIMIZE, true);
Assert.assertEquals(0, solution.getValue(), .0000001);
}
@Test
public void testLargeModel() {
double[] objective = new double[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
12, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 12, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 12, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 12, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 12, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1};
LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0);
Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>();
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49"));
constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0"));
constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49"));
constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0"));
constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51"));
constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0"));
constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0"));
constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51"));
constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0"));
constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0"));
constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49"));
constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0"));
constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59"));
constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0"));
constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0"));
constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x192 = 0"));
constraints.add(equationFromString(objective.length, "x170 - x26 = 0"));
constraints.add(equationFromString(objective.length, "x171 - x27 = 0"));
constraints.add(equationFromString(objective.length, "x172 - x54 = 0"));
constraints.add(equationFromString(objective.length, "x173 - x55 = 0"));
constraints.add(equationFromString(objective.length, "x174 - x168 = 0"));
constraints.add(equationFromString(objective.length, "x177 - x169 = 0"));
constraints.add(equationFromString(objective.length, "x178 - x138 = 0"));
constraints.add(equationFromString(objective.length, "x179 - x139 = 0"));
constraints.add(equationFromString(objective.length, "x180 - x166 = 0"));
constraints.add(equationFromString(objective.length, "x181 - x167 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x205 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x206 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x207 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x208 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x209 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x211 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x212 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x213 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x214 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x215 = 0"));
constraints.add(equationFromString(objective.length, "x193 - x182 = 0"));
constraints.add(equationFromString(objective.length, "x194 - x183 = 0"));
constraints.add(equationFromString(objective.length, "x195 - x184 = 0"));
constraints.add(equationFromString(objective.length, "x196 - x185 = 0"));
constraints.add(equationFromString(objective.length, "x197 - x186 = 0"));
constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0"));
constraints.add(equationFromString(objective.length, "x200 - x188 = 0"));
constraints.add(equationFromString(objective.length, "x201 - x189 = 0"));
constraints.add(equationFromString(objective.length, "x202 - x190 = 0"));
constraints.add(equationFromString(objective.length, "x203 - x191 = 0"));
constraints.add(equationFromString(objective.length, "x204 - x192 = 0"));
SimplexSolver solver = new SimplexSolver();
PointValuePair solution = solver.optimize(f, constraints, GoalType.MINIMIZE, true);
Assert.assertEquals(7518.0, solution.getValue(), .0000001);
}
/**
* Converts a test string to a {@link LinearConstraint}.
* Ex: x0 + x1 + x2 + x3 - x12 = 0
*/
private LinearConstraint equationFromString(int numCoefficients, String s) {
Relationship relationship;
if (s.contains(">=")) {
relationship = Relationship.GEQ;
} else if (s.contains("<=")) {
relationship = Relationship.LEQ;
} else if (s.contains("=")) {
relationship = Relationship.EQ;
} else {
throw new IllegalArgumentException();
}
String[] equationParts = s.split("[>|<]?=");
double rhs = Double.parseDouble(equationParts[1].trim());
double[] lhs = new double[numCoefficients];
String left = equationParts[0].replaceAll(" ?x", "");
String[] coefficients = left.split(" ");
for (String coefficient : coefficients) {
double value = coefficient.charAt(0) == '-' ? -1 : 1;
int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim());
lhs[index] = value;
}
return new LinearConstraint(lhs, relationship, rhs);
}
} |
||
@Test
public void shouldReadBigGid() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
TarArchiveEntry t = new TarArchiveEntry("name");
t.setGroupId(4294967294l);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis);
t = tis.getNextTarEntry();
assertEquals(4294967294l, t.getLongGroupId());
tis.close();
} | org.apache.commons.compress.archivers.tar.TarArchiveInputStreamTest::shouldReadBigGid | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | 256 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | shouldReadBigGid | /*
* 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.apache.commons.compress.AbstractTestCase.getFile;
import static org.apache.commons.compress.AbstractTestCase.mkdir;
import static org.apache.commons.compress.AbstractTestCase.rmdir;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.utils.CharsetNames;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
public class TarArchiveInputStreamTest {
@Test
public void readSimplePaxHeader() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
@Test
public void readPaxHeaderWithEmbeddedNewline() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("line1\nline2\nand3", headers.get("comment"));
tais.close();
}
@Test
public void readNonAsciiPaxHeader() throws Exception {
String ae = "\u00e4";
String line = "11 path="+ ae + "\n";
assertEquals(11, line.getBytes(CharsetNames.UTF_8).length);
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals(ae, headers.get("path"));
tais.close();
}
@Test
public void workaroundForBrokenTimeHeader() throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar")));
TarArchiveEntry tae = in.getNextTarEntry();
tae = in.getNextTarEntry();
assertEquals("sample/link-to-txt-file.lnk", tae.getName());
assertEquals(new Date(0), tae.getLastModifiedDate());
assertTrue(tae.isSymbolicLink());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void datePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("preepoch-star.tar");
}
@Test
public void datePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("preepoch-posix.tar");
}
private void datePriorToEpoch(String archive) throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile(archive)));
TarArchiveEntry tae = in.getNextTarEntry();
assertEquals("foo", tae.getName());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1969, 11, 31, 23, 59, 59);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(cal.getTime(), tae.getLastModifiedDate());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
}
@Test
public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()
throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoding = CharsetNames.UTF_16;
String name = "1234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890\u00e4";
TarArchiveOutputStream tos =
new TarArchiveOutputStream(bos, encoding);
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
TarArchiveEntry t = new TarArchiveEntry(name);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis, encoding);
t = tis.getNextTarEntry();
assertEquals(name, t.getName());
tis.close();
}
@Test
public void shouldConsumeArchiveCompletely() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/archive_with_trailer.tar");
TarArchiveInputStream tar = new TarArchiveInputStream(is);
while (tar.getNextTarEntry() != null) {
// just consume the archive
}
byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'
};
byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
tar.close();
}
@Test
public void readsArchiveCompletely_COMPRESS245() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/COMPRESS-245.tar.gz");
try {
InputStream gin = new GZIPInputStream(is);
TarArchiveInputStream tar = new TarArchiveInputStream(gin);
int count = 0;
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
count++;
entry = tar.getNextTarEntry();
}
assertEquals(31, count);
tar.close();
} catch (IOException e) {
fail("COMPRESS-245: " + e.getMessage());
} finally {
is.close();
}
}
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
File dir = mkdir("COMPRESS-279");
TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar");
FileOutputStream out = null;
try {
TarArchiveEntry entry = is.getNextTarEntry();
int count = 0;
while (entry != null) {
out = new FileOutputStream(new File(dir, String.valueOf(count)));
IOUtils.copy(is, out);
out.close();
out = null;
count++;
entry = is.getNextTarEntry();
}
} finally {
is.close();
if (out != null) {
out.close();
}
rmdir(dir);
}
}
@Test
public void shouldReadBigGid() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
TarArchiveEntry t = new TarArchiveEntry("name");
t.setGroupId(4294967294l);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis);
t = tis.getNextTarEntry();
assertEquals(4294967294l, t.getLongGroupId());
tis.close();
}
private TarArchiveInputStream getTestStream(String name) {
return new TarArchiveInputStream(
TarArchiveInputStreamTest.class.getResourceAsStream(name));
}
} | // You are a professional Java test case writer, please create a test case named `shouldReadBigGid` for the issue `Compress-COMPRESS-314`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-314
//
// ## Issue-Title:
// TarArchiveInputStream rejects uid or gid >= 0x80000000
//
// ## Issue-Description:
//
// A POSIX-format archive that came from sysdiagnose produces NumberFormatException[1] when I try to read it with TarArchiveInputStream.
//
//
// The relevant part of the .tar file looks like this:
//
//
// 18 uid=429496729
//
//
// That's the uid of 'nobody' on Mac OS (on Mac OS, uid\_t is 'unsigned int').
//
//
// POSIX doesn't say anything about the width of the uid extended header[2], so I assume the tar file is okay. GNU tar doesn't have trouble with it.
//
//
// The relevant code, in applyPaxHeadersToCurrentEntry:
//
//
// } else if ("gid".equals(key))
//
//
// {
// currEntry.setGroupId(Integer.parseInt(val));
// ...
// }
// else if ("uid".equals(key)){
//
// currEntry.setUserId(Integer.parseInt(val));
//
//
// uid\_t and gid\_t are typically unsigned 32-bit integers, so these should presumably use Long.parseLong to handle integers with the top bit set (and TarArchiveEntry would need some modifications to handle large uid and gid, too).
//
//
// [1] java.lang.NumberFormatException: For input string: "4294967294"
//
// at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
//
// at java.lang.Integer.parseInt(Integer.java:495)
//
// at java.lang.Integer.parseInt(Integer.java:527)
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.applyPaxHeadersToCurrentEntry(TarArchiveInputStream.java:488)
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.paxHeaders(TarArchiveInputStream.java:415)
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:295)
//
//
// [2] <http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_03>
//
// uid
//
// The user ID of the file owner, expressed as a decimal number using digits from the ISO/IEC 646:1991 standard. This record shall override the uid field in the following header block(s). When used in write or copy mode, pax shall include a uid extended header record for each file whose owner ID is greater than 2097151 (octal 7777777).
//
//
//
//
//
@Test
public void shouldReadBigGid() throws Exception {
| 256 | 32 | 237 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-314
## Issue-Title:
TarArchiveInputStream rejects uid or gid >= 0x80000000
## Issue-Description:
A POSIX-format archive that came from sysdiagnose produces NumberFormatException[1] when I try to read it with TarArchiveInputStream.
The relevant part of the .tar file looks like this:
18 uid=429496729
That's the uid of 'nobody' on Mac OS (on Mac OS, uid\_t is 'unsigned int').
POSIX doesn't say anything about the width of the uid extended header[2], so I assume the tar file is okay. GNU tar doesn't have trouble with it.
The relevant code, in applyPaxHeadersToCurrentEntry:
} else if ("gid".equals(key))
{
currEntry.setGroupId(Integer.parseInt(val));
...
}
else if ("uid".equals(key)){
currEntry.setUserId(Integer.parseInt(val));
uid\_t and gid\_t are typically unsigned 32-bit integers, so these should presumably use Long.parseLong to handle integers with the top bit set (and TarArchiveEntry would need some modifications to handle large uid and gid, too).
[1] java.lang.NumberFormatException: For input string: "4294967294"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.applyPaxHeadersToCurrentEntry(TarArchiveInputStream.java:488)
at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.paxHeaders(TarArchiveInputStream.java:415)
at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:295)
[2] <http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_03>
uid
The user ID of the file owner, expressed as a decimal number using digits from the ISO/IEC 646:1991 standard. This record shall override the uid field in the following header block(s). When used in write or copy mode, pax shall include a uid extended header record for each file whose owner ID is greater than 2097151 (octal 7777777).
```
You are a professional Java test case writer, please create a test case named `shouldReadBigGid` for the issue `Compress-COMPRESS-314`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void shouldReadBigGid() throws Exception {
```
| 237 | [
"org.apache.commons.compress.archivers.tar.TarArchiveInputStream"
] | 4007375a86ce1fedf2f145981166c969e92c2471f8bc811b62155bfd68dbe198 | @Test
public void shouldReadBigGid() throws Exception | // You are a professional Java test case writer, please create a test case named `shouldReadBigGid` for the issue `Compress-COMPRESS-314`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-314
//
// ## Issue-Title:
// TarArchiveInputStream rejects uid or gid >= 0x80000000
//
// ## Issue-Description:
//
// A POSIX-format archive that came from sysdiagnose produces NumberFormatException[1] when I try to read it with TarArchiveInputStream.
//
//
// The relevant part of the .tar file looks like this:
//
//
// 18 uid=429496729
//
//
// That's the uid of 'nobody' on Mac OS (on Mac OS, uid\_t is 'unsigned int').
//
//
// POSIX doesn't say anything about the width of the uid extended header[2], so I assume the tar file is okay. GNU tar doesn't have trouble with it.
//
//
// The relevant code, in applyPaxHeadersToCurrentEntry:
//
//
// } else if ("gid".equals(key))
//
//
// {
// currEntry.setGroupId(Integer.parseInt(val));
// ...
// }
// else if ("uid".equals(key)){
//
// currEntry.setUserId(Integer.parseInt(val));
//
//
// uid\_t and gid\_t are typically unsigned 32-bit integers, so these should presumably use Long.parseLong to handle integers with the top bit set (and TarArchiveEntry would need some modifications to handle large uid and gid, too).
//
//
// [1] java.lang.NumberFormatException: For input string: "4294967294"
//
// at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
//
// at java.lang.Integer.parseInt(Integer.java:495)
//
// at java.lang.Integer.parseInt(Integer.java:527)
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.applyPaxHeadersToCurrentEntry(TarArchiveInputStream.java:488)
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.paxHeaders(TarArchiveInputStream.java:415)
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:295)
//
//
// [2] <http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_03>
//
// uid
//
// The user ID of the file owner, expressed as a decimal number using digits from the ISO/IEC 646:1991 standard. This record shall override the uid field in the following header block(s). When used in write or copy mode, pax shall include a uid extended header record for each file whose owner ID is greater than 2097151 (octal 7777777).
//
//
//
//
//
| 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.apache.commons.compress.AbstractTestCase.getFile;
import static org.apache.commons.compress.AbstractTestCase.mkdir;
import static org.apache.commons.compress.AbstractTestCase.rmdir;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.utils.CharsetNames;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
public class TarArchiveInputStreamTest {
@Test
public void readSimplePaxHeader() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
@Test
public void readPaxHeaderWithEmbeddedNewline() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("line1\nline2\nand3", headers.get("comment"));
tais.close();
}
@Test
public void readNonAsciiPaxHeader() throws Exception {
String ae = "\u00e4";
String line = "11 path="+ ae + "\n";
assertEquals(11, line.getBytes(CharsetNames.UTF_8).length);
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals(ae, headers.get("path"));
tais.close();
}
@Test
public void workaroundForBrokenTimeHeader() throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar")));
TarArchiveEntry tae = in.getNextTarEntry();
tae = in.getNextTarEntry();
assertEquals("sample/link-to-txt-file.lnk", tae.getName());
assertEquals(new Date(0), tae.getLastModifiedDate());
assertTrue(tae.isSymbolicLink());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void datePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("preepoch-star.tar");
}
@Test
public void datePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("preepoch-posix.tar");
}
private void datePriorToEpoch(String archive) throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile(archive)));
TarArchiveEntry tae = in.getNextTarEntry();
assertEquals("foo", tae.getName());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1969, 11, 31, 23, 59, 59);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(cal.getTime(), tae.getLastModifiedDate());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
}
@Test
public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()
throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoding = CharsetNames.UTF_16;
String name = "1234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890\u00e4";
TarArchiveOutputStream tos =
new TarArchiveOutputStream(bos, encoding);
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
TarArchiveEntry t = new TarArchiveEntry(name);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis, encoding);
t = tis.getNextTarEntry();
assertEquals(name, t.getName());
tis.close();
}
@Test
public void shouldConsumeArchiveCompletely() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/archive_with_trailer.tar");
TarArchiveInputStream tar = new TarArchiveInputStream(is);
while (tar.getNextTarEntry() != null) {
// just consume the archive
}
byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'
};
byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
tar.close();
}
@Test
public void readsArchiveCompletely_COMPRESS245() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/COMPRESS-245.tar.gz");
try {
InputStream gin = new GZIPInputStream(is);
TarArchiveInputStream tar = new TarArchiveInputStream(gin);
int count = 0;
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
count++;
entry = tar.getNextTarEntry();
}
assertEquals(31, count);
tar.close();
} catch (IOException e) {
fail("COMPRESS-245: " + e.getMessage());
} finally {
is.close();
}
}
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
File dir = mkdir("COMPRESS-279");
TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar");
FileOutputStream out = null;
try {
TarArchiveEntry entry = is.getNextTarEntry();
int count = 0;
while (entry != null) {
out = new FileOutputStream(new File(dir, String.valueOf(count)));
IOUtils.copy(is, out);
out.close();
out = null;
count++;
entry = is.getNextTarEntry();
}
} finally {
is.close();
if (out != null) {
out.close();
}
rmdir(dir);
}
}
@Test
public void shouldReadBigGid() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);
tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
TarArchiveEntry t = new TarArchiveEntry("name");
t.setGroupId(4294967294l);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis);
t = tis.getNextTarEntry();
assertEquals(4294967294l, t.getLongGroupId());
tis.close();
}
private TarArchiveInputStream getTestStream(String name) {
return new TarArchiveInputStream(
TarArchiveInputStreamTest.class.getResourceAsStream(name));
}
} |
||
public void testPlusMonths_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(-1);
MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance());
assertEquals(expected, result);
} | org.joda.time.TestMonthDay_Basics::testPlusMonths_int_negativeFromLeap | src/test/java/org/joda/time/TestMonthDay_Basics.java | 462 | src/test/java/org/joda/time/TestMonthDay_Basics.java | testPlusMonths_int_negativeFromLeap | /*
* Copyright 2001-2010 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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Locale;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.chrono.BuddhistChronology;
import org.joda.time.chrono.CopticChronology;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* This class is a Junit unit test for MonthDay. Based on {@link TestYearMonth_Basics}
*/
public class TestMonthDay_Basics extends TestCase {
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 Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS);
// private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON);
private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO);
private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC();
// private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS);
// private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON);
// private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO);
private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC();
// private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS);
// private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON);
private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO);
private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC();
private long TEST_TIME_NOW =
(31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
private DateTimeZone zone = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestMonthDay_Basics.class);
}
public TestMonthDay_Basics(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
zone = DateTimeZone.getDefault();
DateTimeZone.setDefault(LONDON);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(zone);
zone = null;
}
//-----------------------------------------------------------------------
public void testGet() {
MonthDay test = new MonthDay();
assertEquals(6, test.get(DateTimeFieldType.monthOfYear()));
assertEquals(9, test.get(DateTimeFieldType.dayOfMonth()));
try {
test.get(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.get(DateTimeFieldType.year());
fail();
} catch (IllegalArgumentException ex) {}
}
public void testSize() {
MonthDay test = new MonthDay();
assertEquals(2, test.size());
}
public void testGetFieldType() {
MonthDay test = new MonthDay(COPTIC_PARIS);
assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(0));
assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(1));
try {
test.getFieldType(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getFieldType(2);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetFieldTypes() {
MonthDay test = new MonthDay(COPTIC_PARIS);
DateTimeFieldType[] fields = test.getFieldTypes();
assertEquals(2, fields.length);
assertSame(DateTimeFieldType.monthOfYear(), fields[0]);
assertSame(DateTimeFieldType.dayOfMonth(), fields[1]);
assertNotSame(test.getFieldTypes(), test.getFieldTypes());
}
public void testGetField() {
MonthDay test = new MonthDay(COPTIC_PARIS);
assertSame(COPTIC_UTC.monthOfYear(), test.getField(0));
assertSame(COPTIC_UTC.dayOfMonth(), test.getField(1));
try {
test.getField(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getField(2);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetFields() {
MonthDay test = new MonthDay(COPTIC_PARIS);
DateTimeField[] fields = test.getFields();
assertEquals(2, fields.length);
assertSame(COPTIC_UTC.monthOfYear(), fields[0]);
assertSame(COPTIC_UTC.dayOfMonth(), fields[1]);
assertNotSame(test.getFields(), test.getFields());
}
public void testGetValue() {
MonthDay test = new MonthDay();
assertEquals(6, test.getValue(0));
assertEquals(9, test.getValue(1));
try {
test.getValue(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getValue(2);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetValues() {
MonthDay test = new MonthDay();
int[] values = test.getValues();
assertEquals(2, values.length);
assertEquals(6, values[0]);
assertEquals(9, values[1]);
assertNotSame(test.getValues(), test.getValues());
}
public void testIsSupported() {
MonthDay test = new MonthDay(COPTIC_PARIS);
assertEquals(false, test.isSupported(DateTimeFieldType.year()));
assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear()));
assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth()));
assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay()));
}
public void testEqualsHashCode() {
MonthDay test1 = new MonthDay(10, 6, COPTIC_PARIS);
MonthDay test2 = new MonthDay(10, 6, COPTIC_PARIS);
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
MonthDay test3 = new MonthDay(10, 6);
assertEquals(false, test1.equals(test3));
assertEquals(false, test2.equals(test3));
assertEquals(false, test3.equals(test1));
assertEquals(false, test3.equals(test2));
assertEquals(false, test1.hashCode() == test3.hashCode());
assertEquals(false, test2.hashCode() == test3.hashCode());
assertEquals(false, test1.equals("Hello"));
assertEquals(true, test1.equals(new MockMD()));
assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE));
}
class MockMD extends MockPartial {
@Override
public Chronology getChronology() {
return COPTIC_UTC;
}
@Override
public DateTimeField[] getFields() {
return new DateTimeField[] {
COPTIC_UTC.monthOfYear(),
COPTIC_UTC.dayOfMonth()
};
}
@Override
public int[] getValues() {
return new int[] {10, 6};
}
}
//-----------------------------------------------------------------------
public void testCompareTo() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(0, test1.compareTo(test1a));
assertEquals(0, test1a.compareTo(test1));
assertEquals(0, test1.compareTo(test1));
assertEquals(0, test1a.compareTo(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(-1, test1.compareTo(test2));
assertEquals(+1, test2.compareTo(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(-1, test1.compareTo(test3));
assertEquals(+1, test3.compareTo(test1));
assertEquals(0, test3.compareTo(test2));
DateTimeFieldType[] types = new DateTimeFieldType[] {
DateTimeFieldType.monthOfYear(),
DateTimeFieldType.dayOfMonth()
};
int[] values = new int[] {6, 6};
Partial p = new Partial(types, values);
assertEquals(0, test1.compareTo(p));
try {
test1.compareTo(null);
fail();
} catch (NullPointerException ex) {}
try {
test1.compareTo(new LocalTime());
fail();
} catch (ClassCastException ex) {}
Partial partial = new Partial()
.with(DateTimeFieldType.centuryOfEra(), 1)
.with(DateTimeFieldType.halfdayOfDay(), 0)
.with(DateTimeFieldType.dayOfMonth(), 9);
try {
new MonthDay(10, 6).compareTo(partial);
fail();
} catch (ClassCastException ex) {}
}
//-----------------------------------------------------------------------
public void testIsEqual_MD() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(true, test1.isEqual(test1a));
assertEquals(true, test1a.isEqual(test1));
assertEquals(true, test1.isEqual(test1));
assertEquals(true, test1a.isEqual(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(false, test1.isEqual(test2));
assertEquals(false, test2.isEqual(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isEqual(test3));
assertEquals(false, test3.isEqual(test1));
assertEquals(true, test3.isEqual(test2));
try {
new MonthDay(6, 7).isEqual(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testIsBefore_MD() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(false, test1.isBefore(test1a));
assertEquals(false, test1a.isBefore(test1));
assertEquals(false, test1.isBefore(test1));
assertEquals(false, test1a.isBefore(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(true, test1.isBefore(test2));
assertEquals(false, test2.isBefore(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(true, test1.isBefore(test3));
assertEquals(false, test3.isBefore(test1));
assertEquals(false, test3.isBefore(test2));
try {
new MonthDay(6, 7).isBefore(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testIsAfter_MD() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(false, test1.isAfter(test1a));
assertEquals(false, test1a.isAfter(test1));
assertEquals(false, test1.isAfter(test1));
assertEquals(false, test1a.isAfter(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(false, test1.isAfter(test2));
assertEquals(true, test2.isAfter(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isAfter(test3));
assertEquals(true, test3.isAfter(test1));
assertEquals(false, test3.isAfter(test2));
try {
new MonthDay(6, 7).isAfter(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testWithChronologyRetainFields_Chrono() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
MonthDay test = base.withChronologyRetainFields(BUDDHIST_TOKYO);
check(base, 6, 6);
assertEquals(COPTIC_UTC, base.getChronology());
check(test, 6, 6);
assertEquals(BUDDHIST_UTC, test.getChronology());
}
public void testWithChronologyRetainFields_sameChrono() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
MonthDay test = base.withChronologyRetainFields(COPTIC_TOKYO);
assertSame(base, test);
}
public void testWithChronologyRetainFields_nullChrono() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
MonthDay test = base.withChronologyRetainFields(null);
check(base, 6, 6);
assertEquals(COPTIC_UTC, base.getChronology());
check(test, 6, 6);
assertEquals(ISO_UTC, test.getChronology());
}
//-----------------------------------------------------------------------
public void testWithField() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withField(DateTimeFieldType.monthOfYear(), 10);
assertEquals(new MonthDay(9, 6), test);
assertEquals(new MonthDay(10, 6), result);
}
public void testWithField_nullField() {
MonthDay test = new MonthDay(9, 6);
try {
test.withField(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithField_unknownField() {
MonthDay test = new MonthDay(9, 6);
try {
test.withField(DateTimeFieldType.hourOfDay(), 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithField_same() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withField(DateTimeFieldType.monthOfYear(), 9);
assertEquals(new MonthDay(9, 6), test);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testWithFieldAdded() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withFieldAdded(DurationFieldType.months(), 1);
assertEquals(new MonthDay(9, 6), test);
assertEquals(new MonthDay(10, 6), result);
}
public void testWithFieldAdded_nullField_zero() {
MonthDay test = new MonthDay(9, 6);
try {
test.withFieldAdded(null, 0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithFieldAdded_nullField_nonZero() {
MonthDay test = new MonthDay(9, 6);
try {
test.withFieldAdded(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithFieldAdded_zero() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withFieldAdded(DurationFieldType.months(), 0);
assertSame(test, result);
}
public void testWithFieldAdded_unknownField() {
MonthDay test = new MonthDay(9, 6);
try {
test.withFieldAdded(DurationFieldType.hours(), 6);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testPlus_RP() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8));
MonthDay expected = new MonthDay(8, 9, BuddhistChronology.getInstance());
assertEquals(expected, result);
result = test.plus((ReadablePeriod) null);
assertSame(test, result);
}
public void testPlusMonths_int() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.plusMonths(1);
MonthDay expected = new MonthDay(7, 5, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(1);
MonthDay expected = new MonthDay(3, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(-1);
MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_endOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(1);
MonthDay expected = new MonthDay(4, 30, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_negativeEndOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(-1);
MonthDay expected = new MonthDay(2, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_same() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.plusMonths(0);
assertSame(test, result);
}
public void testPlusMonths_int_wrap() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.plusMonths(10);
MonthDay expected = new MonthDay(4, 5, ISO_UTC);
assertEquals(expected, result);
}
public void testPlusMonths_int_adjust() {
MonthDay test = new MonthDay(7, 31, ISO_UTC);
MonthDay result = test.plusMonths(2);
MonthDay expected = new MonthDay(9, 30, ISO_UTC);
assertEquals(expected, result);
}
//-------------------------------------------------------------------------
public void testPlusDays_int() {
MonthDay test = new MonthDay(5, 10, BuddhistChronology.getInstance());
MonthDay result = test.plusDays(1);
MonthDay expected = new MonthDay(5, 11, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusDays_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusDays(1);
MonthDay expected = new MonthDay(3, 1, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusDays_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusDays(-1);
MonthDay expected = new MonthDay(2, 28, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusDays_same() {
MonthDay test = new MonthDay(5, 10, BuddhistChronology.getInstance());
MonthDay result = test.plusDays(0);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testMinus_RP() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1));
MonthDay expected = new MonthDay(5, 4, BuddhistChronology.getInstance());
assertEquals(expected, result);
result = test.minus((ReadablePeriod) null);
assertSame(test, result);
}
public void testMinusMonths_int() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.minusMonths(1);
MonthDay expected = new MonthDay(5, 5, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(1);
MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(-1);
MonthDay expected = new MonthDay(3, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_endOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(1);
MonthDay expected = new MonthDay(2, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_negativeEndOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(-1);
MonthDay expected = new MonthDay(4, 30, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_same() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.minusMonths(0);
assertSame(test, result);
}
public void testMinusMonths_int_wrap() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.minusMonths(10);
MonthDay expected = new MonthDay(8, 5, ISO_UTC);
assertEquals(expected, result);
}
public void testMinusMonths_int_adjust() {
MonthDay test = new MonthDay(7, 31, ISO_UTC);
MonthDay result = test.minusMonths(3);
MonthDay expected = new MonthDay(4, 30, ISO_UTC);
assertEquals(expected, result);
}
//-------------------------------------------------------------------------
public void testMinusDays_int() {
MonthDay test = new MonthDay(5, 11, BuddhistChronology.getInstance());
MonthDay result = test.minusDays(1);
MonthDay expected = new MonthDay(5, 10, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusDays_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusDays(1);
MonthDay expected = new MonthDay(2, 28, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusDays_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusDays(-1);
MonthDay expected = new MonthDay(3, 1, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusDays_same() {
MonthDay test = new MonthDay(5, 11, BuddhistChronology.getInstance());
MonthDay result = test.minusDays(0);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testToLocalDate() {
MonthDay base = new MonthDay(6, 6, COPTIC_UTC);
LocalDate test = base.toLocalDate(2009);
assertEquals(new LocalDate(2009, 6, 6, COPTIC_UTC), test);
try {
base.toLocalDate(0);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testToDateTime_RI() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
DateTime test = base.toDateTime(dt);
check(base, 6, 6);
DateTime expected = dt;
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(6);
assertEquals(expected, test);
}
public void testToDateTime_nullRI() {
MonthDay base = new MonthDay(6, 6);
DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
DateTimeUtils.setCurrentMillisFixed(dt.getMillis());
DateTime test = base.toDateTime((ReadableInstant) null);
check(base, 6, 6);
DateTime expected = dt;
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(6);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testWithers() {
MonthDay test = new MonthDay(10, 6);
check(test.withMonthOfYear(5), 5, 6);
check(test.withDayOfMonth(2), 10, 2);
try {
test.withMonthOfYear(0);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.withMonthOfYear(13);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testProperty() {
MonthDay test = new MonthDay(6, 6);
assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear()));
assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth()));
try {
test.property(DateTimeFieldType.millisOfDay());
fail();
} catch (IllegalArgumentException ex) {}
try {
test.property(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testSerialization() throws Exception {
MonthDay test = new MonthDay(5, 6, COPTIC_PARIS);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test);
byte[] bytes = baos.toByteArray();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
MonthDay result = (MonthDay) ois.readObject();
ois.close();
assertEquals(test, result);
assertTrue(Arrays.equals(test.getValues(), result.getValues()));
assertTrue(Arrays.equals(test.getFields(), result.getFields()));
assertEquals(test.getChronology(), result.getChronology());
}
//-----------------------------------------------------------------------
public void testToString() {
MonthDay test = new MonthDay(5, 6);
assertEquals("--05-06", test.toString());
}
//-----------------------------------------------------------------------
public void testToString_String() {
MonthDay test = new MonthDay(5, 6);
assertEquals("05 \ufffd\ufffd", test.toString("MM HH"));
assertEquals("--05-06", test.toString((String) null));
}
//-----------------------------------------------------------------------
public void testToString_String_Locale() {
MonthDay test = new MonthDay(5, 6);
assertEquals("\ufffd 6/5", test.toString("EEE d/M", Locale.ENGLISH));
assertEquals("\ufffd 6/5", test.toString("EEE d/M", Locale.FRENCH));
assertEquals("--05-06", test.toString(null, Locale.ENGLISH));
assertEquals("\ufffd 6/5", test.toString("EEE d/M", null));
assertEquals("--05-06", test.toString(null, null));
}
//-----------------------------------------------------------------------
public void testToString_DTFormatter() {
MonthDay test = new MonthDay(5, 6);
assertEquals("05 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("MM HH")));
assertEquals("--05-06", test.toString((DateTimeFormatter) null));
}
//-----------------------------------------------------------------------
private void check(MonthDay test, int month, int day) {
assertEquals(month, test.getMonthOfYear());
assertEquals(day, test.getDayOfMonth());
}
} | // You are a professional Java test case writer, please create a test case named `testPlusMonths_int_negativeFromLeap` for the issue `Time-151`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-151
//
// ## Issue-Title:
// #151 Unable to add days to a MonthDay set to the ISO leap date
//
//
//
//
//
// ## Issue-Description:
// It's not possible to add days to a MonthDay set to the ISO leap date (February 29th). This is even more bizarre given the exact error message thrown.
//
//
// Sample snippet:
//
//
//
// ```
// final MonthDay isoLeap = new MonthDay(DateTimeConstants.FEBRUARY, 29, ISOChronology.getInstanceUTC());
// System.out.println(isoLeap);
// System.out.println(isoLeap.plusDays(2));
//
// ```
//
// Which generates the following combined console output and stack trace:
//
//
// --02-29
//
// Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]
//
// at org.joda.time.field.FieldUtils.verifyValueBounds(FieldUtils.java:215)
//
// at org.joda.time.field.PreciseDurationDateTimeField.set(PreciseDurationDateTimeField.java:78)
//
// at org.joda.time.chrono.BasicMonthOfYearDateTimeField.add(BasicMonthOfYearDateTimeField.java:212)
//
// at org.joda.time.field.BaseDateTimeField.add(BaseDateTimeField.java:324)
//
// at org.joda.time.MonthDay.withFieldAdded(MonthDay.java:519)
//
// at org.joda.time.MonthDay.minusDays(MonthDay.java:672)
//
// at ext.site.time.chrono.Main.m7(Main.java:191)
//
// at ext.site.time.chrono.Main.main(Main.java:27)
//
//
// The follwing method calls and parameters also generate the same or related error:
//
//
//
// ```
// isoLeap.plusMonths(1);
// isoLeap.plusMonths(-1);
// isoLeap.minusMonths(1);
// isoLeap.minusMonths(-1);
// isoLeap.minusDays(-1);
//
// ```
//
// However, the following methods work:
//
//
//
// ```
// isoLeap.minusDays(1);
// isoLeap.plusDays(-1);
//
// ```
//
// Performing operations on dates around the ISO leap date react as if it exists, ie:
//
//
//
// ```
// System.out.println(isoLeap.minusDays(1).plusDays(2));
//
// ```
//
// Prints out '--03-01' as expected.
//
//
//
//
public void testPlusMonths_int_negativeFromLeap() {
| 462 | 14 | 457 | src/test/java/org/joda/time/TestMonthDay_Basics.java | src/test/java | ```markdown
## Issue-ID: Time-151
## Issue-Title:
#151 Unable to add days to a MonthDay set to the ISO leap date
## Issue-Description:
It's not possible to add days to a MonthDay set to the ISO leap date (February 29th). This is even more bizarre given the exact error message thrown.
Sample snippet:
```
final MonthDay isoLeap = new MonthDay(DateTimeConstants.FEBRUARY, 29, ISOChronology.getInstanceUTC());
System.out.println(isoLeap);
System.out.println(isoLeap.plusDays(2));
```
Which generates the following combined console output and stack trace:
--02-29
Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]
at org.joda.time.field.FieldUtils.verifyValueBounds(FieldUtils.java:215)
at org.joda.time.field.PreciseDurationDateTimeField.set(PreciseDurationDateTimeField.java:78)
at org.joda.time.chrono.BasicMonthOfYearDateTimeField.add(BasicMonthOfYearDateTimeField.java:212)
at org.joda.time.field.BaseDateTimeField.add(BaseDateTimeField.java:324)
at org.joda.time.MonthDay.withFieldAdded(MonthDay.java:519)
at org.joda.time.MonthDay.minusDays(MonthDay.java:672)
at ext.site.time.chrono.Main.m7(Main.java:191)
at ext.site.time.chrono.Main.main(Main.java:27)
The follwing method calls and parameters also generate the same or related error:
```
isoLeap.plusMonths(1);
isoLeap.plusMonths(-1);
isoLeap.minusMonths(1);
isoLeap.minusMonths(-1);
isoLeap.minusDays(-1);
```
However, the following methods work:
```
isoLeap.minusDays(1);
isoLeap.plusDays(-1);
```
Performing operations on dates around the ISO leap date react as if it exists, ie:
```
System.out.println(isoLeap.minusDays(1).plusDays(2));
```
Prints out '--03-01' as expected.
```
You are a professional Java test case writer, please create a test case named `testPlusMonths_int_negativeFromLeap` for the issue `Time-151`, utilizing the provided issue report information and the following function signature.
```java
public void testPlusMonths_int_negativeFromLeap() {
```
| 457 | [
"org.joda.time.chrono.BasicMonthOfYearDateTimeField"
] | 420c6f4f48cc6e754605e5cf45ad0e088cabf9bfb0d2c04c85ec14da31b70ce7 | public void testPlusMonths_int_negativeFromLeap() | // You are a professional Java test case writer, please create a test case named `testPlusMonths_int_negativeFromLeap` for the issue `Time-151`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-151
//
// ## Issue-Title:
// #151 Unable to add days to a MonthDay set to the ISO leap date
//
//
//
//
//
// ## Issue-Description:
// It's not possible to add days to a MonthDay set to the ISO leap date (February 29th). This is even more bizarre given the exact error message thrown.
//
//
// Sample snippet:
//
//
//
// ```
// final MonthDay isoLeap = new MonthDay(DateTimeConstants.FEBRUARY, 29, ISOChronology.getInstanceUTC());
// System.out.println(isoLeap);
// System.out.println(isoLeap.plusDays(2));
//
// ```
//
// Which generates the following combined console output and stack trace:
//
//
// --02-29
//
// Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]
//
// at org.joda.time.field.FieldUtils.verifyValueBounds(FieldUtils.java:215)
//
// at org.joda.time.field.PreciseDurationDateTimeField.set(PreciseDurationDateTimeField.java:78)
//
// at org.joda.time.chrono.BasicMonthOfYearDateTimeField.add(BasicMonthOfYearDateTimeField.java:212)
//
// at org.joda.time.field.BaseDateTimeField.add(BaseDateTimeField.java:324)
//
// at org.joda.time.MonthDay.withFieldAdded(MonthDay.java:519)
//
// at org.joda.time.MonthDay.minusDays(MonthDay.java:672)
//
// at ext.site.time.chrono.Main.m7(Main.java:191)
//
// at ext.site.time.chrono.Main.main(Main.java:27)
//
//
// The follwing method calls and parameters also generate the same or related error:
//
//
//
// ```
// isoLeap.plusMonths(1);
// isoLeap.plusMonths(-1);
// isoLeap.minusMonths(1);
// isoLeap.minusMonths(-1);
// isoLeap.minusDays(-1);
//
// ```
//
// However, the following methods work:
//
//
//
// ```
// isoLeap.minusDays(1);
// isoLeap.plusDays(-1);
//
// ```
//
// Performing operations on dates around the ISO leap date react as if it exists, ie:
//
//
//
// ```
// System.out.println(isoLeap.minusDays(1).plusDays(2));
//
// ```
//
// Prints out '--03-01' as expected.
//
//
//
//
| Time | /*
* Copyright 2001-2010 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 java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Locale;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.chrono.BuddhistChronology;
import org.joda.time.chrono.CopticChronology;
import org.joda.time.chrono.GregorianChronology;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* This class is a Junit unit test for MonthDay. Based on {@link TestYearMonth_Basics}
*/
public class TestMonthDay_Basics extends TestCase {
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 Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS);
// private static final Chronology COPTIC_LONDON = CopticChronology.getInstance(LONDON);
private static final Chronology COPTIC_TOKYO = CopticChronology.getInstance(TOKYO);
private static final Chronology COPTIC_UTC = CopticChronology.getInstanceUTC();
// private static final Chronology ISO_PARIS = ISOChronology.getInstance(PARIS);
// private static final Chronology ISO_LONDON = ISOChronology.getInstance(LONDON);
// private static final Chronology ISO_TOKYO = ISOChronology.getInstance(TOKYO);
private static final Chronology ISO_UTC = ISOChronology.getInstanceUTC();
// private static final Chronology BUDDHIST_PARIS = BuddhistChronology.getInstance(PARIS);
// private static final Chronology BUDDHIST_LONDON = BuddhistChronology.getInstance(LONDON);
private static final Chronology BUDDHIST_TOKYO = BuddhistChronology.getInstance(TOKYO);
private static final Chronology BUDDHIST_UTC = BuddhistChronology.getInstanceUTC();
private long TEST_TIME_NOW =
(31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
private DateTimeZone zone = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestMonthDay_Basics.class);
}
public TestMonthDay_Basics(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
zone = DateTimeZone.getDefault();
DateTimeZone.setDefault(LONDON);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(zone);
zone = null;
}
//-----------------------------------------------------------------------
public void testGet() {
MonthDay test = new MonthDay();
assertEquals(6, test.get(DateTimeFieldType.monthOfYear()));
assertEquals(9, test.get(DateTimeFieldType.dayOfMonth()));
try {
test.get(null);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.get(DateTimeFieldType.year());
fail();
} catch (IllegalArgumentException ex) {}
}
public void testSize() {
MonthDay test = new MonthDay();
assertEquals(2, test.size());
}
public void testGetFieldType() {
MonthDay test = new MonthDay(COPTIC_PARIS);
assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(0));
assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(1));
try {
test.getFieldType(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getFieldType(2);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetFieldTypes() {
MonthDay test = new MonthDay(COPTIC_PARIS);
DateTimeFieldType[] fields = test.getFieldTypes();
assertEquals(2, fields.length);
assertSame(DateTimeFieldType.monthOfYear(), fields[0]);
assertSame(DateTimeFieldType.dayOfMonth(), fields[1]);
assertNotSame(test.getFieldTypes(), test.getFieldTypes());
}
public void testGetField() {
MonthDay test = new MonthDay(COPTIC_PARIS);
assertSame(COPTIC_UTC.monthOfYear(), test.getField(0));
assertSame(COPTIC_UTC.dayOfMonth(), test.getField(1));
try {
test.getField(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getField(2);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetFields() {
MonthDay test = new MonthDay(COPTIC_PARIS);
DateTimeField[] fields = test.getFields();
assertEquals(2, fields.length);
assertSame(COPTIC_UTC.monthOfYear(), fields[0]);
assertSame(COPTIC_UTC.dayOfMonth(), fields[1]);
assertNotSame(test.getFields(), test.getFields());
}
public void testGetValue() {
MonthDay test = new MonthDay();
assertEquals(6, test.getValue(0));
assertEquals(9, test.getValue(1));
try {
test.getValue(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getValue(2);
} catch (IndexOutOfBoundsException ex) {}
}
public void testGetValues() {
MonthDay test = new MonthDay();
int[] values = test.getValues();
assertEquals(2, values.length);
assertEquals(6, values[0]);
assertEquals(9, values[1]);
assertNotSame(test.getValues(), test.getValues());
}
public void testIsSupported() {
MonthDay test = new MonthDay(COPTIC_PARIS);
assertEquals(false, test.isSupported(DateTimeFieldType.year()));
assertEquals(true, test.isSupported(DateTimeFieldType.monthOfYear()));
assertEquals(true, test.isSupported(DateTimeFieldType.dayOfMonth()));
assertEquals(false, test.isSupported(DateTimeFieldType.hourOfDay()));
}
public void testEqualsHashCode() {
MonthDay test1 = new MonthDay(10, 6, COPTIC_PARIS);
MonthDay test2 = new MonthDay(10, 6, COPTIC_PARIS);
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test1.equals(test1));
assertEquals(true, test2.equals(test2));
assertEquals(true, test1.hashCode() == test2.hashCode());
assertEquals(true, test1.hashCode() == test1.hashCode());
assertEquals(true, test2.hashCode() == test2.hashCode());
MonthDay test3 = new MonthDay(10, 6);
assertEquals(false, test1.equals(test3));
assertEquals(false, test2.equals(test3));
assertEquals(false, test3.equals(test1));
assertEquals(false, test3.equals(test2));
assertEquals(false, test1.hashCode() == test3.hashCode());
assertEquals(false, test2.hashCode() == test3.hashCode());
assertEquals(false, test1.equals("Hello"));
assertEquals(true, test1.equals(new MockMD()));
assertEquals(false, test1.equals(MockPartial.EMPTY_INSTANCE));
}
class MockMD extends MockPartial {
@Override
public Chronology getChronology() {
return COPTIC_UTC;
}
@Override
public DateTimeField[] getFields() {
return new DateTimeField[] {
COPTIC_UTC.monthOfYear(),
COPTIC_UTC.dayOfMonth()
};
}
@Override
public int[] getValues() {
return new int[] {10, 6};
}
}
//-----------------------------------------------------------------------
public void testCompareTo() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(0, test1.compareTo(test1a));
assertEquals(0, test1a.compareTo(test1));
assertEquals(0, test1.compareTo(test1));
assertEquals(0, test1a.compareTo(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(-1, test1.compareTo(test2));
assertEquals(+1, test2.compareTo(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(-1, test1.compareTo(test3));
assertEquals(+1, test3.compareTo(test1));
assertEquals(0, test3.compareTo(test2));
DateTimeFieldType[] types = new DateTimeFieldType[] {
DateTimeFieldType.monthOfYear(),
DateTimeFieldType.dayOfMonth()
};
int[] values = new int[] {6, 6};
Partial p = new Partial(types, values);
assertEquals(0, test1.compareTo(p));
try {
test1.compareTo(null);
fail();
} catch (NullPointerException ex) {}
try {
test1.compareTo(new LocalTime());
fail();
} catch (ClassCastException ex) {}
Partial partial = new Partial()
.with(DateTimeFieldType.centuryOfEra(), 1)
.with(DateTimeFieldType.halfdayOfDay(), 0)
.with(DateTimeFieldType.dayOfMonth(), 9);
try {
new MonthDay(10, 6).compareTo(partial);
fail();
} catch (ClassCastException ex) {}
}
//-----------------------------------------------------------------------
public void testIsEqual_MD() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(true, test1.isEqual(test1a));
assertEquals(true, test1a.isEqual(test1));
assertEquals(true, test1.isEqual(test1));
assertEquals(true, test1a.isEqual(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(false, test1.isEqual(test2));
assertEquals(false, test2.isEqual(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isEqual(test3));
assertEquals(false, test3.isEqual(test1));
assertEquals(true, test3.isEqual(test2));
try {
new MonthDay(6, 7).isEqual(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testIsBefore_MD() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(false, test1.isBefore(test1a));
assertEquals(false, test1a.isBefore(test1));
assertEquals(false, test1.isBefore(test1));
assertEquals(false, test1a.isBefore(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(true, test1.isBefore(test2));
assertEquals(false, test2.isBefore(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(true, test1.isBefore(test3));
assertEquals(false, test3.isBefore(test1));
assertEquals(false, test3.isBefore(test2));
try {
new MonthDay(6, 7).isBefore(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testIsAfter_MD() {
MonthDay test1 = new MonthDay(6, 6);
MonthDay test1a = new MonthDay(6, 6);
assertEquals(false, test1.isAfter(test1a));
assertEquals(false, test1a.isAfter(test1));
assertEquals(false, test1.isAfter(test1));
assertEquals(false, test1a.isAfter(test1a));
MonthDay test2 = new MonthDay(6, 7);
assertEquals(false, test1.isAfter(test2));
assertEquals(true, test2.isAfter(test1));
MonthDay test3 = new MonthDay(6, 7, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isAfter(test3));
assertEquals(true, test3.isAfter(test1));
assertEquals(false, test3.isAfter(test2));
try {
new MonthDay(6, 7).isAfter(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testWithChronologyRetainFields_Chrono() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
MonthDay test = base.withChronologyRetainFields(BUDDHIST_TOKYO);
check(base, 6, 6);
assertEquals(COPTIC_UTC, base.getChronology());
check(test, 6, 6);
assertEquals(BUDDHIST_UTC, test.getChronology());
}
public void testWithChronologyRetainFields_sameChrono() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
MonthDay test = base.withChronologyRetainFields(COPTIC_TOKYO);
assertSame(base, test);
}
public void testWithChronologyRetainFields_nullChrono() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
MonthDay test = base.withChronologyRetainFields(null);
check(base, 6, 6);
assertEquals(COPTIC_UTC, base.getChronology());
check(test, 6, 6);
assertEquals(ISO_UTC, test.getChronology());
}
//-----------------------------------------------------------------------
public void testWithField() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withField(DateTimeFieldType.monthOfYear(), 10);
assertEquals(new MonthDay(9, 6), test);
assertEquals(new MonthDay(10, 6), result);
}
public void testWithField_nullField() {
MonthDay test = new MonthDay(9, 6);
try {
test.withField(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithField_unknownField() {
MonthDay test = new MonthDay(9, 6);
try {
test.withField(DateTimeFieldType.hourOfDay(), 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithField_same() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withField(DateTimeFieldType.monthOfYear(), 9);
assertEquals(new MonthDay(9, 6), test);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testWithFieldAdded() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withFieldAdded(DurationFieldType.months(), 1);
assertEquals(new MonthDay(9, 6), test);
assertEquals(new MonthDay(10, 6), result);
}
public void testWithFieldAdded_nullField_zero() {
MonthDay test = new MonthDay(9, 6);
try {
test.withFieldAdded(null, 0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithFieldAdded_nullField_nonZero() {
MonthDay test = new MonthDay(9, 6);
try {
test.withFieldAdded(null, 6);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testWithFieldAdded_zero() {
MonthDay test = new MonthDay(9, 6);
MonthDay result = test.withFieldAdded(DurationFieldType.months(), 0);
assertSame(test, result);
}
public void testWithFieldAdded_unknownField() {
MonthDay test = new MonthDay(9, 6);
try {
test.withFieldAdded(DurationFieldType.hours(), 6);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testPlus_RP() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.plus(new Period(1, 2, 3, 4, 5, 6, 7, 8));
MonthDay expected = new MonthDay(8, 9, BuddhistChronology.getInstance());
assertEquals(expected, result);
result = test.plus((ReadablePeriod) null);
assertSame(test, result);
}
public void testPlusMonths_int() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.plusMonths(1);
MonthDay expected = new MonthDay(7, 5, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(1);
MonthDay expected = new MonthDay(3, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(-1);
MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_endOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(1);
MonthDay expected = new MonthDay(4, 30, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_negativeEndOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.plusMonths(-1);
MonthDay expected = new MonthDay(2, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusMonths_int_same() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.plusMonths(0);
assertSame(test, result);
}
public void testPlusMonths_int_wrap() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.plusMonths(10);
MonthDay expected = new MonthDay(4, 5, ISO_UTC);
assertEquals(expected, result);
}
public void testPlusMonths_int_adjust() {
MonthDay test = new MonthDay(7, 31, ISO_UTC);
MonthDay result = test.plusMonths(2);
MonthDay expected = new MonthDay(9, 30, ISO_UTC);
assertEquals(expected, result);
}
//-------------------------------------------------------------------------
public void testPlusDays_int() {
MonthDay test = new MonthDay(5, 10, BuddhistChronology.getInstance());
MonthDay result = test.plusDays(1);
MonthDay expected = new MonthDay(5, 11, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusDays_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusDays(1);
MonthDay expected = new MonthDay(3, 1, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusDays_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.plusDays(-1);
MonthDay expected = new MonthDay(2, 28, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testPlusDays_same() {
MonthDay test = new MonthDay(5, 10, BuddhistChronology.getInstance());
MonthDay result = test.plusDays(0);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testMinus_RP() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.minus(new Period(1, 1, 1, 1, 1, 1, 1, 1));
MonthDay expected = new MonthDay(5, 4, BuddhistChronology.getInstance());
assertEquals(expected, result);
result = test.minus((ReadablePeriod) null);
assertSame(test, result);
}
public void testMinusMonths_int() {
MonthDay test = new MonthDay(6, 5, BuddhistChronology.getInstance());
MonthDay result = test.minusMonths(1);
MonthDay expected = new MonthDay(5, 5, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(1);
MonthDay expected = new MonthDay(1, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(-1);
MonthDay expected = new MonthDay(3, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_endOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(1);
MonthDay expected = new MonthDay(2, 29, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_negativeEndOfMonthAdjust() {
MonthDay test = new MonthDay(3, 31, ISOChronology.getInstanceUTC());
MonthDay result = test.minusMonths(-1);
MonthDay expected = new MonthDay(4, 30, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusMonths_int_same() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.minusMonths(0);
assertSame(test, result);
}
public void testMinusMonths_int_wrap() {
MonthDay test = new MonthDay(6, 5, ISO_UTC);
MonthDay result = test.minusMonths(10);
MonthDay expected = new MonthDay(8, 5, ISO_UTC);
assertEquals(expected, result);
}
public void testMinusMonths_int_adjust() {
MonthDay test = new MonthDay(7, 31, ISO_UTC);
MonthDay result = test.minusMonths(3);
MonthDay expected = new MonthDay(4, 30, ISO_UTC);
assertEquals(expected, result);
}
//-------------------------------------------------------------------------
public void testMinusDays_int() {
MonthDay test = new MonthDay(5, 11, BuddhistChronology.getInstance());
MonthDay result = test.minusDays(1);
MonthDay expected = new MonthDay(5, 10, BuddhistChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusDays_int_fromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusDays(1);
MonthDay expected = new MonthDay(2, 28, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusDays_int_negativeFromLeap() {
MonthDay test = new MonthDay(2, 29, ISOChronology.getInstanceUTC());
MonthDay result = test.minusDays(-1);
MonthDay expected = new MonthDay(3, 1, ISOChronology.getInstance());
assertEquals(expected, result);
}
public void testMinusDays_same() {
MonthDay test = new MonthDay(5, 11, BuddhistChronology.getInstance());
MonthDay result = test.minusDays(0);
assertSame(test, result);
}
//-----------------------------------------------------------------------
public void testToLocalDate() {
MonthDay base = new MonthDay(6, 6, COPTIC_UTC);
LocalDate test = base.toLocalDate(2009);
assertEquals(new LocalDate(2009, 6, 6, COPTIC_UTC), test);
try {
base.toLocalDate(0);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testToDateTime_RI() {
MonthDay base = new MonthDay(6, 6, COPTIC_PARIS);
DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
DateTime test = base.toDateTime(dt);
check(base, 6, 6);
DateTime expected = dt;
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(6);
assertEquals(expected, test);
}
public void testToDateTime_nullRI() {
MonthDay base = new MonthDay(6, 6);
DateTime dt = new DateTime(2002, 1, 3, 4, 5, 6, 7);
DateTimeUtils.setCurrentMillisFixed(dt.getMillis());
DateTime test = base.toDateTime((ReadableInstant) null);
check(base, 6, 6);
DateTime expected = dt;
expected = expected.monthOfYear().setCopy(6);
expected = expected.dayOfMonth().setCopy(6);
assertEquals(expected, test);
}
//-----------------------------------------------------------------------
public void testWithers() {
MonthDay test = new MonthDay(10, 6);
check(test.withMonthOfYear(5), 5, 6);
check(test.withDayOfMonth(2), 10, 2);
try {
test.withMonthOfYear(0);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.withMonthOfYear(13);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testProperty() {
MonthDay test = new MonthDay(6, 6);
assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear()));
assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth()));
try {
test.property(DateTimeFieldType.millisOfDay());
fail();
} catch (IllegalArgumentException ex) {}
try {
test.property(null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testSerialization() throws Exception {
MonthDay test = new MonthDay(5, 6, COPTIC_PARIS);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test);
byte[] bytes = baos.toByteArray();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
MonthDay result = (MonthDay) ois.readObject();
ois.close();
assertEquals(test, result);
assertTrue(Arrays.equals(test.getValues(), result.getValues()));
assertTrue(Arrays.equals(test.getFields(), result.getFields()));
assertEquals(test.getChronology(), result.getChronology());
}
//-----------------------------------------------------------------------
public void testToString() {
MonthDay test = new MonthDay(5, 6);
assertEquals("--05-06", test.toString());
}
//-----------------------------------------------------------------------
public void testToString_String() {
MonthDay test = new MonthDay(5, 6);
assertEquals("05 \ufffd\ufffd", test.toString("MM HH"));
assertEquals("--05-06", test.toString((String) null));
}
//-----------------------------------------------------------------------
public void testToString_String_Locale() {
MonthDay test = new MonthDay(5, 6);
assertEquals("\ufffd 6/5", test.toString("EEE d/M", Locale.ENGLISH));
assertEquals("\ufffd 6/5", test.toString("EEE d/M", Locale.FRENCH));
assertEquals("--05-06", test.toString(null, Locale.ENGLISH));
assertEquals("\ufffd 6/5", test.toString("EEE d/M", null));
assertEquals("--05-06", test.toString(null, null));
}
//-----------------------------------------------------------------------
public void testToString_DTFormatter() {
MonthDay test = new MonthDay(5, 6);
assertEquals("05 \ufffd\ufffd", test.toString(DateTimeFormat.forPattern("MM HH")));
assertEquals("--05-06", test.toString((DateTimeFormatter) null));
}
//-----------------------------------------------------------------------
private void check(MonthDay test, int month, int day) {
assertEquals(month, test.getMonthOfYear());
assertEquals(day, test.getDayOfMonth());
}
} |
||
public void testSSENonNegative() {
double[] y = { 8915.102, 8919.302, 8923.502 };
double[] x = { 1.107178495E2, 1.107264895E2, 1.107351295E2 };
SimpleRegression reg = new SimpleRegression();
for (int i = 0; i < x.length; i++) {
reg.addData(x[i], y[i]);
}
assertTrue(reg.getSumSquaredErrors() >= 0.0);
} | org.apache.commons.math.stat.regression.SimpleRegressionTest::testSSENonNegative | src/test/org/apache/commons/math/stat/regression/SimpleRegressionTest.java | 275 | src/test/org/apache/commons/math/stat/regression/SimpleRegressionTest.java | testSSENonNegative | /*
* Copyright 2003-2004 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.math.stat.regression;
import java.util.Random;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test cases for the TestStatistic class.
*
* @version $Revision$ $Date$
*/
public final class SimpleRegressionTest extends TestCase {
/*
* NIST "Norris" refernce data set from
* http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Norris.dat
* Strangely, order is {y,x}
*/
private double[][] data = { { 0.1, 0.2 }, {338.8, 337.4 }, {118.1, 118.2 },
{888.0, 884.6 }, {9.2, 10.1 }, {228.1, 226.5 }, {668.5, 666.3 }, {998.5, 996.3 },
{449.1, 448.6 }, {778.9, 777.0 }, {559.2, 558.2 }, {0.3, 0.4 }, {0.1, 0.6 }, {778.1, 775.5 },
{668.8, 666.9 }, {339.3, 338.0 }, {448.9, 447.5 }, {10.8, 11.6 }, {557.7, 556.0 },
{228.3, 228.1 }, {998.0, 995.8 }, {888.8, 887.6 }, {119.6, 120.2 }, {0.3, 0.3 },
{0.6, 0.3 }, {557.6, 556.8 }, {339.3, 339.1 }, {888.0, 887.2 }, {998.5, 999.0 },
{778.9, 779.0 }, {10.2, 11.1 }, {117.6, 118.3 }, {228.9, 229.2 }, {668.4, 669.1 },
{449.2, 448.9 }, {0.2, 0.5 }
};
/*
* Correlation example from
* http://www.xycoon.com/correlation.htm
*/
private double[][] corrData = { { 101.0, 99.2 }, {100.1, 99.0 }, {100.0, 100.0 },
{90.6, 111.6 }, {86.5, 122.2 }, {89.7, 117.6 }, {90.6, 121.1 }, {82.8, 136.0 },
{70.1, 154.2 }, {65.4, 153.6 }, {61.3, 158.5 }, {62.5, 140.6 }, {63.6, 136.2 },
{52.6, 168.0 }, {59.7, 154.3 }, {59.5, 149.0 }, {61.3, 165.5 }
};
/*
* From Moore and Mcabe, "Introduction to the Practice of Statistics"
* Example 10.3
*/
private double[][] infData = { { 15.6, 5.2 }, {26.8, 6.1 }, {37.8, 8.7 }, {36.4, 8.5 },
{35.5, 8.8 }, {18.6, 4.9 }, {15.3, 4.5 }, {7.9, 2.5 }, {0.0, 1.1 }
};
/*
* Data with bad linear fit
*/
private double[][] infData2 = { { 1, 1 }, {2, 0 }, {3, 5 }, {4, 2 },
{5, -1 }, {6, 12 }
};
public SimpleRegressionTest(String name) {
super(name);
}
public void setUp() {
}
public static Test suite() {
TestSuite suite = new TestSuite(SimpleRegressionTest.class);
suite.setName("BivariateRegression Tests");
return suite;
}
public void testNorris() {
SimpleRegression regression = new SimpleRegression();
for (int i = 0; i < data.length; i++) {
regression.addData(data[i][1], data[i][0]);
}
// Tests against certified values from
// http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Norris.dat
assertEquals("slope", 1.00211681802045, regression.getSlope(), 10E-12);
assertEquals("slope std err", 0.429796848199937E-03,
regression.getSlopeStdErr(),10E-12);
assertEquals("number of observations", 36, regression.getN());
assertEquals( "intercept", -0.262323073774029,
regression.getIntercept(),10E-12);
assertEquals("std err intercept", 0.232818234301152,
regression.getInterceptStdErr(),10E-12);
assertEquals("r-square", 0.999993745883712,
regression.getRSquare(), 10E-12);
assertEquals("SSR", 4255954.13232369,
regression.getRegressionSumSquares(), 10E-9);
assertEquals("MSE", 0.782864662630069,
regression.getMeanSquareError(), 10E-10);
assertEquals("SSE", 26.6173985294224,
regression.getSumSquaredErrors(),10E-9);
// ------------ End certified data tests
assertEquals( "predict(0)", -0.262323073774029,
regression.predict(0), 10E-12);
assertEquals("predict(1)", 1.00211681802045 - 0.262323073774029,
regression.predict(1), 10E-12);
}
public void testCorr() {
SimpleRegression regression = new SimpleRegression();
regression.addData(corrData);
assertEquals("number of observations", 17, regression.getN());
assertEquals("r-square", .896123, regression.getRSquare(), 10E-6);
assertEquals("r", -0.94663767742, regression.getR(), 1E-10);
}
public void testNaNs() {
SimpleRegression regression = new SimpleRegression();
assertTrue("intercept not NaN", Double.isNaN(regression.getIntercept()));
assertTrue("slope not NaN", Double.isNaN(regression.getSlope()));
assertTrue("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err not NaN", Double.isNaN(regression.getInterceptStdErr()));
assertTrue("MSE not NaN", Double.isNaN(regression.getMeanSquareError()));
assertTrue("e not NaN", Double.isNaN(regression.getR()));
assertTrue("r-square not NaN", Double.isNaN(regression.getRSquare()));
assertTrue( "RSS not NaN", Double.isNaN(regression.getRegressionSumSquares()));
assertTrue("SSE not NaN",Double.isNaN(regression.getSumSquaredErrors()));
assertTrue("SSTO not NaN", Double.isNaN(regression.getTotalSumSquares()));
assertTrue("predict not NaN", Double.isNaN(regression.predict(0)));
regression.addData(1, 2);
regression.addData(1, 3);
// No x variation, so these should still blow...
assertTrue("intercept not NaN", Double.isNaN(regression.getIntercept()));
assertTrue("slope not NaN", Double.isNaN(regression.getSlope()));
assertTrue("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err not NaN", Double.isNaN(regression.getInterceptStdErr()));
assertTrue("MSE not NaN", Double.isNaN(regression.getMeanSquareError()));
assertTrue("e not NaN", Double.isNaN(regression.getR()));
assertTrue("r-square not NaN", Double.isNaN(regression.getRSquare()));
assertTrue("RSS not NaN", Double.isNaN(regression.getRegressionSumSquares()));
assertTrue("SSE not NaN", Double.isNaN(regression.getSumSquaredErrors()));
assertTrue("predict not NaN", Double.isNaN(regression.predict(0)));
// but SSTO should be OK
assertTrue("SSTO NaN", !Double.isNaN(regression.getTotalSumSquares()));
regression = new SimpleRegression();
regression.addData(1, 2);
regression.addData(3, 3);
// All should be OK except MSE, s(b0), s(b1) which need one more df
assertTrue("interceptNaN", !Double.isNaN(regression.getIntercept()));
assertTrue("slope NaN", !Double.isNaN(regression.getSlope()));
assertTrue ("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err not NaN", Double.isNaN(regression.getInterceptStdErr()));
assertTrue("MSE not NaN", Double.isNaN(regression.getMeanSquareError()));
assertTrue("r NaN", !Double.isNaN(regression.getR()));
assertTrue("r-square NaN", !Double.isNaN(regression.getRSquare()));
assertTrue("RSS NaN", !Double.isNaN(regression.getRegressionSumSquares()));
assertTrue("SSE NaN", !Double.isNaN(regression.getSumSquaredErrors()));
assertTrue("SSTO NaN", !Double.isNaN(regression.getTotalSumSquares()));
assertTrue("predict NaN", !Double.isNaN(regression.predict(0)));
regression.addData(1, 4);
// MSE, MSE, s(b0), s(b1) should all be OK now
assertTrue("MSE NaN", !Double.isNaN(regression.getMeanSquareError()));
assertTrue("slope std err NaN", !Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err NaN", !Double.isNaN(regression.getInterceptStdErr()));
}
public void testClear() {
SimpleRegression regression = new SimpleRegression();
regression.addData(corrData);
assertEquals("number of observations", 17, regression.getN());
regression.clear();
assertEquals("number of observations", 0, regression.getN());
regression.addData(corrData);
assertEquals("r-square", .896123, regression.getRSquare(), 10E-6);
regression.addData(data);
assertEquals("number of observations", 53, regression.getN());
}
public void testInference() throws Exception {
//---------- verified against R, version 1.8.1 -----
// infData
SimpleRegression regression = new SimpleRegression();
regression.addData(infData);
assertEquals("slope std err", 0.011448491,
regression.getSlopeStdErr(), 1E-10);
assertEquals("std err intercept", 0.286036932,
regression.getInterceptStdErr(),1E-8);
assertEquals("significance", 4.596e-07,
regression.getSignificance(),1E-8);
assertEquals("slope conf interval half-width", 0.0270713794287,
regression.getSlopeConfidenceInterval(),1E-8);
// infData2
regression = new SimpleRegression();
regression.addData(infData2);
assertEquals("slope std err", 1.07260253,
regression.getSlopeStdErr(), 1E-8);
assertEquals("std err intercept",4.17718672,
regression.getInterceptStdErr(),1E-8);
assertEquals("significance", 0.261829133982,
regression.getSignificance(),1E-11);
assertEquals("slope conf interval half-width", 2.97802204827,
regression.getSlopeConfidenceInterval(),1E-8);
//------------- End R-verified tests -------------------------------
//FIXME: get a real example to test against with alpha = .01
assertTrue("tighter means wider",
regression.getSlopeConfidenceInterval() < regression.getSlopeConfidenceInterval(0.01));
try {
double x = regression.getSlopeConfidenceInterval(1);
fail("expecting IllegalArgumentException for alpha = 1");
} catch (IllegalArgumentException ex) {
;
}
}
public void testPerfect() throws Exception {
SimpleRegression regression = new SimpleRegression();
int n = 100;
for (int i = 0; i < n; i++) {
regression.addData(((double) i) / (n - 1), i);
}
assertEquals(0.0, regression.getSignificance(), 1.0e-5);
assertTrue(regression.getSlope() > 0.0);
assertTrue(regression.getSumSquaredErrors() >= 0.0);
}
public void testPerfectNegative() throws Exception {
SimpleRegression regression = new SimpleRegression();
int n = 100;
for (int i = 0; i < n; i++) {
regression.addData(- ((double) i) / (n - 1), i);
}
assertEquals(0.0, regression.getSignificance(), 1.0e-5);
assertTrue(regression.getSlope() < 0.0);
}
public void testRandom() throws Exception {
SimpleRegression regression = new SimpleRegression();
Random random = new Random(1);
int n = 100;
for (int i = 0; i < n; i++) {
regression.addData(((double) i) / (n - 1), random.nextDouble());
}
assertTrue( 0.0 < regression.getSignificance()
&& regression.getSignificance() < 1.0);
}
// Jira MATH-85 = Bugzilla 39432
public void testSSENonNegative() {
double[] y = { 8915.102, 8919.302, 8923.502 };
double[] x = { 1.107178495E2, 1.107264895E2, 1.107351295E2 };
SimpleRegression reg = new SimpleRegression();
for (int i = 0; i < x.length; i++) {
reg.addData(x[i], y[i]);
}
assertTrue(reg.getSumSquaredErrors() >= 0.0);
}
} | // You are a professional Java test case writer, please create a test case named `testSSENonNegative` for the issue `Math-MATH-85`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-85
//
// ## Issue-Title:
// [math] SimpleRegression getSumSquaredErrors
//
// ## Issue-Description:
//
// getSumSquaredErrors returns -ve value. See test below:
//
//
// public void testSimpleRegression() {
//
// double[] y =
//
//
// { 8915.102, 8919.302, 8923.502}
// ;
//
// double[] x =
//
//
// { 1.107178495, 1.107264895, 1.107351295}
// ;
//
// double[] x2 =
//
//
// { 1.107178495E2, 1.107264895E2, 1.107351295E2}
// ;
//
// SimpleRegression reg = new SimpleRegression();
//
// for (int i = 0; i < x.length; i++)
//
//
// {
// reg.addData(x[i],y[i]);
// }
// assertTrue(reg.getSumSquaredErrors() >= 0.0); // OK
//
// reg.clear();
//
// for (int i = 0; i < x.length; i++)
//
//
// {
// reg.addData(x2[i],y[i]);
// }
// assertTrue(reg.getSumSquaredErrors() >= 0.0); // FAIL
//
//
// }
//
//
//
//
//
public void testSSENonNegative() {
| 275 | // Jira MATH-85 = Bugzilla 39432 | 105 | 267 | src/test/org/apache/commons/math/stat/regression/SimpleRegressionTest.java | src/test | ```markdown
## Issue-ID: Math-MATH-85
## Issue-Title:
[math] SimpleRegression getSumSquaredErrors
## Issue-Description:
getSumSquaredErrors returns -ve value. See test below:
public void testSimpleRegression() {
double[] y =
{ 8915.102, 8919.302, 8923.502}
;
double[] x =
{ 1.107178495, 1.107264895, 1.107351295}
;
double[] x2 =
{ 1.107178495E2, 1.107264895E2, 1.107351295E2}
;
SimpleRegression reg = new SimpleRegression();
for (int i = 0; i < x.length; i++)
{
reg.addData(x[i],y[i]);
}
assertTrue(reg.getSumSquaredErrors() >= 0.0); // OK
reg.clear();
for (int i = 0; i < x.length; i++)
{
reg.addData(x2[i],y[i]);
}
assertTrue(reg.getSumSquaredErrors() >= 0.0); // FAIL
}
```
You are a professional Java test case writer, please create a test case named `testSSENonNegative` for the issue `Math-MATH-85`, utilizing the provided issue report information and the following function signature.
```java
public void testSSENonNegative() {
```
| 267 | [
"org.apache.commons.math.stat.regression.SimpleRegression"
] | 424adf8d1a8235482af9d0d0115df379b7296c3a68c00f8c5b49e6c4fd022949 | public void testSSENonNegative() | // You are a professional Java test case writer, please create a test case named `testSSENonNegative` for the issue `Math-MATH-85`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-85
//
// ## Issue-Title:
// [math] SimpleRegression getSumSquaredErrors
//
// ## Issue-Description:
//
// getSumSquaredErrors returns -ve value. See test below:
//
//
// public void testSimpleRegression() {
//
// double[] y =
//
//
// { 8915.102, 8919.302, 8923.502}
// ;
//
// double[] x =
//
//
// { 1.107178495, 1.107264895, 1.107351295}
// ;
//
// double[] x2 =
//
//
// { 1.107178495E2, 1.107264895E2, 1.107351295E2}
// ;
//
// SimpleRegression reg = new SimpleRegression();
//
// for (int i = 0; i < x.length; i++)
//
//
// {
// reg.addData(x[i],y[i]);
// }
// assertTrue(reg.getSumSquaredErrors() >= 0.0); // OK
//
// reg.clear();
//
// for (int i = 0; i < x.length; i++)
//
//
// {
// reg.addData(x2[i],y[i]);
// }
// assertTrue(reg.getSumSquaredErrors() >= 0.0); // FAIL
//
//
// }
//
//
//
//
//
| Math | /*
* Copyright 2003-2004 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.math.stat.regression;
import java.util.Random;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test cases for the TestStatistic class.
*
* @version $Revision$ $Date$
*/
public final class SimpleRegressionTest extends TestCase {
/*
* NIST "Norris" refernce data set from
* http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Norris.dat
* Strangely, order is {y,x}
*/
private double[][] data = { { 0.1, 0.2 }, {338.8, 337.4 }, {118.1, 118.2 },
{888.0, 884.6 }, {9.2, 10.1 }, {228.1, 226.5 }, {668.5, 666.3 }, {998.5, 996.3 },
{449.1, 448.6 }, {778.9, 777.0 }, {559.2, 558.2 }, {0.3, 0.4 }, {0.1, 0.6 }, {778.1, 775.5 },
{668.8, 666.9 }, {339.3, 338.0 }, {448.9, 447.5 }, {10.8, 11.6 }, {557.7, 556.0 },
{228.3, 228.1 }, {998.0, 995.8 }, {888.8, 887.6 }, {119.6, 120.2 }, {0.3, 0.3 },
{0.6, 0.3 }, {557.6, 556.8 }, {339.3, 339.1 }, {888.0, 887.2 }, {998.5, 999.0 },
{778.9, 779.0 }, {10.2, 11.1 }, {117.6, 118.3 }, {228.9, 229.2 }, {668.4, 669.1 },
{449.2, 448.9 }, {0.2, 0.5 }
};
/*
* Correlation example from
* http://www.xycoon.com/correlation.htm
*/
private double[][] corrData = { { 101.0, 99.2 }, {100.1, 99.0 }, {100.0, 100.0 },
{90.6, 111.6 }, {86.5, 122.2 }, {89.7, 117.6 }, {90.6, 121.1 }, {82.8, 136.0 },
{70.1, 154.2 }, {65.4, 153.6 }, {61.3, 158.5 }, {62.5, 140.6 }, {63.6, 136.2 },
{52.6, 168.0 }, {59.7, 154.3 }, {59.5, 149.0 }, {61.3, 165.5 }
};
/*
* From Moore and Mcabe, "Introduction to the Practice of Statistics"
* Example 10.3
*/
private double[][] infData = { { 15.6, 5.2 }, {26.8, 6.1 }, {37.8, 8.7 }, {36.4, 8.5 },
{35.5, 8.8 }, {18.6, 4.9 }, {15.3, 4.5 }, {7.9, 2.5 }, {0.0, 1.1 }
};
/*
* Data with bad linear fit
*/
private double[][] infData2 = { { 1, 1 }, {2, 0 }, {3, 5 }, {4, 2 },
{5, -1 }, {6, 12 }
};
public SimpleRegressionTest(String name) {
super(name);
}
public void setUp() {
}
public static Test suite() {
TestSuite suite = new TestSuite(SimpleRegressionTest.class);
suite.setName("BivariateRegression Tests");
return suite;
}
public void testNorris() {
SimpleRegression regression = new SimpleRegression();
for (int i = 0; i < data.length; i++) {
regression.addData(data[i][1], data[i][0]);
}
// Tests against certified values from
// http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Norris.dat
assertEquals("slope", 1.00211681802045, regression.getSlope(), 10E-12);
assertEquals("slope std err", 0.429796848199937E-03,
regression.getSlopeStdErr(),10E-12);
assertEquals("number of observations", 36, regression.getN());
assertEquals( "intercept", -0.262323073774029,
regression.getIntercept(),10E-12);
assertEquals("std err intercept", 0.232818234301152,
regression.getInterceptStdErr(),10E-12);
assertEquals("r-square", 0.999993745883712,
regression.getRSquare(), 10E-12);
assertEquals("SSR", 4255954.13232369,
regression.getRegressionSumSquares(), 10E-9);
assertEquals("MSE", 0.782864662630069,
regression.getMeanSquareError(), 10E-10);
assertEquals("SSE", 26.6173985294224,
regression.getSumSquaredErrors(),10E-9);
// ------------ End certified data tests
assertEquals( "predict(0)", -0.262323073774029,
regression.predict(0), 10E-12);
assertEquals("predict(1)", 1.00211681802045 - 0.262323073774029,
regression.predict(1), 10E-12);
}
public void testCorr() {
SimpleRegression regression = new SimpleRegression();
regression.addData(corrData);
assertEquals("number of observations", 17, regression.getN());
assertEquals("r-square", .896123, regression.getRSquare(), 10E-6);
assertEquals("r", -0.94663767742, regression.getR(), 1E-10);
}
public void testNaNs() {
SimpleRegression regression = new SimpleRegression();
assertTrue("intercept not NaN", Double.isNaN(regression.getIntercept()));
assertTrue("slope not NaN", Double.isNaN(regression.getSlope()));
assertTrue("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err not NaN", Double.isNaN(regression.getInterceptStdErr()));
assertTrue("MSE not NaN", Double.isNaN(regression.getMeanSquareError()));
assertTrue("e not NaN", Double.isNaN(regression.getR()));
assertTrue("r-square not NaN", Double.isNaN(regression.getRSquare()));
assertTrue( "RSS not NaN", Double.isNaN(regression.getRegressionSumSquares()));
assertTrue("SSE not NaN",Double.isNaN(regression.getSumSquaredErrors()));
assertTrue("SSTO not NaN", Double.isNaN(regression.getTotalSumSquares()));
assertTrue("predict not NaN", Double.isNaN(regression.predict(0)));
regression.addData(1, 2);
regression.addData(1, 3);
// No x variation, so these should still blow...
assertTrue("intercept not NaN", Double.isNaN(regression.getIntercept()));
assertTrue("slope not NaN", Double.isNaN(regression.getSlope()));
assertTrue("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err not NaN", Double.isNaN(regression.getInterceptStdErr()));
assertTrue("MSE not NaN", Double.isNaN(regression.getMeanSquareError()));
assertTrue("e not NaN", Double.isNaN(regression.getR()));
assertTrue("r-square not NaN", Double.isNaN(regression.getRSquare()));
assertTrue("RSS not NaN", Double.isNaN(regression.getRegressionSumSquares()));
assertTrue("SSE not NaN", Double.isNaN(regression.getSumSquaredErrors()));
assertTrue("predict not NaN", Double.isNaN(regression.predict(0)));
// but SSTO should be OK
assertTrue("SSTO NaN", !Double.isNaN(regression.getTotalSumSquares()));
regression = new SimpleRegression();
regression.addData(1, 2);
regression.addData(3, 3);
// All should be OK except MSE, s(b0), s(b1) which need one more df
assertTrue("interceptNaN", !Double.isNaN(regression.getIntercept()));
assertTrue("slope NaN", !Double.isNaN(regression.getSlope()));
assertTrue ("slope std err not NaN", Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err not NaN", Double.isNaN(regression.getInterceptStdErr()));
assertTrue("MSE not NaN", Double.isNaN(regression.getMeanSquareError()));
assertTrue("r NaN", !Double.isNaN(regression.getR()));
assertTrue("r-square NaN", !Double.isNaN(regression.getRSquare()));
assertTrue("RSS NaN", !Double.isNaN(regression.getRegressionSumSquares()));
assertTrue("SSE NaN", !Double.isNaN(regression.getSumSquaredErrors()));
assertTrue("SSTO NaN", !Double.isNaN(regression.getTotalSumSquares()));
assertTrue("predict NaN", !Double.isNaN(regression.predict(0)));
regression.addData(1, 4);
// MSE, MSE, s(b0), s(b1) should all be OK now
assertTrue("MSE NaN", !Double.isNaN(regression.getMeanSquareError()));
assertTrue("slope std err NaN", !Double.isNaN(regression.getSlopeStdErr()));
assertTrue("intercept std err NaN", !Double.isNaN(regression.getInterceptStdErr()));
}
public void testClear() {
SimpleRegression regression = new SimpleRegression();
regression.addData(corrData);
assertEquals("number of observations", 17, regression.getN());
regression.clear();
assertEquals("number of observations", 0, regression.getN());
regression.addData(corrData);
assertEquals("r-square", .896123, regression.getRSquare(), 10E-6);
regression.addData(data);
assertEquals("number of observations", 53, regression.getN());
}
public void testInference() throws Exception {
//---------- verified against R, version 1.8.1 -----
// infData
SimpleRegression regression = new SimpleRegression();
regression.addData(infData);
assertEquals("slope std err", 0.011448491,
regression.getSlopeStdErr(), 1E-10);
assertEquals("std err intercept", 0.286036932,
regression.getInterceptStdErr(),1E-8);
assertEquals("significance", 4.596e-07,
regression.getSignificance(),1E-8);
assertEquals("slope conf interval half-width", 0.0270713794287,
regression.getSlopeConfidenceInterval(),1E-8);
// infData2
regression = new SimpleRegression();
regression.addData(infData2);
assertEquals("slope std err", 1.07260253,
regression.getSlopeStdErr(), 1E-8);
assertEquals("std err intercept",4.17718672,
regression.getInterceptStdErr(),1E-8);
assertEquals("significance", 0.261829133982,
regression.getSignificance(),1E-11);
assertEquals("slope conf interval half-width", 2.97802204827,
regression.getSlopeConfidenceInterval(),1E-8);
//------------- End R-verified tests -------------------------------
//FIXME: get a real example to test against with alpha = .01
assertTrue("tighter means wider",
regression.getSlopeConfidenceInterval() < regression.getSlopeConfidenceInterval(0.01));
try {
double x = regression.getSlopeConfidenceInterval(1);
fail("expecting IllegalArgumentException for alpha = 1");
} catch (IllegalArgumentException ex) {
;
}
}
public void testPerfect() throws Exception {
SimpleRegression regression = new SimpleRegression();
int n = 100;
for (int i = 0; i < n; i++) {
regression.addData(((double) i) / (n - 1), i);
}
assertEquals(0.0, regression.getSignificance(), 1.0e-5);
assertTrue(regression.getSlope() > 0.0);
assertTrue(regression.getSumSquaredErrors() >= 0.0);
}
public void testPerfectNegative() throws Exception {
SimpleRegression regression = new SimpleRegression();
int n = 100;
for (int i = 0; i < n; i++) {
regression.addData(- ((double) i) / (n - 1), i);
}
assertEquals(0.0, regression.getSignificance(), 1.0e-5);
assertTrue(regression.getSlope() < 0.0);
}
public void testRandom() throws Exception {
SimpleRegression regression = new SimpleRegression();
Random random = new Random(1);
int n = 100;
for (int i = 0; i < n; i++) {
regression.addData(((double) i) / (n - 1), random.nextDouble());
}
assertTrue( 0.0 < regression.getSignificance()
&& regression.getSignificance() < 1.0);
}
// Jira MATH-85 = Bugzilla 39432
public void testSSENonNegative() {
double[] y = { 8915.102, 8919.302, 8923.502 };
double[] x = { 1.107178495E2, 1.107264895E2, 1.107351295E2 };
SimpleRegression reg = new SimpleRegression();
for (int i = 0; i < x.length; i++) {
reg.addData(x[i], y[i]);
}
assertTrue(reg.getSumSquaredErrors() >= 0.0);
}
} |
|
@Test
public void handlesInvalidAttributeNames() {
String html = "<html><head></head><body style=\"color: red\" \" name\"></body></html>";
org.jsoup.nodes.Document jsoupDoc;
jsoupDoc = Jsoup.parse(html);
Element body = jsoupDoc.select("body").first();
assertTrue(body.hasAttr("\"")); // actually an attribute with key '"'. Correct per HTML5 spec, but w3c xml dom doesn't dig it
assertTrue(body.hasAttr("name\""));
Document w3Doc = new W3CDom().fromJsoup(jsoupDoc);
} | org.jsoup.helper.W3CDomTest::handlesInvalidAttributeNames | src/test/java/org/jsoup/helper/W3CDomTest.java | 93 | src/test/java/org/jsoup/helper/W3CDomTest.java | handlesInvalidAttributeNames | package org.jsoup.helper;
import org.jsoup.Jsoup;
import org.jsoup.integration.ParseTest;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.io.File;
import java.io.IOException;
import static org.jsoup.TextUtil.LE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class W3CDomTest {
@Test
public void simpleConversion() {
String html = "<html><head><title>W3c</title></head><body><p class='one' id=12>Text</p><!-- comment --><invalid>What<script>alert('!')";
org.jsoup.nodes.Document doc = Jsoup.parse(html);
W3CDom w3c = new W3CDom();
Document wDoc = w3c.fromJsoup(doc);
String out = w3c.asString(wDoc);
assertEquals(
"<html>" + LE +
"<head>" + LE +
"<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" + LE +
"<title>W3c</title>" + LE +
"</head>" + LE +
"<body>" + LE +
"<p class=\"one\" id=\"12\">Text</p>" + LE +
"<!-- comment -->" + LE +
"<invalid>What<script>alert('!')</script>" + LE +
"</invalid>" + LE +
"</body>" + LE +
"</html>" + LE
, out);
}
@Test
public void convertsGoogle() throws IOException {
File in = ParseTest.getFile("/htmltests/google-ipod.html");
org.jsoup.nodes.Document doc = Jsoup.parse(in, "UTF8");
W3CDom w3c = new W3CDom();
Document wDoc = w3c.fromJsoup(doc);
Node htmlEl = wDoc.getChildNodes().item(0);
assertEquals(null, htmlEl.getNamespaceURI());
assertEquals("html", htmlEl.getLocalName());
assertEquals("html", htmlEl.getNodeName());
String out = w3c.asString(wDoc);
assertTrue(out.contains("ipod"));
}
@Test
public void namespacePreservation() throws IOException {
File in = ParseTest.getFile("/htmltests/namespaces.xhtml");
org.jsoup.nodes.Document jsoupDoc;
jsoupDoc = Jsoup.parse(in, "UTF-8");
Document doc;
org.jsoup.helper.W3CDom jDom = new org.jsoup.helper.W3CDom();
doc = jDom.fromJsoup(jsoupDoc);
Node htmlEl = doc.getChildNodes().item(0);
assertEquals("http://www.w3.org/1999/xhtml", htmlEl.getNamespaceURI());
assertEquals("html", htmlEl.getLocalName());
assertEquals("html", htmlEl.getNodeName());
Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3);
assertEquals("http://www.idpf.org/2007/ops", epubTitle.getNamespaceURI());
assertEquals("title", epubTitle.getLocalName());
assertEquals("epub:title", epubTitle.getNodeName());
Node xSection = epubTitle.getNextSibling().getNextSibling();
assertEquals("urn:test", xSection.getNamespaceURI());
assertEquals("section", xSection.getLocalName());
assertEquals("x:section", xSection.getNodeName());
}
@Test
public void handlesInvalidAttributeNames() {
String html = "<html><head></head><body style=\"color: red\" \" name\"></body></html>";
org.jsoup.nodes.Document jsoupDoc;
jsoupDoc = Jsoup.parse(html);
Element body = jsoupDoc.select("body").first();
assertTrue(body.hasAttr("\"")); // actually an attribute with key '"'. Correct per HTML5 spec, but w3c xml dom doesn't dig it
assertTrue(body.hasAttr("name\""));
Document w3Doc = new W3CDom().fromJsoup(jsoupDoc);
}
}
| // You are a professional Java test case writer, please create a test case named `handlesInvalidAttributeNames` for the issue `Jsoup-721`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-721
//
// ## Issue-Title:
// INVALID_CHARACTER_ERR when converting Document to W3C
//
// ## Issue-Description:
// A recent ClearQuest version has an HTML generation bug, which is ignored by both Chrome and Internet Explorer. Jsoup.parse is also successful:
//
//
// `org.jsoup.nodes.Document doc = Jsoup.parse("<html><head></head><body style=\"color: red\" \"></body></html>");`
//
//
// (Please note the single quotation mark at the end of the body start tag.)
//
//
// But trying to convert this to a W3C document fails:
//
//
// `new W3CDom().fromJsoup(doc);`
//
//
//
// ```
// Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
// at org.apache.xerces.dom.CoreDocumentImpl.createAttribute(Unknown Source)
// at org.apache.xerces.dom.ElementImpl.setAttribute(Unknown Source)
// at org.jsoup.helper.W3CDom$W3CBuilder.copyAttributes(W3CDom.java:124)
// at org.jsoup.helper.W3CDom$W3CBuilder.head(W3CDom.java:92)
// at org.jsoup.select.NodeTraversor.traverse(NodeTraversor.java:31)
// at org.jsoup.helper.W3CDom.convert(W3CDom.java:66)
// at org.jsoup.helper.W3CDom.fromJsoup(W3CDom.java:46)
//
// ```
//
// Perhaps copyAttributes() should ignore invalid attributes, or catch exactly this error, and ignore it, or W3CDom could have flags to ignore such errors...
//
//
//
//
@Test
public void handlesInvalidAttributeNames() {
| 93 | 54 | 83 | src/test/java/org/jsoup/helper/W3CDomTest.java | src/test/java | ```markdown
## Issue-ID: Jsoup-721
## Issue-Title:
INVALID_CHARACTER_ERR when converting Document to W3C
## Issue-Description:
A recent ClearQuest version has an HTML generation bug, which is ignored by both Chrome and Internet Explorer. Jsoup.parse is also successful:
`org.jsoup.nodes.Document doc = Jsoup.parse("<html><head></head><body style=\"color: red\" \"></body></html>");`
(Please note the single quotation mark at the end of the body start tag.)
But trying to convert this to a W3C document fails:
`new W3CDom().fromJsoup(doc);`
```
Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
at org.apache.xerces.dom.CoreDocumentImpl.createAttribute(Unknown Source)
at org.apache.xerces.dom.ElementImpl.setAttribute(Unknown Source)
at org.jsoup.helper.W3CDom$W3CBuilder.copyAttributes(W3CDom.java:124)
at org.jsoup.helper.W3CDom$W3CBuilder.head(W3CDom.java:92)
at org.jsoup.select.NodeTraversor.traverse(NodeTraversor.java:31)
at org.jsoup.helper.W3CDom.convert(W3CDom.java:66)
at org.jsoup.helper.W3CDom.fromJsoup(W3CDom.java:46)
```
Perhaps copyAttributes() should ignore invalid attributes, or catch exactly this error, and ignore it, or W3CDom could have flags to ignore such errors...
```
You are a professional Java test case writer, please create a test case named `handlesInvalidAttributeNames` for the issue `Jsoup-721`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void handlesInvalidAttributeNames() {
```
| 83 | [
"org.jsoup.helper.W3CDom"
] | 436d09cbcdbcc90657698b553624b9cb72ebac3674f7dfa56914cbc2306b010b | @Test
public void handlesInvalidAttributeNames() | // You are a professional Java test case writer, please create a test case named `handlesInvalidAttributeNames` for the issue `Jsoup-721`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-721
//
// ## Issue-Title:
// INVALID_CHARACTER_ERR when converting Document to W3C
//
// ## Issue-Description:
// A recent ClearQuest version has an HTML generation bug, which is ignored by both Chrome and Internet Explorer. Jsoup.parse is also successful:
//
//
// `org.jsoup.nodes.Document doc = Jsoup.parse("<html><head></head><body style=\"color: red\" \"></body></html>");`
//
//
// (Please note the single quotation mark at the end of the body start tag.)
//
//
// But trying to convert this to a W3C document fails:
//
//
// `new W3CDom().fromJsoup(doc);`
//
//
//
// ```
// Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
// at org.apache.xerces.dom.CoreDocumentImpl.createAttribute(Unknown Source)
// at org.apache.xerces.dom.ElementImpl.setAttribute(Unknown Source)
// at org.jsoup.helper.W3CDom$W3CBuilder.copyAttributes(W3CDom.java:124)
// at org.jsoup.helper.W3CDom$W3CBuilder.head(W3CDom.java:92)
// at org.jsoup.select.NodeTraversor.traverse(NodeTraversor.java:31)
// at org.jsoup.helper.W3CDom.convert(W3CDom.java:66)
// at org.jsoup.helper.W3CDom.fromJsoup(W3CDom.java:46)
//
// ```
//
// Perhaps copyAttributes() should ignore invalid attributes, or catch exactly this error, and ignore it, or W3CDom could have flags to ignore such errors...
//
//
//
//
| Jsoup | package org.jsoup.helper;
import org.jsoup.Jsoup;
import org.jsoup.integration.ParseTest;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.io.File;
import java.io.IOException;
import static org.jsoup.TextUtil.LE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class W3CDomTest {
@Test
public void simpleConversion() {
String html = "<html><head><title>W3c</title></head><body><p class='one' id=12>Text</p><!-- comment --><invalid>What<script>alert('!')";
org.jsoup.nodes.Document doc = Jsoup.parse(html);
W3CDom w3c = new W3CDom();
Document wDoc = w3c.fromJsoup(doc);
String out = w3c.asString(wDoc);
assertEquals(
"<html>" + LE +
"<head>" + LE +
"<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" + LE +
"<title>W3c</title>" + LE +
"</head>" + LE +
"<body>" + LE +
"<p class=\"one\" id=\"12\">Text</p>" + LE +
"<!-- comment -->" + LE +
"<invalid>What<script>alert('!')</script>" + LE +
"</invalid>" + LE +
"</body>" + LE +
"</html>" + LE
, out);
}
@Test
public void convertsGoogle() throws IOException {
File in = ParseTest.getFile("/htmltests/google-ipod.html");
org.jsoup.nodes.Document doc = Jsoup.parse(in, "UTF8");
W3CDom w3c = new W3CDom();
Document wDoc = w3c.fromJsoup(doc);
Node htmlEl = wDoc.getChildNodes().item(0);
assertEquals(null, htmlEl.getNamespaceURI());
assertEquals("html", htmlEl.getLocalName());
assertEquals("html", htmlEl.getNodeName());
String out = w3c.asString(wDoc);
assertTrue(out.contains("ipod"));
}
@Test
public void namespacePreservation() throws IOException {
File in = ParseTest.getFile("/htmltests/namespaces.xhtml");
org.jsoup.nodes.Document jsoupDoc;
jsoupDoc = Jsoup.parse(in, "UTF-8");
Document doc;
org.jsoup.helper.W3CDom jDom = new org.jsoup.helper.W3CDom();
doc = jDom.fromJsoup(jsoupDoc);
Node htmlEl = doc.getChildNodes().item(0);
assertEquals("http://www.w3.org/1999/xhtml", htmlEl.getNamespaceURI());
assertEquals("html", htmlEl.getLocalName());
assertEquals("html", htmlEl.getNodeName());
Node epubTitle = htmlEl.getChildNodes().item(2).getChildNodes().item(3);
assertEquals("http://www.idpf.org/2007/ops", epubTitle.getNamespaceURI());
assertEquals("title", epubTitle.getLocalName());
assertEquals("epub:title", epubTitle.getNodeName());
Node xSection = epubTitle.getNextSibling().getNextSibling();
assertEquals("urn:test", xSection.getNamespaceURI());
assertEquals("section", xSection.getLocalName());
assertEquals("x:section", xSection.getNodeName());
}
@Test
public void handlesInvalidAttributeNames() {
String html = "<html><head></head><body style=\"color: red\" \" name\"></body></html>";
org.jsoup.nodes.Document jsoupDoc;
jsoupDoc = Jsoup.parse(html);
Element body = jsoupDoc.select("body").first();
assertTrue(body.hasAttr("\"")); // actually an attribute with key '"'. Correct per HTML5 spec, but w3c xml dom doesn't dig it
assertTrue(body.hasAttr("name\""));
Document w3Doc = new W3CDom().fromJsoup(jsoupDoc);
}
}
|
||
@Test
public void testMath519() {
// The optimizer will try negative sigma values but "GaussianFitter"
// will catch the raised exceptions and return NaN values instead.
final double[] data = {
1.1143831578403364E-29,
4.95281403484594E-28,
1.1171347211930288E-26,
1.7044813962636277E-25,
1.9784716574832164E-24,
1.8630236407866774E-23,
1.4820532905097742E-22,
1.0241963854632831E-21,
6.275077366673128E-21,
3.461808994532493E-20,
1.7407124684715706E-19,
8.056687953553974E-19,
3.460193945992071E-18,
1.3883326374011525E-17,
5.233894983671116E-17,
1.8630791465263745E-16,
6.288759227922111E-16,
2.0204433920597856E-15,
6.198768938576155E-15,
1.821419346860626E-14,
5.139176445538471E-14,
1.3956427429045787E-13,
3.655705706448139E-13,
9.253753324779779E-13,
2.267636001476696E-12,
5.3880460095836855E-12,
1.2431632654852931E-11
};
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
for (int i = 0; i < data.length; i++) {
fitter.addObservedPoint(i, data[i]);
}
final double[] p = fitter.fit();
Assert.assertEquals(53.1572792, p[1], 1e-7);
Assert.assertEquals(5.75214622, p[2], 1e-8);
} | org.apache.commons.math.optimization.fitting.GaussianFitterTest::testMath519 | src/test/java/org/apache/commons/math/optimization/fitting/GaussianFitterTest.java | 339 | src/test/java/org/apache/commons/math/optimization/fitting/GaussianFitterTest.java | testMath519 | /*
* 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.fitting;
import org.apache.commons.math.exception.MathIllegalArgumentException;
import org.apache.commons.math.optimization.OptimizationException;
import org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests {@link GaussianFitter}.
*
* @since 2.2
* @version $Revision$ $Date$
*/
public class GaussianFitterTest {
/** Good data. */
protected static final double[][] DATASET1 = new double[][] {
{4.0254623, 531026.0},
{4.02804905, 664002.0},
{4.02934242, 787079.0},
{4.03128248, 984167.0},
{4.03386923, 1294546.0},
{4.03580929, 1560230.0},
{4.03839603, 1887233.0},
{4.0396894, 2113240.0},
{4.04162946, 2375211.0},
{4.04421621, 2687152.0},
{4.04550958, 2862644.0},
{4.04744964, 3078898.0},
{4.05003639, 3327238.0},
{4.05132976, 3461228.0},
{4.05326982, 3580526.0},
{4.05585657, 3576946.0},
{4.05779662, 3439750.0},
{4.06038337, 3220296.0},
{4.06167674, 3070073.0},
{4.0636168, 2877648.0},
{4.06620355, 2595848.0},
{4.06749692, 2390157.0},
{4.06943698, 2175960.0},
{4.07202373, 1895104.0},
{4.0733171, 1687576.0},
{4.07525716, 1447024.0},
{4.0778439, 1130879.0},
{4.07978396, 904900.0},
{4.08237071, 717104.0},
{4.08366408, 620014.0}
};
/** Poor data: right of peak not symmetric with left of peak. */
protected static final double[][] DATASET2 = new double[][] {
{-20.15, 1523.0},
{-19.65, 1566.0},
{-19.15, 1592.0},
{-18.65, 1927.0},
{-18.15, 3089.0},
{-17.65, 6068.0},
{-17.15, 14239.0},
{-16.65, 34124.0},
{-16.15, 64097.0},
{-15.65, 110352.0},
{-15.15, 164742.0},
{-14.65, 209499.0},
{-14.15, 267274.0},
{-13.65, 283290.0},
{-13.15, 275363.0},
{-12.65, 258014.0},
{-12.15, 225000.0},
{-11.65, 200000.0},
{-11.15, 190000.0},
{-10.65, 185000.0},
{-10.15, 180000.0},
{ -9.65, 179000.0},
{ -9.15, 178000.0},
{ -8.65, 177000.0},
{ -8.15, 176000.0},
{ -7.65, 175000.0},
{ -7.15, 174000.0},
{ -6.65, 173000.0},
{ -6.15, 172000.0},
{ -5.65, 171000.0},
{ -5.15, 170000.0}
};
/** Poor data: long tails. */
protected static final double[][] DATASET3 = new double[][] {
{-90.15, 1513.0},
{-80.15, 1514.0},
{-70.15, 1513.0},
{-60.15, 1514.0},
{-50.15, 1513.0},
{-40.15, 1514.0},
{-30.15, 1513.0},
{-20.15, 1523.0},
{-19.65, 1566.0},
{-19.15, 1592.0},
{-18.65, 1927.0},
{-18.15, 3089.0},
{-17.65, 6068.0},
{-17.15, 14239.0},
{-16.65, 34124.0},
{-16.15, 64097.0},
{-15.65, 110352.0},
{-15.15, 164742.0},
{-14.65, 209499.0},
{-14.15, 267274.0},
{-13.65, 283290.0},
{-13.15, 275363.0},
{-12.65, 258014.0},
{-12.15, 214073.0},
{-11.65, 182244.0},
{-11.15, 136419.0},
{-10.65, 97823.0},
{-10.15, 58930.0},
{ -9.65, 35404.0},
{ -9.15, 16120.0},
{ -8.65, 9823.0},
{ -8.15, 5064.0},
{ -7.65, 2575.0},
{ -7.15, 1642.0},
{ -6.65, 1101.0},
{ -6.15, 812.0},
{ -5.65, 690.0},
{ -5.15, 565.0},
{ 5.15, 564.0},
{ 15.15, 565.0},
{ 25.15, 564.0},
{ 35.15, 565.0},
{ 45.15, 564.0},
{ 55.15, 565.0},
{ 65.15, 564.0},
{ 75.15, 565.0}
};
/** Poor data: right of peak is missing. */
protected static final double[][] DATASET4 = new double[][] {
{-20.15, 1523.0},
{-19.65, 1566.0},
{-19.15, 1592.0},
{-18.65, 1927.0},
{-18.15, 3089.0},
{-17.65, 6068.0},
{-17.15, 14239.0},
{-16.65, 34124.0},
{-16.15, 64097.0},
{-15.65, 110352.0},
{-15.15, 164742.0},
{-14.65, 209499.0},
{-14.15, 267274.0},
{-13.65, 283290.0}
};
/** Good data, but few points. */
protected static final double[][] DATASET5 = new double[][] {
{4.0254623, 531026.0},
{4.03128248, 984167.0},
{4.03839603, 1887233.0},
{4.04421621, 2687152.0},
{4.05132976, 3461228.0},
{4.05326982, 3580526.0},
{4.05779662, 3439750.0},
{4.0636168, 2877648.0},
{4.06943698, 2175960.0},
{4.07525716, 1447024.0},
{4.08237071, 717104.0},
{4.08366408, 620014.0}
};
/**
* Basic.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit01()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET1, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(3496978.1837704973, parameters[0], 1e-4);
Assert.assertEquals(4.054933085999146, parameters[1], 1e-4);
Assert.assertEquals(0.015039355620304326, parameters[2], 1e-4);
}
/**
* Zero points is not enough observed points.
*
* @throws OptimizationException in the event of a test case error
*/
@Test(expected=MathIllegalArgumentException.class)
public void testFit02()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
fitter.fit();
}
/**
* Two points is not enough observed points.
*
* @throws OptimizationException in the event of a test case error
*/
@Test(expected=MathIllegalArgumentException.class)
public void testFit03()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(new double[][] {
{4.0254623, 531026.0},
{4.02804905, 664002.0}},
fitter);
fitter.fit();
}
/**
* Poor data: right of peak not symmetric with left of peak.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit04()
throws OptimizationException
{
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET2, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(233003.2967252038, parameters[0], 1e-4);
Assert.assertEquals(-10.654887521095983, parameters[1], 1e-4);
Assert.assertEquals(4.335937353196641, parameters[2], 1e-4);
}
/**
* Poor data: long tails.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit05()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET3, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(283863.81929180305, parameters[0], 1e-4);
Assert.assertEquals(-13.29641995105174, parameters[1], 1e-4);
Assert.assertEquals(1.7297330293549908, parameters[2], 1e-4);
}
/**
* Poor data: right of peak is missing.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit06()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET4, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(285250.66754309234, parameters[0], 1e-4);
Assert.assertEquals(-13.528375695228455, parameters[1], 1e-4);
Assert.assertEquals(1.5204344894331614, parameters[2], 1e-4);
}
/**
* Basic with smaller dataset.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit07()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET5, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(3514384.729342235, parameters[0], 1e-4);
Assert.assertEquals(4.054970307455625, parameters[1], 1e-4);
Assert.assertEquals(0.015029412832160017, parameters[2], 1e-4);
}
@Test
public void testMath519() {
// The optimizer will try negative sigma values but "GaussianFitter"
// will catch the raised exceptions and return NaN values instead.
final double[] data = {
1.1143831578403364E-29,
4.95281403484594E-28,
1.1171347211930288E-26,
1.7044813962636277E-25,
1.9784716574832164E-24,
1.8630236407866774E-23,
1.4820532905097742E-22,
1.0241963854632831E-21,
6.275077366673128E-21,
3.461808994532493E-20,
1.7407124684715706E-19,
8.056687953553974E-19,
3.460193945992071E-18,
1.3883326374011525E-17,
5.233894983671116E-17,
1.8630791465263745E-16,
6.288759227922111E-16,
2.0204433920597856E-15,
6.198768938576155E-15,
1.821419346860626E-14,
5.139176445538471E-14,
1.3956427429045787E-13,
3.655705706448139E-13,
9.253753324779779E-13,
2.267636001476696E-12,
5.3880460095836855E-12,
1.2431632654852931E-11
};
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
for (int i = 0; i < data.length; i++) {
fitter.addObservedPoint(i, data[i]);
}
final double[] p = fitter.fit();
Assert.assertEquals(53.1572792, p[1], 1e-7);
Assert.assertEquals(5.75214622, p[2], 1e-8);
}
/**
* Adds the specified points to specified <code>GaussianFitter</code>
* instance.
*
* @param points data points where first dimension is a point index and
* second dimension is an array of length two representing the point
* with the first value corresponding to X and the second value
* corresponding to Y
* @param fitter fitter to which the points in <code>points</code> should be
* added as observed points
*/
protected static void addDatasetToGaussianFitter(double[][] points,
GaussianFitter fitter) {
for (int i = 0; i < points.length; i++) {
fitter.addObservedPoint(points[i][0], points[i][1]);
}
}
} | // You are a professional Java test case writer, please create a test case named `testMath519` for the issue `Math-MATH-519`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-519
//
// ## Issue-Title:
// GaussianFitter Unexpectedly Throws NotStrictlyPositiveException
//
// ## Issue-Description:
//
// Running the following:
//
//
// double[] observations =
//
//
//
//
// {
// 1.1143831578403364E-29,
// 4.95281403484594E-28,
// 1.1171347211930288E-26,
// 1.7044813962636277E-25,
// 1.9784716574832164E-24,
// 1.8630236407866774E-23,
// 1.4820532905097742E-22,
// 1.0241963854632831E-21,
// 6.275077366673128E-21,
// 3.461808994532493E-20,
// 1.7407124684715706E-19,
// 8.056687953553974E-19,
// 3.460193945992071E-18,
// 1.3883326374011525E-17,
// 5.233894983671116E-17,
// 1.8630791465263745E-16,
// 6.288759227922111E-16,
// 2.0204433920597856E-15,
// 6.198768938576155E-15,
// 1.821419346860626E-14,
// 5.139176445538471E-14,
// 1.3956427429045787E-13,
// 3.655705706448139E-13,
// 9.253753324779779E-13,
// 2.267636001476696E-12,
// 5.3880460095836855E-12,
// 1.2431632654852931E-11
// }
// ;
//
//
// GaussianFitter g =
//
// new GaussianFitter(new LevenbergMarquardtOptimizer());
//
//
// for (int index = 0; index < 27; index++)
//
//
// {
// g.addObservedPoint(index, observations[index]);
// }
// g.fit();
//
//
// Results in:
//
//
// org.apache.commons.math.exception.NotStrictlyPositiveException: -1.277 is smaller than, or equal to, the minimum (0)
//
// at org.apache.commons.math.analysis.function.Gaussian$Parametric.validateParameters(Gaussian.java:184)
//
// at org.apache.commons.math.analysis.function.Gaussian$Parametric.value(Gaussian.java:129)
//
//
// I'm guessing the initial guess for sigma is off.
//
//
//
//
//
@Test
public void testMath519() {
| 339 | 58 | 296 | src/test/java/org/apache/commons/math/optimization/fitting/GaussianFitterTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-519
## Issue-Title:
GaussianFitter Unexpectedly Throws NotStrictlyPositiveException
## Issue-Description:
Running the following:
double[] observations =
{
1.1143831578403364E-29,
4.95281403484594E-28,
1.1171347211930288E-26,
1.7044813962636277E-25,
1.9784716574832164E-24,
1.8630236407866774E-23,
1.4820532905097742E-22,
1.0241963854632831E-21,
6.275077366673128E-21,
3.461808994532493E-20,
1.7407124684715706E-19,
8.056687953553974E-19,
3.460193945992071E-18,
1.3883326374011525E-17,
5.233894983671116E-17,
1.8630791465263745E-16,
6.288759227922111E-16,
2.0204433920597856E-15,
6.198768938576155E-15,
1.821419346860626E-14,
5.139176445538471E-14,
1.3956427429045787E-13,
3.655705706448139E-13,
9.253753324779779E-13,
2.267636001476696E-12,
5.3880460095836855E-12,
1.2431632654852931E-11
}
;
GaussianFitter g =
new GaussianFitter(new LevenbergMarquardtOptimizer());
for (int index = 0; index < 27; index++)
{
g.addObservedPoint(index, observations[index]);
}
g.fit();
Results in:
org.apache.commons.math.exception.NotStrictlyPositiveException: -1.277 is smaller than, or equal to, the minimum (0)
at org.apache.commons.math.analysis.function.Gaussian$Parametric.validateParameters(Gaussian.java:184)
at org.apache.commons.math.analysis.function.Gaussian$Parametric.value(Gaussian.java:129)
I'm guessing the initial guess for sigma is off.
```
You are a professional Java test case writer, please create a test case named `testMath519` for the issue `Math-MATH-519`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testMath519() {
```
| 296 | [
"org.apache.commons.math.optimization.fitting.GaussianFitter"
] | 43cbd9c8389c68a64c1e0902c0aa70f5a51159a50f2823b3cca7bd5cdd814960 | @Test
public void testMath519() | // You are a professional Java test case writer, please create a test case named `testMath519` for the issue `Math-MATH-519`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-519
//
// ## Issue-Title:
// GaussianFitter Unexpectedly Throws NotStrictlyPositiveException
//
// ## Issue-Description:
//
// Running the following:
//
//
// double[] observations =
//
//
//
//
// {
// 1.1143831578403364E-29,
// 4.95281403484594E-28,
// 1.1171347211930288E-26,
// 1.7044813962636277E-25,
// 1.9784716574832164E-24,
// 1.8630236407866774E-23,
// 1.4820532905097742E-22,
// 1.0241963854632831E-21,
// 6.275077366673128E-21,
// 3.461808994532493E-20,
// 1.7407124684715706E-19,
// 8.056687953553974E-19,
// 3.460193945992071E-18,
// 1.3883326374011525E-17,
// 5.233894983671116E-17,
// 1.8630791465263745E-16,
// 6.288759227922111E-16,
// 2.0204433920597856E-15,
// 6.198768938576155E-15,
// 1.821419346860626E-14,
// 5.139176445538471E-14,
// 1.3956427429045787E-13,
// 3.655705706448139E-13,
// 9.253753324779779E-13,
// 2.267636001476696E-12,
// 5.3880460095836855E-12,
// 1.2431632654852931E-11
// }
// ;
//
//
// GaussianFitter g =
//
// new GaussianFitter(new LevenbergMarquardtOptimizer());
//
//
// for (int index = 0; index < 27; index++)
//
//
// {
// g.addObservedPoint(index, observations[index]);
// }
// g.fit();
//
//
// Results in:
//
//
// org.apache.commons.math.exception.NotStrictlyPositiveException: -1.277 is smaller than, or equal to, the minimum (0)
//
// at org.apache.commons.math.analysis.function.Gaussian$Parametric.validateParameters(Gaussian.java:184)
//
// at org.apache.commons.math.analysis.function.Gaussian$Parametric.value(Gaussian.java:129)
//
//
// I'm guessing the initial guess for sigma is off.
//
//
//
//
//
| 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.fitting;
import org.apache.commons.math.exception.MathIllegalArgumentException;
import org.apache.commons.math.optimization.OptimizationException;
import org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests {@link GaussianFitter}.
*
* @since 2.2
* @version $Revision$ $Date$
*/
public class GaussianFitterTest {
/** Good data. */
protected static final double[][] DATASET1 = new double[][] {
{4.0254623, 531026.0},
{4.02804905, 664002.0},
{4.02934242, 787079.0},
{4.03128248, 984167.0},
{4.03386923, 1294546.0},
{4.03580929, 1560230.0},
{4.03839603, 1887233.0},
{4.0396894, 2113240.0},
{4.04162946, 2375211.0},
{4.04421621, 2687152.0},
{4.04550958, 2862644.0},
{4.04744964, 3078898.0},
{4.05003639, 3327238.0},
{4.05132976, 3461228.0},
{4.05326982, 3580526.0},
{4.05585657, 3576946.0},
{4.05779662, 3439750.0},
{4.06038337, 3220296.0},
{4.06167674, 3070073.0},
{4.0636168, 2877648.0},
{4.06620355, 2595848.0},
{4.06749692, 2390157.0},
{4.06943698, 2175960.0},
{4.07202373, 1895104.0},
{4.0733171, 1687576.0},
{4.07525716, 1447024.0},
{4.0778439, 1130879.0},
{4.07978396, 904900.0},
{4.08237071, 717104.0},
{4.08366408, 620014.0}
};
/** Poor data: right of peak not symmetric with left of peak. */
protected static final double[][] DATASET2 = new double[][] {
{-20.15, 1523.0},
{-19.65, 1566.0},
{-19.15, 1592.0},
{-18.65, 1927.0},
{-18.15, 3089.0},
{-17.65, 6068.0},
{-17.15, 14239.0},
{-16.65, 34124.0},
{-16.15, 64097.0},
{-15.65, 110352.0},
{-15.15, 164742.0},
{-14.65, 209499.0},
{-14.15, 267274.0},
{-13.65, 283290.0},
{-13.15, 275363.0},
{-12.65, 258014.0},
{-12.15, 225000.0},
{-11.65, 200000.0},
{-11.15, 190000.0},
{-10.65, 185000.0},
{-10.15, 180000.0},
{ -9.65, 179000.0},
{ -9.15, 178000.0},
{ -8.65, 177000.0},
{ -8.15, 176000.0},
{ -7.65, 175000.0},
{ -7.15, 174000.0},
{ -6.65, 173000.0},
{ -6.15, 172000.0},
{ -5.65, 171000.0},
{ -5.15, 170000.0}
};
/** Poor data: long tails. */
protected static final double[][] DATASET3 = new double[][] {
{-90.15, 1513.0},
{-80.15, 1514.0},
{-70.15, 1513.0},
{-60.15, 1514.0},
{-50.15, 1513.0},
{-40.15, 1514.0},
{-30.15, 1513.0},
{-20.15, 1523.0},
{-19.65, 1566.0},
{-19.15, 1592.0},
{-18.65, 1927.0},
{-18.15, 3089.0},
{-17.65, 6068.0},
{-17.15, 14239.0},
{-16.65, 34124.0},
{-16.15, 64097.0},
{-15.65, 110352.0},
{-15.15, 164742.0},
{-14.65, 209499.0},
{-14.15, 267274.0},
{-13.65, 283290.0},
{-13.15, 275363.0},
{-12.65, 258014.0},
{-12.15, 214073.0},
{-11.65, 182244.0},
{-11.15, 136419.0},
{-10.65, 97823.0},
{-10.15, 58930.0},
{ -9.65, 35404.0},
{ -9.15, 16120.0},
{ -8.65, 9823.0},
{ -8.15, 5064.0},
{ -7.65, 2575.0},
{ -7.15, 1642.0},
{ -6.65, 1101.0},
{ -6.15, 812.0},
{ -5.65, 690.0},
{ -5.15, 565.0},
{ 5.15, 564.0},
{ 15.15, 565.0},
{ 25.15, 564.0},
{ 35.15, 565.0},
{ 45.15, 564.0},
{ 55.15, 565.0},
{ 65.15, 564.0},
{ 75.15, 565.0}
};
/** Poor data: right of peak is missing. */
protected static final double[][] DATASET4 = new double[][] {
{-20.15, 1523.0},
{-19.65, 1566.0},
{-19.15, 1592.0},
{-18.65, 1927.0},
{-18.15, 3089.0},
{-17.65, 6068.0},
{-17.15, 14239.0},
{-16.65, 34124.0},
{-16.15, 64097.0},
{-15.65, 110352.0},
{-15.15, 164742.0},
{-14.65, 209499.0},
{-14.15, 267274.0},
{-13.65, 283290.0}
};
/** Good data, but few points. */
protected static final double[][] DATASET5 = new double[][] {
{4.0254623, 531026.0},
{4.03128248, 984167.0},
{4.03839603, 1887233.0},
{4.04421621, 2687152.0},
{4.05132976, 3461228.0},
{4.05326982, 3580526.0},
{4.05779662, 3439750.0},
{4.0636168, 2877648.0},
{4.06943698, 2175960.0},
{4.07525716, 1447024.0},
{4.08237071, 717104.0},
{4.08366408, 620014.0}
};
/**
* Basic.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit01()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET1, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(3496978.1837704973, parameters[0], 1e-4);
Assert.assertEquals(4.054933085999146, parameters[1], 1e-4);
Assert.assertEquals(0.015039355620304326, parameters[2], 1e-4);
}
/**
* Zero points is not enough observed points.
*
* @throws OptimizationException in the event of a test case error
*/
@Test(expected=MathIllegalArgumentException.class)
public void testFit02()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
fitter.fit();
}
/**
* Two points is not enough observed points.
*
* @throws OptimizationException in the event of a test case error
*/
@Test(expected=MathIllegalArgumentException.class)
public void testFit03()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(new double[][] {
{4.0254623, 531026.0},
{4.02804905, 664002.0}},
fitter);
fitter.fit();
}
/**
* Poor data: right of peak not symmetric with left of peak.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit04()
throws OptimizationException
{
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET2, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(233003.2967252038, parameters[0], 1e-4);
Assert.assertEquals(-10.654887521095983, parameters[1], 1e-4);
Assert.assertEquals(4.335937353196641, parameters[2], 1e-4);
}
/**
* Poor data: long tails.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit05()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET3, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(283863.81929180305, parameters[0], 1e-4);
Assert.assertEquals(-13.29641995105174, parameters[1], 1e-4);
Assert.assertEquals(1.7297330293549908, parameters[2], 1e-4);
}
/**
* Poor data: right of peak is missing.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit06()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET4, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(285250.66754309234, parameters[0], 1e-4);
Assert.assertEquals(-13.528375695228455, parameters[1], 1e-4);
Assert.assertEquals(1.5204344894331614, parameters[2], 1e-4);
}
/**
* Basic with smaller dataset.
*
* @throws OptimizationException in the event of a test case error
*/
@Test
public void testFit07()
throws OptimizationException {
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
addDatasetToGaussianFitter(DATASET5, fitter);
double[] parameters = fitter.fit();
Assert.assertEquals(3514384.729342235, parameters[0], 1e-4);
Assert.assertEquals(4.054970307455625, parameters[1], 1e-4);
Assert.assertEquals(0.015029412832160017, parameters[2], 1e-4);
}
@Test
public void testMath519() {
// The optimizer will try negative sigma values but "GaussianFitter"
// will catch the raised exceptions and return NaN values instead.
final double[] data = {
1.1143831578403364E-29,
4.95281403484594E-28,
1.1171347211930288E-26,
1.7044813962636277E-25,
1.9784716574832164E-24,
1.8630236407866774E-23,
1.4820532905097742E-22,
1.0241963854632831E-21,
6.275077366673128E-21,
3.461808994532493E-20,
1.7407124684715706E-19,
8.056687953553974E-19,
3.460193945992071E-18,
1.3883326374011525E-17,
5.233894983671116E-17,
1.8630791465263745E-16,
6.288759227922111E-16,
2.0204433920597856E-15,
6.198768938576155E-15,
1.821419346860626E-14,
5.139176445538471E-14,
1.3956427429045787E-13,
3.655705706448139E-13,
9.253753324779779E-13,
2.267636001476696E-12,
5.3880460095836855E-12,
1.2431632654852931E-11
};
GaussianFitter fitter = new GaussianFitter(new LevenbergMarquardtOptimizer());
for (int i = 0; i < data.length; i++) {
fitter.addObservedPoint(i, data[i]);
}
final double[] p = fitter.fit();
Assert.assertEquals(53.1572792, p[1], 1e-7);
Assert.assertEquals(5.75214622, p[2], 1e-8);
}
/**
* Adds the specified points to specified <code>GaussianFitter</code>
* instance.
*
* @param points data points where first dimension is a point index and
* second dimension is an array of length two representing the point
* with the first value corresponding to X and the second value
* corresponding to Y
* @param fitter fitter to which the points in <code>points</code> should be
* added as observed points
*/
protected static void addDatasetToGaussianFitter(double[][] points,
GaussianFitter fitter) {
for (int i = 0; i < points.length; i++) {
fitter.addObservedPoint(points[i][0], points[i][1]);
}
}
} |
||
public void testFunctionSafariCompatiblity() {
// Functions within IFs cause syntax errors on Safari.
assertPrint("function(){if(e1){function goo(){return true}}else foo()}",
"function(){if(e1){function goo(){return true}}else foo()}");
assertPrint("function(){if(e1)function goo(){return true}else foo()}",
"function(){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}}");
} | com.google.javascript.jscomp.CodePrinterTest::testFunctionSafariCompatiblity | test/com/google/javascript/jscomp/CodePrinterTest.java | 959 | test/com/google/javascript/jscomp/CodePrinterTest.java | testFunctionSafariCompatiblity | /*
* 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;
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();
Node n = compiler.parseTestCode(js);
if (checkTypes) {
DefaultPassConfig passConfig = new DefaultPassConfig(null);
CompilerPass typeResolver = passConfig.resolveTypes.create(compiler);
Node externs = new Node(Token.SCRIPT);
Node externAndJsRoot = new Node(Token.BLOCK, externs, n);
externAndJsRoot.setIsSyntheticBlock(true);
typeResolver.process(externs, n);
CompilerPass inferTypes = passConfig.inferTypes.create(compiler);
inferTypes.process(externs, n);
}
assertEquals("Errors for: " + js, 0, compiler.getErrorCount());
return n;
}
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 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");
// 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})");
// 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 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})()");
assertPrettyPrint("var a = (function() {});alert(a);",
"var a = function() {\n};\nalert(a)");
// 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()");
// 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)");
// 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");
}
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 testTypeAnnotationsAssign() {
assertTypeAnnotations("/** @constructor */ var Foo = function(){}",
"/**\n * @return {undefined}\n * @constructor\n */\n"
+ "var Foo = function() {\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}");
}
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}");
}
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}");
}
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 = \"\"");
}
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}");
}
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" +
"}");
}
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" +
"}");
}
public void testU2UFunctionTypeAnnotation() {
assertTypeAnnotations(
"/** @type {!Function} */ var x = function() {}",
"/**\n * @constructor\n */\nvar x = function() {\n}");
}
public void testEmitUnknownParamTypesAsAllType() {
assertTypeAnnotations(
"var a = function(x) {}",
"/**\n" +
" * @param {*} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\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}");
}
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}");
}
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}"
);
}
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));
}
/**
* This test case is more involved since we need to run a constant folding
* pass to get the -4 converted to a negative number, as opposed to a
* number node with a number 4 attached to the negation unary operator.
*/
public void testSubtraction() {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode("x - -4");
assertEquals(0, compiler.getErrorCount());
NodeTraversal.traverse(compiler, n, new FoldConstants(compiler));
assertEquals(
"x- -4",
new CodePrinter.Builder(n).setLineLengthThreshold(
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build());
}
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) {
Node parse1 = parse(code);
Node parse2 = parse(new CodePrinter.Builder(parse1).build());
assertTrue(code, parse1.checkTreeEqualsSilent(parse2));
}
public void testDoLoopIECompatiblity() {
// Do loops within IFs cause syntax errors in IE6 and IE7.
assertPrint("function(){if(e1){do foo();while(e2)}else foo()}",
"function(){if(e1){do foo();while(e2)}else foo()}");
assertPrint("function(){if(e1)do foo();while(e2)else foo()}",
"function(){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(){if(e1){function goo(){return true}}else foo()}",
"function(){if(e1){function goo(){return true}}else foo()}");
assertPrint("function(){if(e1)function goo(){return true}else foo()}",
"function(){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);
}
} | // You are a professional Java test case writer, please create a test case named `testFunctionSafariCompatiblity` for the issue `Closure-190`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-190
//
// ## Issue-Title:
// Bug with labeled loops and breaks
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// Try to compile this code with the closure compiler :
// var i = 0;
// lab1: do{
// lab2: do{
// i++;
// if (1) {
// break lab2;
// } else {
// break lab1;
// }
// } while(false);
// } while(false);
//
// console.log(i);
//
// **What is the expected output? What do you see instead?**
// The generated code produced is :
// var a=0;do b:do{a++;break b}while(0);while(0);console.log(a);
//
// Which works on all browsers except IE (Looks like IE doesn't like
// the missing brackets just after the first do instruction).
//
// **What version of the product are you using? On what operating system?**
// I am using the version of Jun 16 (latest) on ubuntu 10
//
// **Please provide any additional information below.**
// Strangely, this bug doesn't happen when I use PRETTY\_PRINT formatting option.
//
//
public void testFunctionSafariCompatiblity() {
| 959 | 145 | 943 | test/com/google/javascript/jscomp/CodePrinterTest.java | test | ```markdown
## Issue-ID: Closure-190
## Issue-Title:
Bug with labeled loops and breaks
## Issue-Description:
**What steps will reproduce the problem?**
Try to compile this code with the closure compiler :
var i = 0;
lab1: do{
lab2: do{
i++;
if (1) {
break lab2;
} else {
break lab1;
}
} while(false);
} while(false);
console.log(i);
**What is the expected output? What do you see instead?**
The generated code produced is :
var a=0;do b:do{a++;break b}while(0);while(0);console.log(a);
Which works on all browsers except IE (Looks like IE doesn't like
the missing brackets just after the first do instruction).
**What version of the product are you using? On what operating system?**
I am using the version of Jun 16 (latest) on ubuntu 10
**Please provide any additional information below.**
Strangely, this bug doesn't happen when I use PRETTY\_PRINT formatting option.
```
You are a professional Java test case writer, please create a test case named `testFunctionSafariCompatiblity` for the issue `Closure-190`, utilizing the provided issue report information and the following function signature.
```java
public void testFunctionSafariCompatiblity() {
```
| 943 | [
"com.google.javascript.jscomp.CodeGenerator"
] | 448cf46dcb18748f88954abfd25ac6f2290c8fadc6e7bc78c54cf7750b882ada | public void testFunctionSafariCompatiblity() | // You are a professional Java test case writer, please create a test case named `testFunctionSafariCompatiblity` for the issue `Closure-190`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-190
//
// ## Issue-Title:
// Bug with labeled loops and breaks
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// Try to compile this code with the closure compiler :
// var i = 0;
// lab1: do{
// lab2: do{
// i++;
// if (1) {
// break lab2;
// } else {
// break lab1;
// }
// } while(false);
// } while(false);
//
// console.log(i);
//
// **What is the expected output? What do you see instead?**
// The generated code produced is :
// var a=0;do b:do{a++;break b}while(0);while(0);console.log(a);
//
// Which works on all browsers except IE (Looks like IE doesn't like
// the missing brackets just after the first do instruction).
//
// **What version of the product are you using? On what operating system?**
// I am using the version of Jun 16 (latest) on ubuntu 10
//
// **Please provide any additional information below.**
// Strangely, this bug doesn't happen when I use PRETTY\_PRINT formatting option.
//
//
| 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;
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();
Node n = compiler.parseTestCode(js);
if (checkTypes) {
DefaultPassConfig passConfig = new DefaultPassConfig(null);
CompilerPass typeResolver = passConfig.resolveTypes.create(compiler);
Node externs = new Node(Token.SCRIPT);
Node externAndJsRoot = new Node(Token.BLOCK, externs, n);
externAndJsRoot.setIsSyntheticBlock(true);
typeResolver.process(externs, n);
CompilerPass inferTypes = passConfig.inferTypes.create(compiler);
inferTypes.process(externs, n);
}
assertEquals("Errors for: " + js, 0, compiler.getErrorCount());
return n;
}
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 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");
// 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})");
// 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 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})()");
assertPrettyPrint("var a = (function() {});alert(a);",
"var a = function() {\n};\nalert(a)");
// 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()");
// 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)");
// 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");
}
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 testTypeAnnotationsAssign() {
assertTypeAnnotations("/** @constructor */ var Foo = function(){}",
"/**\n * @return {undefined}\n * @constructor\n */\n"
+ "var Foo = function() {\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}");
}
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}");
}
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}");
}
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 = \"\"");
}
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}");
}
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" +
"}");
}
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" +
"}");
}
public void testU2UFunctionTypeAnnotation() {
assertTypeAnnotations(
"/** @type {!Function} */ var x = function() {}",
"/**\n * @constructor\n */\nvar x = function() {\n}");
}
public void testEmitUnknownParamTypesAsAllType() {
assertTypeAnnotations(
"var a = function(x) {}",
"/**\n" +
" * @param {*} x\n" +
" * @return {undefined}\n" +
" */\n" +
"var a = function(x) {\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}");
}
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}");
}
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}"
);
}
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));
}
/**
* This test case is more involved since we need to run a constant folding
* pass to get the -4 converted to a negative number, as opposed to a
* number node with a number 4 attached to the negation unary operator.
*/
public void testSubtraction() {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode("x - -4");
assertEquals(0, compiler.getErrorCount());
NodeTraversal.traverse(compiler, n, new FoldConstants(compiler));
assertEquals(
"x- -4",
new CodePrinter.Builder(n).setLineLengthThreshold(
CodePrinter.DEFAULT_LINE_LENGTH_THRESHOLD).build());
}
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) {
Node parse1 = parse(code);
Node parse2 = parse(new CodePrinter.Builder(parse1).build());
assertTrue(code, parse1.checkTreeEqualsSilent(parse2));
}
public void testDoLoopIECompatiblity() {
// Do loops within IFs cause syntax errors in IE6 and IE7.
assertPrint("function(){if(e1){do foo();while(e2)}else foo()}",
"function(){if(e1){do foo();while(e2)}else foo()}");
assertPrint("function(){if(e1)do foo();while(e2)else foo()}",
"function(){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(){if(e1){function goo(){return true}}else foo()}",
"function(){if(e1){function goo(){return true}}else foo()}");
assertPrint("function(){if(e1)function goo(){return true}else foo()}",
"function(){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);
}
} |
||
@Test
public void testIssue780() {
float[] coords = {
1.000000f, -1.000000f, -1.000000f,
1.000000f, -1.000000f, 1.000000f,
-1.000000f, -1.000000f, 1.000000f,
-1.000000f, -1.000000f, -1.000000f,
1.000000f, 1.000000f, -1f,
0.999999f, 1.000000f, 1.000000f, // 1.000000f, 1.000000f, 1.000000f,
-1.000000f, 1.000000f, 1.000000f,
-1.000000f, 1.000000f, -1.000000f};
int[] indices = {
0, 1, 2, 0, 2, 3,
4, 7, 6, 4, 6, 5,
0, 4, 5, 0, 5, 1,
1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3,
4, 0, 3, 4, 3, 7};
ArrayList<SubHyperplane<Euclidean3D>> subHyperplaneList = new ArrayList<SubHyperplane<Euclidean3D>>();
for (int idx = 0; idx < indices.length; idx += 3) {
int idxA = indices[idx] * 3;
int idxB = indices[idx + 1] * 3;
int idxC = indices[idx + 2] * 3;
Vector3D v_1 = new Vector3D(coords[idxA], coords[idxA + 1], coords[idxA + 2]);
Vector3D v_2 = new Vector3D(coords[idxB], coords[idxB + 1], coords[idxB + 2]);
Vector3D v_3 = new Vector3D(coords[idxC], coords[idxC + 1], coords[idxC + 2]);
Vector3D[] vertices = {v_1, v_2, v_3};
Plane polyPlane = new Plane(v_1, v_2, v_3);
ArrayList<SubHyperplane<Euclidean2D>> lines = new ArrayList<SubHyperplane<Euclidean2D>>();
Vector2D[] projPts = new Vector2D[vertices.length];
for (int ptIdx = 0; ptIdx < projPts.length; ptIdx++) {
projPts[ptIdx] = polyPlane.toSubSpace(vertices[ptIdx]);
}
SubLine lineInPlane = null;
for (int ptIdx = 0; ptIdx < projPts.length; ptIdx++) {
lineInPlane = new SubLine(projPts[ptIdx], projPts[(ptIdx + 1) % projPts.length]);
lines.add(lineInPlane);
}
Region<Euclidean2D> polyRegion = new PolygonsSet(lines);
SubPlane polygon = new SubPlane(polyPlane, polyRegion);
subHyperplaneList.add(polygon);
}
PolyhedronsSet polyhedronsSet = new PolyhedronsSet(subHyperplaneList);
Assert.assertEquals( 8.0, polyhedronsSet.getSize(), 3.0e-6);
Assert.assertEquals(24.0, polyhedronsSet.getBoundarySize(), 5.0e-6);
} | org.apache.commons.math3.geometry.euclidean.threed.PolyhedronsSetTest::testIssue780 | src/test/java/org/apache/commons/math3/geometry/euclidean/threed/PolyhedronsSetTest.java | 282 | src/test/java/org/apache/commons/math3/geometry/euclidean/threed/PolyhedronsSetTest.java | testIssue780 | /*
* 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.geometry.euclidean.threed;
import java.util.ArrayList;
import org.apache.commons.math3.geometry.euclidean.twod.Euclidean2D;
import org.apache.commons.math3.geometry.euclidean.twod.PolygonsSet;
import org.apache.commons.math3.geometry.euclidean.twod.SubLine;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
import org.apache.commons.math3.geometry.partitioning.BSPTree;
import org.apache.commons.math3.geometry.partitioning.BSPTreeVisitor;
import org.apache.commons.math3.geometry.partitioning.BoundaryAttribute;
import org.apache.commons.math3.geometry.partitioning.Region;
import org.apache.commons.math3.geometry.partitioning.RegionFactory;
import org.apache.commons.math3.geometry.partitioning.SubHyperplane;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
public class PolyhedronsSetTest {
@Test
public void testBox() {
PolyhedronsSet tree = new PolyhedronsSet(0, 1, 0, 1, 0, 1);
Assert.assertEquals(1.0, tree.getSize(), 1.0e-10);
Assert.assertEquals(6.0, tree.getBoundarySize(), 1.0e-10);
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(0.5, barycenter.getX(), 1.0e-10);
Assert.assertEquals(0.5, barycenter.getY(), 1.0e-10);
Assert.assertEquals(0.5, barycenter.getZ(), 1.0e-10);
for (double x = -0.25; x < 1.25; x += 0.1) {
boolean xOK = (x >= 0.0) && (x <= 1.0);
for (double y = -0.25; y < 1.25; y += 0.1) {
boolean yOK = (y >= 0.0) && (y <= 1.0);
for (double z = -0.25; z < 1.25; z += 0.1) {
boolean zOK = (z >= 0.0) && (z <= 1.0);
Region.Location expected =
(xOK && yOK && zOK) ? Region.Location.INSIDE : Region.Location.OUTSIDE;
Assert.assertEquals(expected, tree.checkPoint(new Vector3D(x, y, z)));
}
}
}
checkPoints(Region.Location.BOUNDARY, tree, new Vector3D[] {
new Vector3D(0.0, 0.5, 0.5),
new Vector3D(1.0, 0.5, 0.5),
new Vector3D(0.5, 0.0, 0.5),
new Vector3D(0.5, 1.0, 0.5),
new Vector3D(0.5, 0.5, 0.0),
new Vector3D(0.5, 0.5, 1.0)
});
checkPoints(Region.Location.OUTSIDE, tree, new Vector3D[] {
new Vector3D(0.0, 1.2, 1.2),
new Vector3D(1.0, 1.2, 1.2),
new Vector3D(1.2, 0.0, 1.2),
new Vector3D(1.2, 1.0, 1.2),
new Vector3D(1.2, 1.2, 0.0),
new Vector3D(1.2, 1.2, 1.0)
});
}
@Test
public void testTetrahedron() {
Vector3D vertex1 = new Vector3D(1, 2, 3);
Vector3D vertex2 = new Vector3D(2, 2, 4);
Vector3D vertex3 = new Vector3D(2, 3, 3);
Vector3D vertex4 = new Vector3D(1, 3, 4);
@SuppressWarnings("unchecked")
PolyhedronsSet tree =
(PolyhedronsSet) new RegionFactory<Euclidean3D>().buildConvex(
new Plane(vertex3, vertex2, vertex1),
new Plane(vertex2, vertex3, vertex4),
new Plane(vertex4, vertex3, vertex1),
new Plane(vertex1, vertex2, vertex4));
Assert.assertEquals(1.0 / 3.0, tree.getSize(), 1.0e-10);
Assert.assertEquals(2.0 * FastMath.sqrt(3.0), tree.getBoundarySize(), 1.0e-10);
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(1.5, barycenter.getX(), 1.0e-10);
Assert.assertEquals(2.5, barycenter.getY(), 1.0e-10);
Assert.assertEquals(3.5, barycenter.getZ(), 1.0e-10);
double third = 1.0 / 3.0;
checkPoints(Region.Location.BOUNDARY, tree, new Vector3D[] {
vertex1, vertex2, vertex3, vertex4,
new Vector3D(third, vertex1, third, vertex2, third, vertex3),
new Vector3D(third, vertex2, third, vertex3, third, vertex4),
new Vector3D(third, vertex3, third, vertex4, third, vertex1),
new Vector3D(third, vertex4, third, vertex1, third, vertex2)
});
checkPoints(Region.Location.OUTSIDE, tree, new Vector3D[] {
new Vector3D(1, 2, 4),
new Vector3D(2, 2, 3),
new Vector3D(2, 3, 4),
new Vector3D(1, 3, 3)
});
}
@Test
public void testIsometry() {
Vector3D vertex1 = new Vector3D(1.1, 2.2, 3.3);
Vector3D vertex2 = new Vector3D(2.0, 2.4, 4.2);
Vector3D vertex3 = new Vector3D(2.8, 3.3, 3.7);
Vector3D vertex4 = new Vector3D(1.0, 3.6, 4.5);
@SuppressWarnings("unchecked")
PolyhedronsSet tree =
(PolyhedronsSet) new RegionFactory<Euclidean3D>().buildConvex(
new Plane(vertex3, vertex2, vertex1),
new Plane(vertex2, vertex3, vertex4),
new Plane(vertex4, vertex3, vertex1),
new Plane(vertex1, vertex2, vertex4));
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Vector3D s = new Vector3D(10.2, 4.3, -6.7);
Vector3D c = new Vector3D(-0.2, 2.1, -3.2);
Rotation r = new Rotation(new Vector3D(6.2, -4.4, 2.1), 0.12);
tree = tree.rotate(c, r).translate(s);
Vector3D newB =
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(barycenter.subtract(c)));
Assert.assertEquals(0.0,
newB.subtract(tree.getBarycenter()).getNorm(),
1.0e-10);
final Vector3D[] expectedV = new Vector3D[] {
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex1.subtract(c))),
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex2.subtract(c))),
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex3.subtract(c))),
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex4.subtract(c)))
};
tree.getTree(true).visit(new BSPTreeVisitor<Euclidean3D>() {
public Order visitOrder(BSPTree<Euclidean3D> node) {
return Order.MINUS_SUB_PLUS;
}
public void visitInternalNode(BSPTree<Euclidean3D> node) {
@SuppressWarnings("unchecked")
BoundaryAttribute<Euclidean3D> attribute =
(BoundaryAttribute<Euclidean3D>) node.getAttribute();
if (attribute.getPlusOutside() != null) {
checkFacet((SubPlane) attribute.getPlusOutside());
}
if (attribute.getPlusInside() != null) {
checkFacet((SubPlane) attribute.getPlusInside());
}
}
public void visitLeafNode(BSPTree<Euclidean3D> node) {
}
private void checkFacet(SubPlane facet) {
Plane plane = (Plane) facet.getHyperplane();
Vector2D[][] vertices =
((PolygonsSet) facet.getRemainingRegion()).getVertices();
Assert.assertEquals(1, vertices.length);
for (int i = 0; i < vertices[0].length; ++i) {
Vector3D v = plane.toSpace(vertices[0][i]);
double d = Double.POSITIVE_INFINITY;
for (int k = 0; k < expectedV.length; ++k) {
d = FastMath.min(d, v.subtract(expectedV[k]).getNorm());
}
Assert.assertEquals(0, d, 1.0e-10);
}
}
});
}
@Test
public void testBuildBox() {
double x = 1.0;
double y = 2.0;
double z = 3.0;
double w = 0.1;
double l = 1.0;
PolyhedronsSet tree =
new PolyhedronsSet(x - l, x + l, y - w, y + w, z - w, z + w);
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(x, barycenter.getX(), 1.0e-10);
Assert.assertEquals(y, barycenter.getY(), 1.0e-10);
Assert.assertEquals(z, barycenter.getZ(), 1.0e-10);
Assert.assertEquals(8 * l * w * w, tree.getSize(), 1.0e-10);
Assert.assertEquals(8 * w * (2 * l + w), tree.getBoundarySize(), 1.0e-10);
}
@Test
public void testCross() {
double x = 1.0;
double y = 2.0;
double z = 3.0;
double w = 0.1;
double l = 1.0;
PolyhedronsSet xBeam =
new PolyhedronsSet(x - l, x + l, y - w, y + w, z - w, z + w);
PolyhedronsSet yBeam =
new PolyhedronsSet(x - w, x + w, y - l, y + l, z - w, z + w);
PolyhedronsSet zBeam =
new PolyhedronsSet(x - w, x + w, y - w, y + w, z - l, z + l);
RegionFactory<Euclidean3D> factory = new RegionFactory<Euclidean3D>();
PolyhedronsSet tree = (PolyhedronsSet) factory.union(xBeam, factory.union(yBeam, zBeam));
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(x, barycenter.getX(), 1.0e-10);
Assert.assertEquals(y, barycenter.getY(), 1.0e-10);
Assert.assertEquals(z, barycenter.getZ(), 1.0e-10);
Assert.assertEquals(8 * w * w * (3 * l - 2 * w), tree.getSize(), 1.0e-10);
Assert.assertEquals(24 * w * (2 * l - w), tree.getBoundarySize(), 1.0e-10);
}
@Test
public void testIssue780() {
float[] coords = {
1.000000f, -1.000000f, -1.000000f,
1.000000f, -1.000000f, 1.000000f,
-1.000000f, -1.000000f, 1.000000f,
-1.000000f, -1.000000f, -1.000000f,
1.000000f, 1.000000f, -1f,
0.999999f, 1.000000f, 1.000000f, // 1.000000f, 1.000000f, 1.000000f,
-1.000000f, 1.000000f, 1.000000f,
-1.000000f, 1.000000f, -1.000000f};
int[] indices = {
0, 1, 2, 0, 2, 3,
4, 7, 6, 4, 6, 5,
0, 4, 5, 0, 5, 1,
1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3,
4, 0, 3, 4, 3, 7};
ArrayList<SubHyperplane<Euclidean3D>> subHyperplaneList = new ArrayList<SubHyperplane<Euclidean3D>>();
for (int idx = 0; idx < indices.length; idx += 3) {
int idxA = indices[idx] * 3;
int idxB = indices[idx + 1] * 3;
int idxC = indices[idx + 2] * 3;
Vector3D v_1 = new Vector3D(coords[idxA], coords[idxA + 1], coords[idxA + 2]);
Vector3D v_2 = new Vector3D(coords[idxB], coords[idxB + 1], coords[idxB + 2]);
Vector3D v_3 = new Vector3D(coords[idxC], coords[idxC + 1], coords[idxC + 2]);
Vector3D[] vertices = {v_1, v_2, v_3};
Plane polyPlane = new Plane(v_1, v_2, v_3);
ArrayList<SubHyperplane<Euclidean2D>> lines = new ArrayList<SubHyperplane<Euclidean2D>>();
Vector2D[] projPts = new Vector2D[vertices.length];
for (int ptIdx = 0; ptIdx < projPts.length; ptIdx++) {
projPts[ptIdx] = polyPlane.toSubSpace(vertices[ptIdx]);
}
SubLine lineInPlane = null;
for (int ptIdx = 0; ptIdx < projPts.length; ptIdx++) {
lineInPlane = new SubLine(projPts[ptIdx], projPts[(ptIdx + 1) % projPts.length]);
lines.add(lineInPlane);
}
Region<Euclidean2D> polyRegion = new PolygonsSet(lines);
SubPlane polygon = new SubPlane(polyPlane, polyRegion);
subHyperplaneList.add(polygon);
}
PolyhedronsSet polyhedronsSet = new PolyhedronsSet(subHyperplaneList);
Assert.assertEquals( 8.0, polyhedronsSet.getSize(), 3.0e-6);
Assert.assertEquals(24.0, polyhedronsSet.getBoundarySize(), 5.0e-6);
}
private void checkPoints(Region.Location expected, PolyhedronsSet tree, Vector3D[] points) {
for (int i = 0; i < points.length; ++i) {
Assert.assertEquals(expected, tree.checkPoint(points[i]));
}
}
} | // You are a professional Java test case writer, please create a test case named `testIssue780` for the issue `Math-MATH-780`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-780
//
// ## Issue-Title:
// BSPTree class and recovery of a Euclidean 3D BRep
//
// ## Issue-Description:
//
// New to the work here. Thanks for your efforts on this code.
//
//
// I create a BSPTree from a BoundaryRep (Brep) my test Brep is a cube as represented by a float array containing 8 3D points in(x,y,z) order and an array of indices (12 triplets for the 12 faces of the cube). I construct a BSPMesh() as shown in the code below. I can construct the PolyhedronsSet() but have problems extracting the faces from the BSPTree to reconstruct the BRep. The attached code (BSPMesh2.java) shows that a small change to 1 of the vertex positions causes/corrects the problem.
//
//
// Any ideas?
//
//
//
//
//
@Test
public void testIssue780() {
| 282 | 32 | 235 | src/test/java/org/apache/commons/math3/geometry/euclidean/threed/PolyhedronsSetTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-780
## Issue-Title:
BSPTree class and recovery of a Euclidean 3D BRep
## Issue-Description:
New to the work here. Thanks for your efforts on this code.
I create a BSPTree from a BoundaryRep (Brep) my test Brep is a cube as represented by a float array containing 8 3D points in(x,y,z) order and an array of indices (12 triplets for the 12 faces of the cube). I construct a BSPMesh() as shown in the code below. I can construct the PolyhedronsSet() but have problems extracting the faces from the BSPTree to reconstruct the BRep. The attached code (BSPMesh2.java) shows that a small change to 1 of the vertex positions causes/corrects the problem.
Any ideas?
```
You are a professional Java test case writer, please create a test case named `testIssue780` for the issue `Math-MATH-780`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testIssue780() {
```
| 235 | [
"org.apache.commons.math3.geometry.euclidean.twod.PolygonsSet"
] | 44f600f1fe6d1db53deefd7f2f654b3ff38e98f1222d5da6088094c35a7f4e78 | @Test
public void testIssue780() | // You are a professional Java test case writer, please create a test case named `testIssue780` for the issue `Math-MATH-780`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-780
//
// ## Issue-Title:
// BSPTree class and recovery of a Euclidean 3D BRep
//
// ## Issue-Description:
//
// New to the work here. Thanks for your efforts on this code.
//
//
// I create a BSPTree from a BoundaryRep (Brep) my test Brep is a cube as represented by a float array containing 8 3D points in(x,y,z) order and an array of indices (12 triplets for the 12 faces of the cube). I construct a BSPMesh() as shown in the code below. I can construct the PolyhedronsSet() but have problems extracting the faces from the BSPTree to reconstruct the BRep. The attached code (BSPMesh2.java) shows that a small change to 1 of the vertex positions causes/corrects the problem.
//
//
// Any ideas?
//
//
//
//
//
| 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.geometry.euclidean.threed;
import java.util.ArrayList;
import org.apache.commons.math3.geometry.euclidean.twod.Euclidean2D;
import org.apache.commons.math3.geometry.euclidean.twod.PolygonsSet;
import org.apache.commons.math3.geometry.euclidean.twod.SubLine;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
import org.apache.commons.math3.geometry.partitioning.BSPTree;
import org.apache.commons.math3.geometry.partitioning.BSPTreeVisitor;
import org.apache.commons.math3.geometry.partitioning.BoundaryAttribute;
import org.apache.commons.math3.geometry.partitioning.Region;
import org.apache.commons.math3.geometry.partitioning.RegionFactory;
import org.apache.commons.math3.geometry.partitioning.SubHyperplane;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
public class PolyhedronsSetTest {
@Test
public void testBox() {
PolyhedronsSet tree = new PolyhedronsSet(0, 1, 0, 1, 0, 1);
Assert.assertEquals(1.0, tree.getSize(), 1.0e-10);
Assert.assertEquals(6.0, tree.getBoundarySize(), 1.0e-10);
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(0.5, barycenter.getX(), 1.0e-10);
Assert.assertEquals(0.5, barycenter.getY(), 1.0e-10);
Assert.assertEquals(0.5, barycenter.getZ(), 1.0e-10);
for (double x = -0.25; x < 1.25; x += 0.1) {
boolean xOK = (x >= 0.0) && (x <= 1.0);
for (double y = -0.25; y < 1.25; y += 0.1) {
boolean yOK = (y >= 0.0) && (y <= 1.0);
for (double z = -0.25; z < 1.25; z += 0.1) {
boolean zOK = (z >= 0.0) && (z <= 1.0);
Region.Location expected =
(xOK && yOK && zOK) ? Region.Location.INSIDE : Region.Location.OUTSIDE;
Assert.assertEquals(expected, tree.checkPoint(new Vector3D(x, y, z)));
}
}
}
checkPoints(Region.Location.BOUNDARY, tree, new Vector3D[] {
new Vector3D(0.0, 0.5, 0.5),
new Vector3D(1.0, 0.5, 0.5),
new Vector3D(0.5, 0.0, 0.5),
new Vector3D(0.5, 1.0, 0.5),
new Vector3D(0.5, 0.5, 0.0),
new Vector3D(0.5, 0.5, 1.0)
});
checkPoints(Region.Location.OUTSIDE, tree, new Vector3D[] {
new Vector3D(0.0, 1.2, 1.2),
new Vector3D(1.0, 1.2, 1.2),
new Vector3D(1.2, 0.0, 1.2),
new Vector3D(1.2, 1.0, 1.2),
new Vector3D(1.2, 1.2, 0.0),
new Vector3D(1.2, 1.2, 1.0)
});
}
@Test
public void testTetrahedron() {
Vector3D vertex1 = new Vector3D(1, 2, 3);
Vector3D vertex2 = new Vector3D(2, 2, 4);
Vector3D vertex3 = new Vector3D(2, 3, 3);
Vector3D vertex4 = new Vector3D(1, 3, 4);
@SuppressWarnings("unchecked")
PolyhedronsSet tree =
(PolyhedronsSet) new RegionFactory<Euclidean3D>().buildConvex(
new Plane(vertex3, vertex2, vertex1),
new Plane(vertex2, vertex3, vertex4),
new Plane(vertex4, vertex3, vertex1),
new Plane(vertex1, vertex2, vertex4));
Assert.assertEquals(1.0 / 3.0, tree.getSize(), 1.0e-10);
Assert.assertEquals(2.0 * FastMath.sqrt(3.0), tree.getBoundarySize(), 1.0e-10);
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(1.5, barycenter.getX(), 1.0e-10);
Assert.assertEquals(2.5, barycenter.getY(), 1.0e-10);
Assert.assertEquals(3.5, barycenter.getZ(), 1.0e-10);
double third = 1.0 / 3.0;
checkPoints(Region.Location.BOUNDARY, tree, new Vector3D[] {
vertex1, vertex2, vertex3, vertex4,
new Vector3D(third, vertex1, third, vertex2, third, vertex3),
new Vector3D(third, vertex2, third, vertex3, third, vertex4),
new Vector3D(third, vertex3, third, vertex4, third, vertex1),
new Vector3D(third, vertex4, third, vertex1, third, vertex2)
});
checkPoints(Region.Location.OUTSIDE, tree, new Vector3D[] {
new Vector3D(1, 2, 4),
new Vector3D(2, 2, 3),
new Vector3D(2, 3, 4),
new Vector3D(1, 3, 3)
});
}
@Test
public void testIsometry() {
Vector3D vertex1 = new Vector3D(1.1, 2.2, 3.3);
Vector3D vertex2 = new Vector3D(2.0, 2.4, 4.2);
Vector3D vertex3 = new Vector3D(2.8, 3.3, 3.7);
Vector3D vertex4 = new Vector3D(1.0, 3.6, 4.5);
@SuppressWarnings("unchecked")
PolyhedronsSet tree =
(PolyhedronsSet) new RegionFactory<Euclidean3D>().buildConvex(
new Plane(vertex3, vertex2, vertex1),
new Plane(vertex2, vertex3, vertex4),
new Plane(vertex4, vertex3, vertex1),
new Plane(vertex1, vertex2, vertex4));
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Vector3D s = new Vector3D(10.2, 4.3, -6.7);
Vector3D c = new Vector3D(-0.2, 2.1, -3.2);
Rotation r = new Rotation(new Vector3D(6.2, -4.4, 2.1), 0.12);
tree = tree.rotate(c, r).translate(s);
Vector3D newB =
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(barycenter.subtract(c)));
Assert.assertEquals(0.0,
newB.subtract(tree.getBarycenter()).getNorm(),
1.0e-10);
final Vector3D[] expectedV = new Vector3D[] {
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex1.subtract(c))),
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex2.subtract(c))),
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex3.subtract(c))),
new Vector3D(1.0, s,
1.0, c,
1.0, r.applyTo(vertex4.subtract(c)))
};
tree.getTree(true).visit(new BSPTreeVisitor<Euclidean3D>() {
public Order visitOrder(BSPTree<Euclidean3D> node) {
return Order.MINUS_SUB_PLUS;
}
public void visitInternalNode(BSPTree<Euclidean3D> node) {
@SuppressWarnings("unchecked")
BoundaryAttribute<Euclidean3D> attribute =
(BoundaryAttribute<Euclidean3D>) node.getAttribute();
if (attribute.getPlusOutside() != null) {
checkFacet((SubPlane) attribute.getPlusOutside());
}
if (attribute.getPlusInside() != null) {
checkFacet((SubPlane) attribute.getPlusInside());
}
}
public void visitLeafNode(BSPTree<Euclidean3D> node) {
}
private void checkFacet(SubPlane facet) {
Plane plane = (Plane) facet.getHyperplane();
Vector2D[][] vertices =
((PolygonsSet) facet.getRemainingRegion()).getVertices();
Assert.assertEquals(1, vertices.length);
for (int i = 0; i < vertices[0].length; ++i) {
Vector3D v = plane.toSpace(vertices[0][i]);
double d = Double.POSITIVE_INFINITY;
for (int k = 0; k < expectedV.length; ++k) {
d = FastMath.min(d, v.subtract(expectedV[k]).getNorm());
}
Assert.assertEquals(0, d, 1.0e-10);
}
}
});
}
@Test
public void testBuildBox() {
double x = 1.0;
double y = 2.0;
double z = 3.0;
double w = 0.1;
double l = 1.0;
PolyhedronsSet tree =
new PolyhedronsSet(x - l, x + l, y - w, y + w, z - w, z + w);
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(x, barycenter.getX(), 1.0e-10);
Assert.assertEquals(y, barycenter.getY(), 1.0e-10);
Assert.assertEquals(z, barycenter.getZ(), 1.0e-10);
Assert.assertEquals(8 * l * w * w, tree.getSize(), 1.0e-10);
Assert.assertEquals(8 * w * (2 * l + w), tree.getBoundarySize(), 1.0e-10);
}
@Test
public void testCross() {
double x = 1.0;
double y = 2.0;
double z = 3.0;
double w = 0.1;
double l = 1.0;
PolyhedronsSet xBeam =
new PolyhedronsSet(x - l, x + l, y - w, y + w, z - w, z + w);
PolyhedronsSet yBeam =
new PolyhedronsSet(x - w, x + w, y - l, y + l, z - w, z + w);
PolyhedronsSet zBeam =
new PolyhedronsSet(x - w, x + w, y - w, y + w, z - l, z + l);
RegionFactory<Euclidean3D> factory = new RegionFactory<Euclidean3D>();
PolyhedronsSet tree = (PolyhedronsSet) factory.union(xBeam, factory.union(yBeam, zBeam));
Vector3D barycenter = (Vector3D) tree.getBarycenter();
Assert.assertEquals(x, barycenter.getX(), 1.0e-10);
Assert.assertEquals(y, barycenter.getY(), 1.0e-10);
Assert.assertEquals(z, barycenter.getZ(), 1.0e-10);
Assert.assertEquals(8 * w * w * (3 * l - 2 * w), tree.getSize(), 1.0e-10);
Assert.assertEquals(24 * w * (2 * l - w), tree.getBoundarySize(), 1.0e-10);
}
@Test
public void testIssue780() {
float[] coords = {
1.000000f, -1.000000f, -1.000000f,
1.000000f, -1.000000f, 1.000000f,
-1.000000f, -1.000000f, 1.000000f,
-1.000000f, -1.000000f, -1.000000f,
1.000000f, 1.000000f, -1f,
0.999999f, 1.000000f, 1.000000f, // 1.000000f, 1.000000f, 1.000000f,
-1.000000f, 1.000000f, 1.000000f,
-1.000000f, 1.000000f, -1.000000f};
int[] indices = {
0, 1, 2, 0, 2, 3,
4, 7, 6, 4, 6, 5,
0, 4, 5, 0, 5, 1,
1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3,
4, 0, 3, 4, 3, 7};
ArrayList<SubHyperplane<Euclidean3D>> subHyperplaneList = new ArrayList<SubHyperplane<Euclidean3D>>();
for (int idx = 0; idx < indices.length; idx += 3) {
int idxA = indices[idx] * 3;
int idxB = indices[idx + 1] * 3;
int idxC = indices[idx + 2] * 3;
Vector3D v_1 = new Vector3D(coords[idxA], coords[idxA + 1], coords[idxA + 2]);
Vector3D v_2 = new Vector3D(coords[idxB], coords[idxB + 1], coords[idxB + 2]);
Vector3D v_3 = new Vector3D(coords[idxC], coords[idxC + 1], coords[idxC + 2]);
Vector3D[] vertices = {v_1, v_2, v_3};
Plane polyPlane = new Plane(v_1, v_2, v_3);
ArrayList<SubHyperplane<Euclidean2D>> lines = new ArrayList<SubHyperplane<Euclidean2D>>();
Vector2D[] projPts = new Vector2D[vertices.length];
for (int ptIdx = 0; ptIdx < projPts.length; ptIdx++) {
projPts[ptIdx] = polyPlane.toSubSpace(vertices[ptIdx]);
}
SubLine lineInPlane = null;
for (int ptIdx = 0; ptIdx < projPts.length; ptIdx++) {
lineInPlane = new SubLine(projPts[ptIdx], projPts[(ptIdx + 1) % projPts.length]);
lines.add(lineInPlane);
}
Region<Euclidean2D> polyRegion = new PolygonsSet(lines);
SubPlane polygon = new SubPlane(polyPlane, polyRegion);
subHyperplaneList.add(polygon);
}
PolyhedronsSet polyhedronsSet = new PolyhedronsSet(subHyperplaneList);
Assert.assertEquals( 8.0, polyhedronsSet.getSize(), 3.0e-6);
Assert.assertEquals(24.0, polyhedronsSet.getBoundarySize(), 5.0e-6);
}
private void checkPoints(Region.Location expected, PolyhedronsSet tree, Vector3D[] points) {
for (int i = 0; i < points.length; ++i) {
Assert.assertEquals(expected, tree.checkPoint(points[i]));
}
}
} |
||
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);
} | org.apache.commons.lang.math.FractionTest::testReduce | src/test/org/apache/commons/lang/math/FractionTest.java | 656 | src/test/org/apache/commons/lang/math/FractionTest.java | testReduce | /*
* 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.math;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test cases for the {@link Fraction} class
*
* @author Stephen Colebourne
* @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 static Test suite() {
TestSuite suite = new TestSuite(FractionTest.class);
suite.setName("Fraction Tests");
return suite;
}
public void setUp() {
}
//--------------------------------------------------------------------------
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) {}
}
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);
}
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) {}
try {
f1.compareTo(new Object());
fail("expecting ClassCastException");
} catch (ClassCastException 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 `testReduce` for the issue `Lang-LANG-380`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-380
//
// ## Issue-Title:
// infinite loop in Fraction.reduce when numerator == 0
//
// ## Issue-Description:
//
// Summary pretty much says it all.
//
//
//
//
//
public void testReduce() {
| 656 | 49 | 615 | src/test/org/apache/commons/lang/math/FractionTest.java | src/test | ```markdown
## Issue-ID: Lang-LANG-380
## Issue-Title:
infinite loop in Fraction.reduce when numerator == 0
## Issue-Description:
Summary pretty much says it all.
```
You are a professional Java test case writer, please create a test case named `testReduce` for the issue `Lang-LANG-380`, utilizing the provided issue report information and the following function signature.
```java
public void testReduce() {
```
| 615 | [
"org.apache.commons.lang.math.Fraction"
] | 453c38c5c242a326c227bc656db653e88de47e4d600a684c0493f0271098581b | public void testReduce() | // You are a professional Java test case writer, please create a test case named `testReduce` for the issue `Lang-LANG-380`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-380
//
// ## Issue-Title:
// infinite loop in Fraction.reduce when numerator == 0
//
// ## Issue-Description:
//
// Summary pretty much says it all.
//
//
//
//
//
| 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.math;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Test cases for the {@link Fraction} class
*
* @author Stephen Colebourne
* @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 static Test suite() {
TestSuite suite = new TestSuite(FractionTest.class);
suite.setName("Fraction Tests");
return suite;
}
public void setUp() {
}
//--------------------------------------------------------------------------
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) {}
}
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);
}
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) {}
try {
f1.compareTo(new Object());
fail("expecting ClassCastException");
} catch (ClassCastException 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 testGreatestSubtypeUnionTypes5() throws Exception {
JSType errUnion = createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(NO_OBJECT_TYPE,
errUnion.getGreatestSubtype(STRING_OBJECT_TYPE));
} | com.google.javascript.rhino.jstype.UnionTypeTest::testGreatestSubtypeUnionTypes5 | test/com/google/javascript/rhino/jstype/UnionTypeTest.java | 160 | test/com/google/javascript/rhino/jstype/UnionTypeTest.java | testGreatestSubtypeUnionTypes5 | /*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Nick Santos
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino.jstype;
import com.google.javascript.rhino.testing.BaseJSTypeTestCase;
import com.google.javascript.rhino.testing.Asserts;
public class UnionTypeTest extends BaseJSTypeTestCase {
private NamedType unresolvedNamedType;
@Override
public void setUp() throws Exception {
super.setUp();
unresolvedNamedType =
new NamedType(registry, "not.resolved.named.type", null, -1, -1);
}
/**
* Assert that a type can assign to itself.
*/
private void assertTypeCanAssignToItself(JSType type) {
assertTrue(type.canAssignTo(type));
}
/**
* Tests the behavior of variants type.
*/
@SuppressWarnings("checked")
public void testUnionType() throws Exception {
UnionType nullOrString =
(UnionType) createUnionType(NULL_TYPE, STRING_OBJECT_TYPE);
UnionType stringOrNull =
(UnionType) createUnionType(STRING_OBJECT_TYPE, NULL_TYPE);
assertEquals(nullOrString, stringOrNull);
assertEquals(stringOrNull, nullOrString);
assertTypeCanAssignToItself(createUnionType(VOID_TYPE, NUMBER_TYPE));
assertTypeCanAssignToItself(
createUnionType(NUMBER_TYPE, STRING_TYPE, OBJECT_TYPE));
assertTypeCanAssignToItself(createUnionType(NUMBER_TYPE, BOOLEAN_TYPE));
assertTypeCanAssignToItself(createUnionType(VOID_TYPE));
UnionType nullOrUnknown =
(UnionType) createUnionType(NULL_TYPE, unresolvedNamedType);
assertTrue(nullOrUnknown.isUnknownType());
assertEquals(nullOrUnknown, NULL_TYPE.getLeastSupertype(nullOrUnknown));
assertEquals(nullOrUnknown, nullOrUnknown.getLeastSupertype(NULL_TYPE));
assertEquals(UNKNOWN_TYPE,
NULL_TYPE.getGreatestSubtype(nullOrUnknown));
assertEquals(UNKNOWN_TYPE,
nullOrUnknown.getGreatestSubtype(NULL_TYPE));
assertTrue(NULL_TYPE.differsFrom(nullOrUnknown));
assertTrue(nullOrUnknown.differsFrom(NULL_TYPE));
assertFalse(nullOrUnknown.differsFrom(unresolvedNamedType));
assertTrue(NULL_TYPE.isSubtype(nullOrUnknown));
assertTrue(unresolvedNamedType.isSubtype(nullOrUnknown));
assertTrue(nullOrUnknown.isSubtype(NULL_TYPE));
assertEquals(unresolvedNamedType,
nullOrUnknown.restrictByNotNullOrUndefined());
// findPropertyType
assertEquals(NUMBER_TYPE, nullOrString.findPropertyType("length"));
assertEquals(null, nullOrString.findPropertyType("lengthx"));
Asserts.assertResolvesToSame(nullOrString);
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
public void testGreatestSubtypeUnionTypes1() {
assertEquals(NULL_TYPE, createNullableType(STRING_TYPE).getGreatestSubtype(
createNullableType(NUMBER_TYPE)));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
@SuppressWarnings("checked")
public void testGreatestSubtypeUnionTypes2() {
UnionType evalUriError =
(UnionType) createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(evalUriError,
evalUriError.getGreatestSubtype(ERROR_TYPE));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
@SuppressWarnings("checked")
public void testGreatestSubtypeUnionTypes3() {
// (number,undefined,null)
UnionType nullableOptionalNumber =
(UnionType) createUnionType(NULL_TYPE, VOID_TYPE, NUMBER_TYPE);
// (null,undefined)
UnionType nullUndefined =
(UnionType) createUnionType(VOID_TYPE, NULL_TYPE);
assertEquals(nullUndefined,
nullUndefined.getGreatestSubtype(nullableOptionalNumber));
assertEquals(nullUndefined,
nullableOptionalNumber.getGreatestSubtype(nullUndefined));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
public void testGreatestSubtypeUnionTypes4() throws Exception {
UnionType errUnion = (UnionType) createUnionType(
NULL_TYPE, EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE),
errUnion.getGreatestSubtype(ERROR_TYPE));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
public void testGreatestSubtypeUnionTypes5() throws Exception {
JSType errUnion = createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(NO_OBJECT_TYPE,
errUnion.getGreatestSubtype(STRING_OBJECT_TYPE));
}
/**
* Tests subtyping of union types.
*/
public void testSubtypingUnionTypes() throws Exception {
// subtypes
assertTrue(BOOLEAN_TYPE.
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE, STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE, STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE, STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(STRING_TYPE, NULL_TYPE).isSubtype(ALL_TYPE));
assertTrue(createUnionType(DATE_TYPE, REGEXP_TYPE).isSubtype(OBJECT_TYPE));
assertTrue(createUnionType(URI_ERROR_TYPE, EVAL_ERROR_TYPE).
isSubtype(ERROR_TYPE));
assertTrue(createUnionType(URI_ERROR_TYPE, EVAL_ERROR_TYPE).
isSubtype(OBJECT_TYPE));
// not subtypes
assertFalse(createUnionType(STRING_TYPE, NULL_TYPE).isSubtype(NO_TYPE));
assertFalse(createUnionType(STRING_TYPE, NULL_TYPE).
isSubtype(NO_OBJECT_TYPE));
assertFalse(createUnionType(NO_OBJECT_TYPE, NULL_TYPE).
isSubtype(OBJECT_TYPE));
// defined unions
assertTrue(NUMBER_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(STRING_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(NUMBER_TYPE.isSubtype(NUMBER_STRING_BOOLEAN));
assertTrue(BOOLEAN_TYPE.isSubtype(NUMBER_STRING_BOOLEAN));
assertTrue(STRING_TYPE.isSubtype(NUMBER_STRING_BOOLEAN));
assertTrue(NUMBER_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(STRING_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(BOOLEAN_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
}
/**
* Tests that special union types can assign to other types. Unions
* containing the unknown type should be able to assign to any other
* type.
*/
@SuppressWarnings("checked")
public void testSpecialUnionCanAssignTo() throws Exception {
// autoboxing quirks
UnionType numbers =
(UnionType) createUnionType(NUMBER_TYPE, NUMBER_OBJECT_TYPE);
assertFalse(numbers.canAssignTo(NUMBER_TYPE));
assertFalse(numbers.canAssignTo(NUMBER_OBJECT_TYPE));
assertFalse(numbers.canAssignTo(EVAL_ERROR_TYPE));
UnionType strings =
(UnionType) createUnionType(STRING_OBJECT_TYPE, STRING_TYPE);
assertFalse(strings.canAssignTo(STRING_TYPE));
assertFalse(strings.canAssignTo(STRING_OBJECT_TYPE));
assertFalse(strings.canAssignTo(DATE_TYPE));
UnionType booleans =
(UnionType) createUnionType(BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE);
assertFalse(booleans.canAssignTo(BOOLEAN_TYPE));
assertFalse(booleans.canAssignTo(BOOLEAN_OBJECT_TYPE));
assertFalse(booleans.canAssignTo(REGEXP_TYPE));
// unknown quirks
JSType unknown = createUnionType(UNKNOWN_TYPE, DATE_TYPE);
assertTrue(unknown.canAssignTo(STRING_TYPE));
// all members need to be assignable to
UnionType stringDate =
(UnionType) createUnionType(STRING_OBJECT_TYPE, DATE_TYPE);
assertTrue(stringDate.canAssignTo(OBJECT_TYPE));
assertFalse(stringDate.canAssignTo(STRING_OBJECT_TYPE));
assertFalse(stringDate.canAssignTo(DATE_TYPE));
}
/**
* Tests the factory method
* {@link JSTypeRegistry#createUnionType(JSType...)}.
*/
@SuppressWarnings("checked")
public void testCreateUnionType() throws Exception {
// number
UnionType optNumber =
(UnionType) registry.createUnionType(NUMBER_TYPE, DATE_TYPE);
assertTrue(optNumber.contains(NUMBER_TYPE));
assertTrue(optNumber.contains(DATE_TYPE));
// union
UnionType optUnion =
(UnionType) registry.createUnionType(REGEXP_TYPE,
registry.createUnionType(STRING_OBJECT_TYPE, DATE_TYPE));
assertTrue(optUnion.contains(DATE_TYPE));
assertTrue(optUnion.contains(STRING_OBJECT_TYPE));
assertTrue(optUnion.contains(REGEXP_TYPE));
}
public void testUnionWithUnknown() throws Exception {
assertTrue(createUnionType(UNKNOWN_TYPE, NULL_TYPE).isUnknownType());
}
public void testGetRestrictedUnion1() throws Exception {
UnionType numStr = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE);
assertEquals(STRING_TYPE, numStr.getRestrictedUnion(NUMBER_TYPE));
}
public void testGetRestrictedUnion2() throws Exception {
UnionType numStr = (UnionType) createUnionType(
NULL_TYPE, EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(NULL_TYPE, numStr.getRestrictedUnion(ERROR_TYPE));
}
} | // You are a professional Java test case writer, please create a test case named `testGreatestSubtypeUnionTypes5` for the issue `Closure-114`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-114
//
// ## Issue-Title:
// Typos in externs/html5.js
//
// ## Issue-Description:
// Line 354:
// CanvasRenderingContext2D.prototype.globalCompositingOperation;
//
// Line 366:
// CanvasRenderingContext2D.prototype.mitreLimit;
//
// They should be globalCompositeOperation and miterLimit, respectively.
//
//
public void testGreatestSubtypeUnionTypes5() throws Exception {
| 160 | /**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/ | 104 | 156 | test/com/google/javascript/rhino/jstype/UnionTypeTest.java | test | ```markdown
## Issue-ID: Closure-114
## Issue-Title:
Typos in externs/html5.js
## Issue-Description:
Line 354:
CanvasRenderingContext2D.prototype.globalCompositingOperation;
Line 366:
CanvasRenderingContext2D.prototype.mitreLimit;
They should be globalCompositeOperation and miterLimit, respectively.
```
You are a professional Java test case writer, please create a test case named `testGreatestSubtypeUnionTypes5` for the issue `Closure-114`, utilizing the provided issue report information and the following function signature.
```java
public void testGreatestSubtypeUnionTypes5() throws Exception {
```
| 156 | [
"com.google.javascript.rhino.jstype.UnionType"
] | 459f263e42a2ccdeb97a6af98ef2e04bcb3b7cc123b3cf80e2117fd3c0abb836 | public void testGreatestSubtypeUnionTypes5() throws Exception | // You are a professional Java test case writer, please create a test case named `testGreatestSubtypeUnionTypes5` for the issue `Closure-114`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-114
//
// ## Issue-Title:
// Typos in externs/html5.js
//
// ## Issue-Description:
// Line 354:
// CanvasRenderingContext2D.prototype.globalCompositingOperation;
//
// Line 366:
// CanvasRenderingContext2D.prototype.mitreLimit;
//
// They should be globalCompositeOperation and miterLimit, respectively.
//
//
| Closure | /*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Nick Santos
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino.jstype;
import com.google.javascript.rhino.testing.BaseJSTypeTestCase;
import com.google.javascript.rhino.testing.Asserts;
public class UnionTypeTest extends BaseJSTypeTestCase {
private NamedType unresolvedNamedType;
@Override
public void setUp() throws Exception {
super.setUp();
unresolvedNamedType =
new NamedType(registry, "not.resolved.named.type", null, -1, -1);
}
/**
* Assert that a type can assign to itself.
*/
private void assertTypeCanAssignToItself(JSType type) {
assertTrue(type.canAssignTo(type));
}
/**
* Tests the behavior of variants type.
*/
@SuppressWarnings("checked")
public void testUnionType() throws Exception {
UnionType nullOrString =
(UnionType) createUnionType(NULL_TYPE, STRING_OBJECT_TYPE);
UnionType stringOrNull =
(UnionType) createUnionType(STRING_OBJECT_TYPE, NULL_TYPE);
assertEquals(nullOrString, stringOrNull);
assertEquals(stringOrNull, nullOrString);
assertTypeCanAssignToItself(createUnionType(VOID_TYPE, NUMBER_TYPE));
assertTypeCanAssignToItself(
createUnionType(NUMBER_TYPE, STRING_TYPE, OBJECT_TYPE));
assertTypeCanAssignToItself(createUnionType(NUMBER_TYPE, BOOLEAN_TYPE));
assertTypeCanAssignToItself(createUnionType(VOID_TYPE));
UnionType nullOrUnknown =
(UnionType) createUnionType(NULL_TYPE, unresolvedNamedType);
assertTrue(nullOrUnknown.isUnknownType());
assertEquals(nullOrUnknown, NULL_TYPE.getLeastSupertype(nullOrUnknown));
assertEquals(nullOrUnknown, nullOrUnknown.getLeastSupertype(NULL_TYPE));
assertEquals(UNKNOWN_TYPE,
NULL_TYPE.getGreatestSubtype(nullOrUnknown));
assertEquals(UNKNOWN_TYPE,
nullOrUnknown.getGreatestSubtype(NULL_TYPE));
assertTrue(NULL_TYPE.differsFrom(nullOrUnknown));
assertTrue(nullOrUnknown.differsFrom(NULL_TYPE));
assertFalse(nullOrUnknown.differsFrom(unresolvedNamedType));
assertTrue(NULL_TYPE.isSubtype(nullOrUnknown));
assertTrue(unresolvedNamedType.isSubtype(nullOrUnknown));
assertTrue(nullOrUnknown.isSubtype(NULL_TYPE));
assertEquals(unresolvedNamedType,
nullOrUnknown.restrictByNotNullOrUndefined());
// findPropertyType
assertEquals(NUMBER_TYPE, nullOrString.findPropertyType("length"));
assertEquals(null, nullOrString.findPropertyType("lengthx"));
Asserts.assertResolvesToSame(nullOrString);
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
public void testGreatestSubtypeUnionTypes1() {
assertEquals(NULL_TYPE, createNullableType(STRING_TYPE).getGreatestSubtype(
createNullableType(NUMBER_TYPE)));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
@SuppressWarnings("checked")
public void testGreatestSubtypeUnionTypes2() {
UnionType evalUriError =
(UnionType) createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(evalUriError,
evalUriError.getGreatestSubtype(ERROR_TYPE));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
@SuppressWarnings("checked")
public void testGreatestSubtypeUnionTypes3() {
// (number,undefined,null)
UnionType nullableOptionalNumber =
(UnionType) createUnionType(NULL_TYPE, VOID_TYPE, NUMBER_TYPE);
// (null,undefined)
UnionType nullUndefined =
(UnionType) createUnionType(VOID_TYPE, NULL_TYPE);
assertEquals(nullUndefined,
nullUndefined.getGreatestSubtype(nullableOptionalNumber));
assertEquals(nullUndefined,
nullableOptionalNumber.getGreatestSubtype(nullUndefined));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
public void testGreatestSubtypeUnionTypes4() throws Exception {
UnionType errUnion = (UnionType) createUnionType(
NULL_TYPE, EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE),
errUnion.getGreatestSubtype(ERROR_TYPE));
}
/**
* Tests {@link JSType#getGreatestSubtype(JSType)} on union types.
*/
public void testGreatestSubtypeUnionTypes5() throws Exception {
JSType errUnion = createUnionType(EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(NO_OBJECT_TYPE,
errUnion.getGreatestSubtype(STRING_OBJECT_TYPE));
}
/**
* Tests subtyping of union types.
*/
public void testSubtypingUnionTypes() throws Exception {
// subtypes
assertTrue(BOOLEAN_TYPE.
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE, STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE, STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE, STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(BOOLEAN_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(STRING_TYPE).
isSubtype(createUnionType(BOOLEAN_TYPE, STRING_TYPE, NULL_TYPE)));
assertTrue(createUnionType(STRING_TYPE, NULL_TYPE).isSubtype(ALL_TYPE));
assertTrue(createUnionType(DATE_TYPE, REGEXP_TYPE).isSubtype(OBJECT_TYPE));
assertTrue(createUnionType(URI_ERROR_TYPE, EVAL_ERROR_TYPE).
isSubtype(ERROR_TYPE));
assertTrue(createUnionType(URI_ERROR_TYPE, EVAL_ERROR_TYPE).
isSubtype(OBJECT_TYPE));
// not subtypes
assertFalse(createUnionType(STRING_TYPE, NULL_TYPE).isSubtype(NO_TYPE));
assertFalse(createUnionType(STRING_TYPE, NULL_TYPE).
isSubtype(NO_OBJECT_TYPE));
assertFalse(createUnionType(NO_OBJECT_TYPE, NULL_TYPE).
isSubtype(OBJECT_TYPE));
// defined unions
assertTrue(NUMBER_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(STRING_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING));
assertTrue(NUMBER_TYPE.isSubtype(NUMBER_STRING_BOOLEAN));
assertTrue(BOOLEAN_TYPE.isSubtype(NUMBER_STRING_BOOLEAN));
assertTrue(STRING_TYPE.isSubtype(NUMBER_STRING_BOOLEAN));
assertTrue(NUMBER_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(STRING_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(BOOLEAN_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_NUMBER_STRING_BOOLEAN));
}
/**
* Tests that special union types can assign to other types. Unions
* containing the unknown type should be able to assign to any other
* type.
*/
@SuppressWarnings("checked")
public void testSpecialUnionCanAssignTo() throws Exception {
// autoboxing quirks
UnionType numbers =
(UnionType) createUnionType(NUMBER_TYPE, NUMBER_OBJECT_TYPE);
assertFalse(numbers.canAssignTo(NUMBER_TYPE));
assertFalse(numbers.canAssignTo(NUMBER_OBJECT_TYPE));
assertFalse(numbers.canAssignTo(EVAL_ERROR_TYPE));
UnionType strings =
(UnionType) createUnionType(STRING_OBJECT_TYPE, STRING_TYPE);
assertFalse(strings.canAssignTo(STRING_TYPE));
assertFalse(strings.canAssignTo(STRING_OBJECT_TYPE));
assertFalse(strings.canAssignTo(DATE_TYPE));
UnionType booleans =
(UnionType) createUnionType(BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE);
assertFalse(booleans.canAssignTo(BOOLEAN_TYPE));
assertFalse(booleans.canAssignTo(BOOLEAN_OBJECT_TYPE));
assertFalse(booleans.canAssignTo(REGEXP_TYPE));
// unknown quirks
JSType unknown = createUnionType(UNKNOWN_TYPE, DATE_TYPE);
assertTrue(unknown.canAssignTo(STRING_TYPE));
// all members need to be assignable to
UnionType stringDate =
(UnionType) createUnionType(STRING_OBJECT_TYPE, DATE_TYPE);
assertTrue(stringDate.canAssignTo(OBJECT_TYPE));
assertFalse(stringDate.canAssignTo(STRING_OBJECT_TYPE));
assertFalse(stringDate.canAssignTo(DATE_TYPE));
}
/**
* Tests the factory method
* {@link JSTypeRegistry#createUnionType(JSType...)}.
*/
@SuppressWarnings("checked")
public void testCreateUnionType() throws Exception {
// number
UnionType optNumber =
(UnionType) registry.createUnionType(NUMBER_TYPE, DATE_TYPE);
assertTrue(optNumber.contains(NUMBER_TYPE));
assertTrue(optNumber.contains(DATE_TYPE));
// union
UnionType optUnion =
(UnionType) registry.createUnionType(REGEXP_TYPE,
registry.createUnionType(STRING_OBJECT_TYPE, DATE_TYPE));
assertTrue(optUnion.contains(DATE_TYPE));
assertTrue(optUnion.contains(STRING_OBJECT_TYPE));
assertTrue(optUnion.contains(REGEXP_TYPE));
}
public void testUnionWithUnknown() throws Exception {
assertTrue(createUnionType(UNKNOWN_TYPE, NULL_TYPE).isUnknownType());
}
public void testGetRestrictedUnion1() throws Exception {
UnionType numStr = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE);
assertEquals(STRING_TYPE, numStr.getRestrictedUnion(NUMBER_TYPE));
}
public void testGetRestrictedUnion2() throws Exception {
UnionType numStr = (UnionType) createUnionType(
NULL_TYPE, EVAL_ERROR_TYPE, URI_ERROR_TYPE);
assertEquals(NULL_TYPE, numStr.getRestrictedUnion(ERROR_TYPE));
}
} |
|
public void testMixinWithBundles() throws Exception
{
ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
String result = mapper.writeValueAsString(new Foo("result"));
assertEquals("{\"bar\":\"result\"}", result);
} | com.fasterxml.jackson.databind.mixins.MixinsWithBundlesTest::testMixinWithBundles | src/test/java/com/fasterxml/jackson/databind/mixins/MixinsWithBundlesTest.java | 41 | src/test/java/com/fasterxml/jackson/databind/mixins/MixinsWithBundlesTest.java | testMixinWithBundles | package com.fasterxml.jackson.databind.mixins;
import java.lang.annotation.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
// for [databind#771]
public class MixinsWithBundlesTest extends BaseMapTest
{
@Target(value={ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD })
@Retention(value=RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonProperty("bar")
public @interface ExposeStuff {
}
public abstract class FooMixin {
@ExposeStuff
public abstract String getStuff();
}
public static class Foo {
private String stuff;
Foo(String stuff) {
this.stuff = stuff;
}
public String getStuff() {
return stuff;
}
}
public void testMixinWithBundles() throws Exception
{
ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
String result = mapper.writeValueAsString(new Foo("result"));
assertEquals("{\"bar\":\"result\"}", result);
}
} | // You are a professional Java test case writer, please create a test case named `testMixinWithBundles` for the issue `JacksonDatabind-771`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-771
//
// ## Issue-Title:
// Annotation bundles ignored when added to Mixin
//
// ## Issue-Description:
// When updating from v 2.4.4 to 2.5.\* it appears as though annotation bundles created with `@JacksonAnnotationsInside` are ignored when placed on a mixin. Moving the annotation bundel to the actual class seems to resolve the issue. Below is a simple test that attempts to rename a property. I have more complicated test cases that are also failing but this should provide some context.
//
//
//
// ```
// public class Fun {
//
// @Test
// public void test() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
// String result = mapper.writeValueAsString(new Foo("result"));
// Assert.assertEquals("{\"bar\":\"result\"}", result);
// }
//
// @Target(value={ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD })
// @Retention(value=RetentionPolicy.RUNTIME)
// @JacksonAnnotationsInside
// @JsonProperty("bar")
// public @interface ExposeStuff {
//
// }
//
// public abstract class FooMixin {
// @ExposeStuff
// public abstract String getStuff();
// }
//
// public class Foo {
//
// private String stuff;
//
// Foo(String stuff) {
// this.stuff = stuff;
// }
//
// public String getStuff() {
// return stuff;
// }
// }
// }
// ```
//
// I'm expecting the "stuff" property to be serialized as "bar".
//
//
// I apologize I haven't been able to identify the culprit (and perhaps it's in my usage). Let me know your thoughts. I'm always happy to provide more details!
//
//
//
//
public void testMixinWithBundles() throws Exception {
| 41 | 16 | 36 | src/test/java/com/fasterxml/jackson/databind/mixins/MixinsWithBundlesTest.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-771
## Issue-Title:
Annotation bundles ignored when added to Mixin
## Issue-Description:
When updating from v 2.4.4 to 2.5.\* it appears as though annotation bundles created with `@JacksonAnnotationsInside` are ignored when placed on a mixin. Moving the annotation bundel to the actual class seems to resolve the issue. Below is a simple test that attempts to rename a property. I have more complicated test cases that are also failing but this should provide some context.
```
public class Fun {
@Test
public void test() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
String result = mapper.writeValueAsString(new Foo("result"));
Assert.assertEquals("{\"bar\":\"result\"}", result);
}
@Target(value={ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD })
@Retention(value=RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonProperty("bar")
public @interface ExposeStuff {
}
public abstract class FooMixin {
@ExposeStuff
public abstract String getStuff();
}
public class Foo {
private String stuff;
Foo(String stuff) {
this.stuff = stuff;
}
public String getStuff() {
return stuff;
}
}
}
```
I'm expecting the "stuff" property to be serialized as "bar".
I apologize I haven't been able to identify the culprit (and perhaps it's in my usage). Let me know your thoughts. I'm always happy to provide more details!
```
You are a professional Java test case writer, please create a test case named `testMixinWithBundles` for the issue `JacksonDatabind-771`, utilizing the provided issue report information and the following function signature.
```java
public void testMixinWithBundles() throws Exception {
```
| 36 | [
"com.fasterxml.jackson.databind.introspect.AnnotationMap"
] | 45da089301a1db4083f911024603972844144d0c080961566f4434ffc70ac269 | public void testMixinWithBundles() throws Exception
| // You are a professional Java test case writer, please create a test case named `testMixinWithBundles` for the issue `JacksonDatabind-771`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-771
//
// ## Issue-Title:
// Annotation bundles ignored when added to Mixin
//
// ## Issue-Description:
// When updating from v 2.4.4 to 2.5.\* it appears as though annotation bundles created with `@JacksonAnnotationsInside` are ignored when placed on a mixin. Moving the annotation bundel to the actual class seems to resolve the issue. Below is a simple test that attempts to rename a property. I have more complicated test cases that are also failing but this should provide some context.
//
//
//
// ```
// public class Fun {
//
// @Test
// public void test() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
// String result = mapper.writeValueAsString(new Foo("result"));
// Assert.assertEquals("{\"bar\":\"result\"}", result);
// }
//
// @Target(value={ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD })
// @Retention(value=RetentionPolicy.RUNTIME)
// @JacksonAnnotationsInside
// @JsonProperty("bar")
// public @interface ExposeStuff {
//
// }
//
// public abstract class FooMixin {
// @ExposeStuff
// public abstract String getStuff();
// }
//
// public class Foo {
//
// private String stuff;
//
// Foo(String stuff) {
// this.stuff = stuff;
// }
//
// public String getStuff() {
// return stuff;
// }
// }
// }
// ```
//
// I'm expecting the "stuff" property to be serialized as "bar".
//
//
// I apologize I haven't been able to identify the culprit (and perhaps it's in my usage). Let me know your thoughts. I'm always happy to provide more details!
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.mixins;
import java.lang.annotation.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
// for [databind#771]
public class MixinsWithBundlesTest extends BaseMapTest
{
@Target(value={ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD })
@Retention(value=RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonProperty("bar")
public @interface ExposeStuff {
}
public abstract class FooMixin {
@ExposeStuff
public abstract String getStuff();
}
public static class Foo {
private String stuff;
Foo(String stuff) {
this.stuff = stuff;
}
public String getStuff() {
return stuff;
}
}
public void testMixinWithBundles() throws Exception
{
ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixin.class);
String result = mapper.writeValueAsString(new Foo("result"));
assertEquals("{\"bar\":\"result\"}", result);
}
} |
||
@Test public void handlesCustomProtocols() {
String html = "<img src='cid:12345' /> <img src='data:gzzt' />";
String dropped = Jsoup.clean(html, Whitelist.basicWithImages());
assertEquals("<img /> \n<img />", dropped);
String preserved = Jsoup.clean(html, Whitelist.basicWithImages().addProtocols("img", "src", "cid", "data"));
assertEquals("<img src=\"cid:12345\" /> \n<img src=\"data:gzzt\" />", preserved);
} | org.jsoup.safety.CleanerTest::handlesCustomProtocols | src/test/java/org/jsoup/safety/CleanerTest.java | 123 | src/test/java/org/jsoup/safety/CleanerTest.java | handlesCustomProtocols | package org.jsoup.safety;
import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.jsoup.safety.Whitelist;
import org.junit.Test;
import static org.junit.Assert.*;
/**
Tests for the cleaner.
@author Jonathan Hedley, jonathan@hedley.net */
public class CleanerTest {
@Test public void simpleBehaviourTest() {
String h = "<div><p class=foo><a href='http://evil.com'>Hello <b id=bar>there</b>!</a></div>";
String cleanHtml = Jsoup.clean(h, Whitelist.simpleText());
assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml));
}
@Test public void simpleBehaviourTest2() {
String h = "Hello <b>there</b>!";
String cleanHtml = Jsoup.clean(h, Whitelist.simpleText());
assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml));
}
@Test public void basicBehaviourTest() {
String h = "<div><p><a href='javascript:sendAllMoney()'>Dodgy</a> <A HREF='HTTP://nice.com'>Nice</a></p><blockquote>Hello</blockquote>";
String cleanHtml = Jsoup.clean(h, Whitelist.basic());
assertEquals("<p><a rel=\"nofollow\">Dodgy</a> <a href=\"http://nice.com\" rel=\"nofollow\">Nice</a></p><blockquote>Hello</blockquote>",
TextUtil.stripNewlines(cleanHtml));
}
@Test public void basicWithImagesTest() {
String h = "<div><p><img src='http://example.com/' alt=Image></p><p><img src='ftp://ftp.example.com'></p></div>";
String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages());
assertEquals("<p><img src=\"http://example.com/\" alt=\"Image\" /></p><p><img /></p>", TextUtil.stripNewlines(cleanHtml));
}
@Test public void testRelaxed() {
String h = "<h1>Head</h1><table><tr><td>One<td>Two</td></tr></table>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<h1>Head</h1><table><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(cleanHtml));
}
@Test public void testDropComments() {
String h = "<p>Hello<!-- no --></p>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<p>Hello</p>", cleanHtml);
}
@Test public void testDropXmlProc() {
String h = "<?import namespace=\"xss\"><p>Hello</p>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<p>Hello</p>", cleanHtml);
}
@Test public void testDropScript() {
String h = "<SCRIPT SRC=//ha.ckers.org/.j><SCRIPT>alert(/XSS/.source)</SCRIPT>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("", cleanHtml);
}
@Test public void testDropImageScript() {
String h = "<IMG SRC=\"javascript:alert('XSS')\">";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<img />", cleanHtml);
}
@Test public void testCleanJavascriptHref() {
String h = "<A HREF=\"javascript:document.location='http://www.google.com/'\">XSS</A>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<a>XSS</a>", cleanHtml);
}
@Test public void testDropsUnknownTags() {
String h = "<p><custom foo=true>Test</custom></p>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<p>Test</p>", cleanHtml);
}
@Test public void testHandlesEmptyAttributes() {
String h = "<img alt=\"\" src= unknown=''>";
String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages());
assertEquals("<img alt=\"\" />", cleanHtml);
}
@Test public void testIsValid() {
String ok = "<p>Test <b><a href='http://example.com/'>OK</a></b></p>";
String nok1 = "<p><script></script>Not <b>OK</b></p>";
String nok2 = "<p align=right>Test Not <b>OK</b></p>";
assertTrue(Jsoup.isValid(ok, Whitelist.basic()));
assertFalse(Jsoup.isValid(nok1, Whitelist.basic()));
assertFalse(Jsoup.isValid(nok2, Whitelist.basic()));
}
@Test public void resolvesRelativeLinks() {
String html = "<a href='/foo'>Link</a><img src='/bar'>";
String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages());
assertEquals("<a href=\"http://example.com/foo\" rel=\"nofollow\">Link</a>\n<img src=\"http://example.com/bar\" />", clean);
}
@Test public void preservesRelatedLinksIfConfigured() {
String html = "<a href='/foo'>Link</a><img src='/bar'> <img src='javascript:alert()'>";
String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages().preserveRelativeLinks(true));
assertEquals("<a href=\"/foo\" rel=\"nofollow\">Link</a>\n<img src=\"/bar\" /> \n<img />", clean);
}
@Test public void dropsUnresolvableRelativeLinks() {
String html = "<a href='/foo'>Link</a>";
String clean = Jsoup.clean(html, Whitelist.basic());
assertEquals("<a rel=\"nofollow\">Link</a>", clean);
}
@Test public void handlesCustomProtocols() {
String html = "<img src='cid:12345' /> <img src='data:gzzt' />";
String dropped = Jsoup.clean(html, Whitelist.basicWithImages());
assertEquals("<img /> \n<img />", dropped);
String preserved = Jsoup.clean(html, Whitelist.basicWithImages().addProtocols("img", "src", "cid", "data"));
assertEquals("<img src=\"cid:12345\" /> \n<img src=\"data:gzzt\" />", preserved);
}
} | // You are a professional Java test case writer, please create a test case named `handlesCustomProtocols` for the issue `Jsoup-127`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-127
//
// ## Issue-Title:
// Cleaning html containing the cid identifier breaks images
//
// ## Issue-Description:
// Ok, so in mail type HTML the following is common
//
//
// ![]()
//
//
// The item after CID: can be almost anything (US-ASCII I think) and of any length. It corresponds to an image linked elsewhere in MIME say like this
//
//
// --mimebounday
//
// Content-ID:
//
// Content-Type: image/jpeg.....
//
// (snip)
//
//
// So, to mark a long story somewhat shorter, I use Jsoup's sanitizer extensively. However, I need these CID references to be preserved post sanitization. addProtocols does not work because the items are not valid URLs. As a result
//
// the above becomes ![](). Which for my purposes is not good :)
//
//
//
//
@Test public void handlesCustomProtocols() {
| 123 | 19 | 116 | src/test/java/org/jsoup/safety/CleanerTest.java | src/test/java | ```markdown
## Issue-ID: Jsoup-127
## Issue-Title:
Cleaning html containing the cid identifier breaks images
## Issue-Description:
Ok, so in mail type HTML the following is common
![]()
The item after CID: can be almost anything (US-ASCII I think) and of any length. It corresponds to an image linked elsewhere in MIME say like this
--mimebounday
Content-ID:
Content-Type: image/jpeg.....
(snip)
So, to mark a long story somewhat shorter, I use Jsoup's sanitizer extensively. However, I need these CID references to be preserved post sanitization. addProtocols does not work because the items are not valid URLs. As a result
the above becomes ![](). Which for my purposes is not good :)
```
You are a professional Java test case writer, please create a test case named `handlesCustomProtocols` for the issue `Jsoup-127`, utilizing the provided issue report information and the following function signature.
```java
@Test public void handlesCustomProtocols() {
```
| 116 | [
"org.jsoup.safety.Whitelist"
] | 46181ac5fd3f15da4dcc1a7fa7d2c5f9556f81f414f54d072fbcd03f5bb72c10 | @Test public void handlesCustomProtocols() | // You are a professional Java test case writer, please create a test case named `handlesCustomProtocols` for the issue `Jsoup-127`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-127
//
// ## Issue-Title:
// Cleaning html containing the cid identifier breaks images
//
// ## Issue-Description:
// Ok, so in mail type HTML the following is common
//
//
// ![]()
//
//
// The item after CID: can be almost anything (US-ASCII I think) and of any length. It corresponds to an image linked elsewhere in MIME say like this
//
//
// --mimebounday
//
// Content-ID:
//
// Content-Type: image/jpeg.....
//
// (snip)
//
//
// So, to mark a long story somewhat shorter, I use Jsoup's sanitizer extensively. However, I need these CID references to be preserved post sanitization. addProtocols does not work because the items are not valid URLs. As a result
//
// the above becomes ![](). Which for my purposes is not good :)
//
//
//
//
| Jsoup | package org.jsoup.safety;
import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.jsoup.safety.Whitelist;
import org.junit.Test;
import static org.junit.Assert.*;
/**
Tests for the cleaner.
@author Jonathan Hedley, jonathan@hedley.net */
public class CleanerTest {
@Test public void simpleBehaviourTest() {
String h = "<div><p class=foo><a href='http://evil.com'>Hello <b id=bar>there</b>!</a></div>";
String cleanHtml = Jsoup.clean(h, Whitelist.simpleText());
assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml));
}
@Test public void simpleBehaviourTest2() {
String h = "Hello <b>there</b>!";
String cleanHtml = Jsoup.clean(h, Whitelist.simpleText());
assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml));
}
@Test public void basicBehaviourTest() {
String h = "<div><p><a href='javascript:sendAllMoney()'>Dodgy</a> <A HREF='HTTP://nice.com'>Nice</a></p><blockquote>Hello</blockquote>";
String cleanHtml = Jsoup.clean(h, Whitelist.basic());
assertEquals("<p><a rel=\"nofollow\">Dodgy</a> <a href=\"http://nice.com\" rel=\"nofollow\">Nice</a></p><blockquote>Hello</blockquote>",
TextUtil.stripNewlines(cleanHtml));
}
@Test public void basicWithImagesTest() {
String h = "<div><p><img src='http://example.com/' alt=Image></p><p><img src='ftp://ftp.example.com'></p></div>";
String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages());
assertEquals("<p><img src=\"http://example.com/\" alt=\"Image\" /></p><p><img /></p>", TextUtil.stripNewlines(cleanHtml));
}
@Test public void testRelaxed() {
String h = "<h1>Head</h1><table><tr><td>One<td>Two</td></tr></table>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<h1>Head</h1><table><tbody><tr><td>One</td><td>Two</td></tr></tbody></table>", TextUtil.stripNewlines(cleanHtml));
}
@Test public void testDropComments() {
String h = "<p>Hello<!-- no --></p>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<p>Hello</p>", cleanHtml);
}
@Test public void testDropXmlProc() {
String h = "<?import namespace=\"xss\"><p>Hello</p>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<p>Hello</p>", cleanHtml);
}
@Test public void testDropScript() {
String h = "<SCRIPT SRC=//ha.ckers.org/.j><SCRIPT>alert(/XSS/.source)</SCRIPT>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("", cleanHtml);
}
@Test public void testDropImageScript() {
String h = "<IMG SRC=\"javascript:alert('XSS')\">";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<img />", cleanHtml);
}
@Test public void testCleanJavascriptHref() {
String h = "<A HREF=\"javascript:document.location='http://www.google.com/'\">XSS</A>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<a>XSS</a>", cleanHtml);
}
@Test public void testDropsUnknownTags() {
String h = "<p><custom foo=true>Test</custom></p>";
String cleanHtml = Jsoup.clean(h, Whitelist.relaxed());
assertEquals("<p>Test</p>", cleanHtml);
}
@Test public void testHandlesEmptyAttributes() {
String h = "<img alt=\"\" src= unknown=''>";
String cleanHtml = Jsoup.clean(h, Whitelist.basicWithImages());
assertEquals("<img alt=\"\" />", cleanHtml);
}
@Test public void testIsValid() {
String ok = "<p>Test <b><a href='http://example.com/'>OK</a></b></p>";
String nok1 = "<p><script></script>Not <b>OK</b></p>";
String nok2 = "<p align=right>Test Not <b>OK</b></p>";
assertTrue(Jsoup.isValid(ok, Whitelist.basic()));
assertFalse(Jsoup.isValid(nok1, Whitelist.basic()));
assertFalse(Jsoup.isValid(nok2, Whitelist.basic()));
}
@Test public void resolvesRelativeLinks() {
String html = "<a href='/foo'>Link</a><img src='/bar'>";
String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages());
assertEquals("<a href=\"http://example.com/foo\" rel=\"nofollow\">Link</a>\n<img src=\"http://example.com/bar\" />", clean);
}
@Test public void preservesRelatedLinksIfConfigured() {
String html = "<a href='/foo'>Link</a><img src='/bar'> <img src='javascript:alert()'>";
String clean = Jsoup.clean(html, "http://example.com/", Whitelist.basicWithImages().preserveRelativeLinks(true));
assertEquals("<a href=\"/foo\" rel=\"nofollow\">Link</a>\n<img src=\"/bar\" /> \n<img />", clean);
}
@Test public void dropsUnresolvableRelativeLinks() {
String html = "<a href='/foo'>Link</a>";
String clean = Jsoup.clean(html, Whitelist.basic());
assertEquals("<a rel=\"nofollow\">Link</a>", clean);
}
@Test public void handlesCustomProtocols() {
String html = "<img src='cid:12345' /> <img src='data:gzzt' />";
String dropped = Jsoup.clean(html, Whitelist.basicWithImages());
assertEquals("<img /> \n<img />", dropped);
String preserved = Jsoup.clean(html, Whitelist.basicWithImages().addProtocols("img", "src", "cid", "data"));
assertEquals("<img src=\"cid:12345\" /> \n<img src=\"data:gzzt\" />", preserved);
}
} |
||
public void testJDKTypes1872() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
String json = aposToQuotes(String.format("{'@class':'%s','authorities':['java.util.ArrayList',[]]}",
Authentication1872.class.getName()));
Authentication1872 result = mapper.readValue(json, Authentication1872.class);
assertNotNull(result);
} | com.fasterxml.jackson.databind.interop.IllegalTypesCheckTest::testJDKTypes1872 | src/test/java/com/fasterxml/jackson/databind/interop/IllegalTypesCheckTest.java | 113 | src/test/java/com/fasterxml/jackson/databind/interop/IllegalTypesCheckTest.java | testJDKTypes1872 | package com.fasterxml.jackson.databind.interop;
import java.util.*;
import org.springframework.jacksontest.BogusApplicationContext;
import org.springframework.jacksontest.BogusPointcutAdvisor;
import org.springframework.jacksontest.GrantedAuthority;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.*;
/**
* Test case(s) to guard against handling of types that are illegal to handle
* due to security constraints.
*/
public class IllegalTypesCheckTest extends BaseMapTest
{
static class Bean1599 {
public int id;
public Object obj;
}
static class PolyWrapper {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.WRAPPER_ARRAY)
public Object v;
}
static class Authentication1872 {
public List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
// // // Tests for [databind#1599]
public void testXalanTypes1599() throws Exception
{
final String clsName = "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl";
final String JSON = aposToQuotes(
"{'id': 124,\n"
+" 'obj':[ '"+clsName+"',\n"
+" {\n"
+" 'transletBytecodes' : [ 'AAIAZQ==' ],\n"
+" 'transletName' : 'a.b',\n"
+" 'outputProperties' : { }\n"
+" }\n"
+" ]\n"
+"}"
);
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
try {
mapper.readValue(JSON, Bean1599.class);
fail("Should not pass");
} catch (JsonMappingException e) {
_verifySecurityException(e, clsName);
}
}
// // // Tests for [databind#1737]
public void testJDKTypes1737() throws Exception
{
_testIllegalType(java.util.logging.FileHandler.class);
_testIllegalType(java.rmi.server.UnicastRemoteObject.class);
}
// // // Tests for [databind#1855]
public void testJDKTypes1855() throws Exception
{
// apparently included by JDK?
_testIllegalType("com.sun.org.apache.bcel.internal.util.ClassLoader");
// also: we can try some form of testing, even if bit contrived...
_testIllegalType(BogusPointcutAdvisor.class);
_testIllegalType(BogusApplicationContext.class);
}
// 17-Aug-2017, tatu: Ideally would test handling of 3rd party types, too,
// but would require adding dependencies. This may be practical when
// checking done by module, but for now let's not do that for databind.
/*
public void testSpringTypes1737() throws Exception
{
_testIllegalType("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor");
_testIllegalType("org.springframework.beans.factory.config.PropertyPathFactoryBean");
}
public void testC3P0Types1737() throws Exception
{
_testTypes1737("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
_testTypes1737("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
}
*/
// // // Tests for [databind#1872]
public void testJDKTypes1872() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
String json = aposToQuotes(String.format("{'@class':'%s','authorities':['java.util.ArrayList',[]]}",
Authentication1872.class.getName()));
Authentication1872 result = mapper.readValue(json, Authentication1872.class);
assertNotNull(result);
}
private void _testIllegalType(Class<?> nasty) throws Exception {
_testIllegalType(nasty.getName());
}
private void _testIllegalType(String clsName) throws Exception
{
// While usually exploited via default typing let's not require
// it here; mechanism still the same
String json = aposToQuotes(
"{'v':['"+clsName+"','/tmp/foobar.txt']}"
);
try {
MAPPER.readValue(json, PolyWrapper.class);
fail("Should not pass");
} catch (JsonMappingException e) {
_verifySecurityException(e, clsName);
}
}
protected void _verifySecurityException(Throwable t, String clsName) throws Exception
{
// 17-Aug-2017, tatu: Expected type more granular in 2.9 (over 2.8)
_verifyException(t, JsonMappingException.class,
"Illegal type",
"to deserialize",
"prevented for security reasons");
verifyException(t, clsName);
}
protected void _verifyException(Throwable t, Class<?> expExcType,
String... patterns) throws Exception
{
Class<?> actExc = t.getClass();
if (!expExcType.isAssignableFrom(actExc)) {
fail("Expected Exception of type '"+expExcType.getName()+"', got '"
+actExc.getName()+"', message: "+t.getMessage());
}
for (String pattern : patterns) {
verifyException(t, pattern);
}
}
} | // You are a professional Java test case writer, please create a test case named `testJDKTypes1872` for the issue `JacksonDatabind-1872`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1872
//
// ## Issue-Title:
// NullPointerException in SubTypeValidator.validateSubType when validating Spring interface
//
// ## Issue-Description:
// In jackson-databind-2.8.11 jackson-databind-2.9.3 and jackson-databind-2.9.4-SNAPSHOT `SubTypeValidator.validateSubType` fails with a `NullPointerException` if the `JavaType.getRawClass()` is an interface that starts with `org.springframework.` For example, the following will fail:
//
//
//
// ```
// package org.springframework.security.core;
//
// import java.util.*;
//
// public class Authentication {
// private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
//
// public List<GrantedAuthority> getAuthorities() {
// return this.authorities;
// }
//
// public void setAuthorities(List<GrantedAuthority> authorities) {
// this.authorities = authorities;
// }
// }
// ```
//
//
// ```
// package org.springframework.security.core;
//
// public interface GrantedAuthority {
// String getAuthority();
// }
// ```
//
//
// ```
// @Test
// public void validateSubTypeFailsWithNPE() throws Exception {
// ObjectMapper mapper = new ObjectMapper();
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL, JsonTypeInfo.As.PROPERTY);
//
// String json = "{\"@class\":\"org.springframework.security.core.Authentication\",\"authorities\":[\"java.util.ArrayList\",[]]}";
//
// Authentication authentication = mapper.readValue(json, Authentication.class);
// }
// ```
//
// with the following stacktrace:
//
//
//
// ```
// java.lang.NullPointerException
// at com.fasterxml.jackson.databind.jsontype.impl.SubTypeValidator.validateSubType(SubTypeValidator.java:86)
// at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory._validateSubType(BeanDeserializerFactory.java:916)
// at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:135)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:411)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
// at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
// at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:444)
// at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:183)
// at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:27)
// at com.fasterxml.jackson.databind.DeserializationContext.handlePrimaryContextualization(DeserializationContext.java:651)
// at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:471)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._
public void testJDKTypes1872() throws Exception {
| 113 | // // // Tests for [databind#1872]
/*
public void testSpringTypes1737() throws Exception
{
_testIllegalType("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor");
_testIllegalType("org.springframework.beans.factory.config.PropertyPathFactoryBean");
}
public void testC3P0Types1737() throws Exception
{
_testTypes1737("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
_testTypes1737("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
}
*/
// checking done by module, but for now let's not do that for databind.
// but would require adding dependencies. This may be practical when
// 17-Aug-2017, tatu: Ideally would test handling of 3rd party types, too, | 93 | 104 | src/test/java/com/fasterxml/jackson/databind/interop/IllegalTypesCheckTest.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1872
## Issue-Title:
NullPointerException in SubTypeValidator.validateSubType when validating Spring interface
## Issue-Description:
In jackson-databind-2.8.11 jackson-databind-2.9.3 and jackson-databind-2.9.4-SNAPSHOT `SubTypeValidator.validateSubType` fails with a `NullPointerException` if the `JavaType.getRawClass()` is an interface that starts with `org.springframework.` For example, the following will fail:
```
package org.springframework.security.core;
import java.util.*;
public class Authentication {
private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
public List<GrantedAuthority> getAuthorities() {
return this.authorities;
}
public void setAuthorities(List<GrantedAuthority> authorities) {
this.authorities = authorities;
}
}
```
```
package org.springframework.security.core;
public interface GrantedAuthority {
String getAuthority();
}
```
```
@Test
public void validateSubTypeFailsWithNPE() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL, JsonTypeInfo.As.PROPERTY);
String json = "{\"@class\":\"org.springframework.security.core.Authentication\",\"authorities\":[\"java.util.ArrayList\",[]]}";
Authentication authentication = mapper.readValue(json, Authentication.class);
}
```
with the following stacktrace:
```
java.lang.NullPointerException
at com.fasterxml.jackson.databind.jsontype.impl.SubTypeValidator.validateSubType(SubTypeValidator.java:86)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory._validateSubType(BeanDeserializerFactory.java:916)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:135)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:411)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:444)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:183)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:27)
at com.fasterxml.jackson.databind.DeserializationContext.handlePrimaryContextualization(DeserializationContext.java:651)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:471)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
at com.fasterxml.jackson.databind.deser.DeserializerCache._
```
You are a professional Java test case writer, please create a test case named `testJDKTypes1872` for the issue `JacksonDatabind-1872`, utilizing the provided issue report information and the following function signature.
```java
public void testJDKTypes1872() throws Exception {
```
| 104 | [
"com.fasterxml.jackson.databind.jsontype.impl.SubTypeValidator"
] | 4680af3198a9a99c9cad6a360c773245a5d35c3bfb42be4bd34b25cde61e5a8e | public void testJDKTypes1872() throws Exception
| // You are a professional Java test case writer, please create a test case named `testJDKTypes1872` for the issue `JacksonDatabind-1872`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1872
//
// ## Issue-Title:
// NullPointerException in SubTypeValidator.validateSubType when validating Spring interface
//
// ## Issue-Description:
// In jackson-databind-2.8.11 jackson-databind-2.9.3 and jackson-databind-2.9.4-SNAPSHOT `SubTypeValidator.validateSubType` fails with a `NullPointerException` if the `JavaType.getRawClass()` is an interface that starts with `org.springframework.` For example, the following will fail:
//
//
//
// ```
// package org.springframework.security.core;
//
// import java.util.*;
//
// public class Authentication {
// private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
//
// public List<GrantedAuthority> getAuthorities() {
// return this.authorities;
// }
//
// public void setAuthorities(List<GrantedAuthority> authorities) {
// this.authorities = authorities;
// }
// }
// ```
//
//
// ```
// package org.springframework.security.core;
//
// public interface GrantedAuthority {
// String getAuthority();
// }
// ```
//
//
// ```
// @Test
// public void validateSubTypeFailsWithNPE() throws Exception {
// ObjectMapper mapper = new ObjectMapper();
// mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON\_FINAL, JsonTypeInfo.As.PROPERTY);
//
// String json = "{\"@class\":\"org.springframework.security.core.Authentication\",\"authorities\":[\"java.util.ArrayList\",[]]}";
//
// Authentication authentication = mapper.readValue(json, Authentication.class);
// }
// ```
//
// with the following stacktrace:
//
//
//
// ```
// java.lang.NullPointerException
// at com.fasterxml.jackson.databind.jsontype.impl.SubTypeValidator.validateSubType(SubTypeValidator.java:86)
// at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory._validateSubType(BeanDeserializerFactory.java:916)
// at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:135)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:411)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
// at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
// at com.fasterxml.jackson.databind.DeserializationContext.findContextualValueDeserializer(DeserializationContext.java:444)
// at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:183)
// at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.createContextual(CollectionDeserializer.java:27)
// at com.fasterxml.jackson.databind.DeserializationContext.handlePrimaryContextualization(DeserializationContext.java:651)
// at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:471)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
// at com.fasterxml.jackson.databind.deser.DeserializerCache._
| JacksonDatabind | package com.fasterxml.jackson.databind.interop;
import java.util.*;
import org.springframework.jacksontest.BogusApplicationContext;
import org.springframework.jacksontest.BogusPointcutAdvisor;
import org.springframework.jacksontest.GrantedAuthority;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.*;
/**
* Test case(s) to guard against handling of types that are illegal to handle
* due to security constraints.
*/
public class IllegalTypesCheckTest extends BaseMapTest
{
static class Bean1599 {
public int id;
public Object obj;
}
static class PolyWrapper {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.WRAPPER_ARRAY)
public Object v;
}
static class Authentication1872 {
public List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
// // // Tests for [databind#1599]
public void testXalanTypes1599() throws Exception
{
final String clsName = "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl";
final String JSON = aposToQuotes(
"{'id': 124,\n"
+" 'obj':[ '"+clsName+"',\n"
+" {\n"
+" 'transletBytecodes' : [ 'AAIAZQ==' ],\n"
+" 'transletName' : 'a.b',\n"
+" 'outputProperties' : { }\n"
+" }\n"
+" ]\n"
+"}"
);
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
try {
mapper.readValue(JSON, Bean1599.class);
fail("Should not pass");
} catch (JsonMappingException e) {
_verifySecurityException(e, clsName);
}
}
// // // Tests for [databind#1737]
public void testJDKTypes1737() throws Exception
{
_testIllegalType(java.util.logging.FileHandler.class);
_testIllegalType(java.rmi.server.UnicastRemoteObject.class);
}
// // // Tests for [databind#1855]
public void testJDKTypes1855() throws Exception
{
// apparently included by JDK?
_testIllegalType("com.sun.org.apache.bcel.internal.util.ClassLoader");
// also: we can try some form of testing, even if bit contrived...
_testIllegalType(BogusPointcutAdvisor.class);
_testIllegalType(BogusApplicationContext.class);
}
// 17-Aug-2017, tatu: Ideally would test handling of 3rd party types, too,
// but would require adding dependencies. This may be practical when
// checking done by module, but for now let's not do that for databind.
/*
public void testSpringTypes1737() throws Exception
{
_testIllegalType("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor");
_testIllegalType("org.springframework.beans.factory.config.PropertyPathFactoryBean");
}
public void testC3P0Types1737() throws Exception
{
_testTypes1737("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
_testTypes1737("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
}
*/
// // // Tests for [databind#1872]
public void testJDKTypes1872() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
String json = aposToQuotes(String.format("{'@class':'%s','authorities':['java.util.ArrayList',[]]}",
Authentication1872.class.getName()));
Authentication1872 result = mapper.readValue(json, Authentication1872.class);
assertNotNull(result);
}
private void _testIllegalType(Class<?> nasty) throws Exception {
_testIllegalType(nasty.getName());
}
private void _testIllegalType(String clsName) throws Exception
{
// While usually exploited via default typing let's not require
// it here; mechanism still the same
String json = aposToQuotes(
"{'v':['"+clsName+"','/tmp/foobar.txt']}"
);
try {
MAPPER.readValue(json, PolyWrapper.class);
fail("Should not pass");
} catch (JsonMappingException e) {
_verifySecurityException(e, clsName);
}
}
protected void _verifySecurityException(Throwable t, String clsName) throws Exception
{
// 17-Aug-2017, tatu: Expected type more granular in 2.9 (over 2.8)
_verifyException(t, JsonMappingException.class,
"Illegal type",
"to deserialize",
"prevented for security reasons");
verifyException(t, clsName);
}
protected void _verifyException(Throwable t, Class<?> expExcType,
String... patterns) throws Exception
{
Class<?> actExc = t.getClass();
if (!expExcType.isAssignableFrom(actExc)) {
fail("Expected Exception of type '"+expExcType.getName()+"', got '"
+actExc.getName()+"', message: "+t.getMessage());
}
for (String pattern : patterns) {
verifyException(t, pattern);
}
}
} |
|
@Test
public void testHeader() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(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());
printer.close();
} | org.apache.commons.csv.CSVPrinterTest::testHeader | src/test/java/org/apache/commons/csv/CSVPrinterTest.java | 496 | src/test/java/org/apache/commons/csv/CSVPrinterTest.java | testHeader | /*
* 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.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.junit.Test;
/**
*
*
* @version $Id$
*/
public class CSVPrinterTest {
private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator();
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 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 = 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();
}
}
final StringWriter sw = new StringWriter();
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();
printer.close();
final String result = sw.toString();
// System.out.println("### :" + printable(result));
final CSVParser parser = CSVParser.parse(result, format);
final List<CSVRecord> parseResult = parser.getRecords();
Utils.compare("Printer output :" + printable(result), lines, parseResult);
parser.close();
}
private void doRandom(final CSVFormat format, final int iter) throws Exception {
for (int i = 0; i < iter; i++) {
doOneRandom(format);
}
}
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 = '"';
break;
case 7:
ch = '\'';
break;
case 8:
ch = '\\';
break;
default:
ch = (char) r.nextInt(300);
break;
// default: ch = 'a'; break;
}
buf[i] = ch;
}
return new String(buf);
}
@Test
public void testDisabledComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printComment("This is a comment");
assertEquals("", sw.toString());
printer.close();
}
@Test
public void testExcelPrintAllArrayOfArrays() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } });
assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testExcelPrintAllArrayOfLists() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecords(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") });
assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testExcelPrintAllIterableOfArrays() throws IOException {
final StringWriter sw = new StringWriter();
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());
printer.close();
}
@Test
public void testExcelPrintAllIterableOfLists() throws IOException {
final StringWriter sw = new StringWriter();
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());
printer.close();
}
@Test
public void testExcelPrinter1() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecord("a", "b");
assertEquals("a,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testExcelPrinter2() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecord("a,b", "b");
assertEquals("\"a,b\",b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException {
final StringWriter sw = new StringWriter();
Class.forName("org.h2.Driver");
final Connection connection = DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", "");
try {
final Statement stmt = connection.createStatement();
stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
stmt.execute("insert into TEST values(1, 'r1')");
stmt.execute("insert into TEST values(2, 'r2')");
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());
printer.close();
} finally {
connection.close();
}
}
@Test
public void testMultiLineComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentStart('#'));
printer.printComment("This is a comment\non multiple lines");
assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter1() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b");
assertEquals("a,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter2() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a,b", "b");
assertEquals("\"a,b\",b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter3() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a, b", "b ");
assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter4() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\"c");
assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter5() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\nc");
assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter6() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\r\nc");
assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter7() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\\c");
assertEquals("a,b\\c" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrint() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = CSVFormat.DEFAULT.print(sw);
printer.printRecord("a", "b\\c");
assertEquals("a,b\\c" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrintNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", null, "b");
assertEquals("a,,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrintCustomNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"));
printer.printRecord("a", null, "b");
assertEquals("a,NULL,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testParseCustomNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL");
final CSVPrinter printer = new CSVPrinter(sw, format);
printer.printRecord("a", null, "b");
printer.close();
final String csvString = sw.toString();
assertEquals("a,NULL,b" + recordSeparator, csvString);
final Iterable<CSVRecord> 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());
((CSVParser) iterable).close();
}
@Test
public void testQuoteAll() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuotePolicy(Quote.ALL));
printer.printRecord("a", "b\nc", "d");
assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testQuoteNonNumeric() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuotePolicy(Quote.NON_NUMERIC));
printer.printRecord("a", "b\nc", Integer.valueOf(1));
assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testRandom() throws Exception {
final int iter = 10000;
doRandom(CSVFormat.DEFAULT, iter);
doRandom(CSVFormat.EXCEL, iter);
doRandom(CSVFormat.MYSQL, iter);
}
@Test
public void testPlainQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("abc");
assertEquals("abc", sw.toString());
printer.close();
}
@Test
public void testSingleLineComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentStart('#'));
printer.printComment("This is a comment");
assertEquals("# This is a comment" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testSingleQuoteQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("a'b'c");
printer.print("xyz");
assertEquals("'a''b''c',xyz", sw.toString());
printer.close();
}
@Test
public void testDelimeterQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("a,b,c");
printer.print("xyz");
assertEquals("'a,b,c',xyz", sw.toString());
printer.close();
}
@Test
public void testDelimeterQuoteNONE() throws IOException {
final StringWriter sw = new StringWriter();
final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuotePolicy(Quote.NONE);
final CSVPrinter printer = new CSVPrinter(sw, format);
printer.print("a,b,c");
printer.print("xyz");
assertEquals("a!,b!,c,xyz", sw.toString());
printer.close();
}
@Test
public void testEOLQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("a\rb\nc");
printer.print("x\by\fz");
assertEquals("'a\rb\nc',x\by\fz", sw.toString());
printer.close();
}
@Test
public void testPlainEscaped() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null).withEscape('!'));
printer.print("abc");
printer.print("xyz");
assertEquals("abc,xyz", sw.toString());
printer.close();
}
@Test
public void testDelimiterEscaped() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuoteChar(null));
printer.print("a,b,c");
printer.print("xyz");
assertEquals("a!,b!,c,xyz", sw.toString());
printer.close();
}
@Test
public void testEOLEscaped() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null).withEscape('!'));
printer.print("a\rb\nc");
printer.print("x\fy\bz");
assertEquals("a!rb!nc,x\fy\bz", sw.toString());
printer.close();
}
@Test
public void testPlainPlain() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null));
printer.print("abc");
printer.print("xyz");
assertEquals("abc,xyz", sw.toString());
printer.close();
}
@Test
public void testDelimiterPlain() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null));
printer.print("a,b,c");
printer.print("xyz");
assertEquals("a,b,c,xyz", sw.toString());
printer.close();
}
@Test
public void testHeader() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(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());
printer.close();
}
@Test
public void testEOLPlain() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null));
printer.print("a\rb\nc");
printer.print("x\fy\bz");
assertEquals("a\rb\nc,x\fy\bz", sw.toString());
printer.close();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidFormat() throws Exception {
final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR);
new CSVPrinter(new StringWriter(), invalidFormat).close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCSVPrinterNullAppendableFormat() throws Exception {
new CSVPrinter(null, CSVFormat.DEFAULT).close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCsvPrinterAppendableNullFormat() throws Exception {
new CSVPrinter(new StringWriter(), null).close();
}
} | // You are a professional Java test case writer, please create a test case named `testHeader` for the issue `Csv-CSV-120`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Csv-CSV-120
//
// ## Issue-Title:
// CSVFormat#withHeader doesn't work with CSVPrinter
//
// ## Issue-Description:
//
// In the current version [CSVFormat#withHeader](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withHeader(java.lang.String...)) is only used by CSVParser. It would be nice if CSVPrinter also supported it. Ideally, the following line of code
//
//
//
//
// ```
// CSVPrinter csvPrinter
// = CSVFormat.TDF
// .withHeader("x")
// .print(Files.newBufferedWriter(Paths.get("data.csv")));
// csvPrinter.printRecord(42);
// csvPrinter.close();
//
// ```
//
//
// should produce
//
//
//
//
// ```
// x
// 42
//
// ```
//
//
// If you're alright with the idea of automatically inserting headers, I can attach a patch.
//
//
//
//
//
@Test
public void testHeader() throws IOException {
| 496 | 10 | 487 | src/test/java/org/apache/commons/csv/CSVPrinterTest.java | src/test/java | ```markdown
## Issue-ID: Csv-CSV-120
## Issue-Title:
CSVFormat#withHeader doesn't work with CSVPrinter
## Issue-Description:
In the current version [CSVFormat#withHeader](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withHeader(java.lang.String...)) is only used by CSVParser. It would be nice if CSVPrinter also supported it. Ideally, the following line of code
```
CSVPrinter csvPrinter
= CSVFormat.TDF
.withHeader("x")
.print(Files.newBufferedWriter(Paths.get("data.csv")));
csvPrinter.printRecord(42);
csvPrinter.close();
```
should produce
```
x
42
```
If you're alright with the idea of automatically inserting headers, I can attach a patch.
```
You are a professional Java test case writer, please create a test case named `testHeader` for the issue `Csv-CSV-120`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testHeader() throws IOException {
```
| 487 | [
"org.apache.commons.csv.CSVPrinter"
] | 478207cbdb48725a58cd98422b73ea962225eb9787b4531412143a97044b8c18 | @Test
public void testHeader() throws IOException | // You are a professional Java test case writer, please create a test case named `testHeader` for the issue `Csv-CSV-120`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Csv-CSV-120
//
// ## Issue-Title:
// CSVFormat#withHeader doesn't work with CSVPrinter
//
// ## Issue-Description:
//
// In the current version [CSVFormat#withHeader](https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#withHeader(java.lang.String...)) is only used by CSVParser. It would be nice if CSVPrinter also supported it. Ideally, the following line of code
//
//
//
//
// ```
// CSVPrinter csvPrinter
// = CSVFormat.TDF
// .withHeader("x")
// .print(Files.newBufferedWriter(Paths.get("data.csv")));
// csvPrinter.printRecord(42);
// csvPrinter.close();
//
// ```
//
//
// should produce
//
//
//
//
// ```
// x
// 42
//
// ```
//
//
// If you're alright with the idea of automatically inserting headers, I can attach a patch.
//
//
//
//
//
| 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.assertEquals;
import static org.junit.Assert.assertFalse;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import org.junit.Test;
/**
*
*
* @version $Id$
*/
public class CSVPrinterTest {
private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator();
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 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 = 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();
}
}
final StringWriter sw = new StringWriter();
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();
printer.close();
final String result = sw.toString();
// System.out.println("### :" + printable(result));
final CSVParser parser = CSVParser.parse(result, format);
final List<CSVRecord> parseResult = parser.getRecords();
Utils.compare("Printer output :" + printable(result), lines, parseResult);
parser.close();
}
private void doRandom(final CSVFormat format, final int iter) throws Exception {
for (int i = 0; i < iter; i++) {
doOneRandom(format);
}
}
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 = '"';
break;
case 7:
ch = '\'';
break;
case 8:
ch = '\\';
break;
default:
ch = (char) r.nextInt(300);
break;
// default: ch = 'a'; break;
}
buf[i] = ch;
}
return new String(buf);
}
@Test
public void testDisabledComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printComment("This is a comment");
assertEquals("", sw.toString());
printer.close();
}
@Test
public void testExcelPrintAllArrayOfArrays() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } });
assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testExcelPrintAllArrayOfLists() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecords(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") });
assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testExcelPrintAllIterableOfArrays() throws IOException {
final StringWriter sw = new StringWriter();
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());
printer.close();
}
@Test
public void testExcelPrintAllIterableOfLists() throws IOException {
final StringWriter sw = new StringWriter();
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());
printer.close();
}
@Test
public void testExcelPrinter1() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecord("a", "b");
assertEquals("a,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testExcelPrinter2() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecord("a,b", "b");
assertEquals("\"a,b\",b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException {
final StringWriter sw = new StringWriter();
Class.forName("org.h2.Driver");
final Connection connection = DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", "");
try {
final Statement stmt = connection.createStatement();
stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
stmt.execute("insert into TEST values(1, 'r1')");
stmt.execute("insert into TEST values(2, 'r2')");
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());
printer.close();
} finally {
connection.close();
}
}
@Test
public void testMultiLineComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentStart('#'));
printer.printComment("This is a comment\non multiple lines");
assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter1() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b");
assertEquals("a,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter2() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a,b", "b");
assertEquals("\"a,b\",b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter3() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a, b", "b ");
assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter4() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\"c");
assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter5() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\nc");
assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter6() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\r\nc");
assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrinter7() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", "b\\c");
assertEquals("a,b\\c" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrint() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = CSVFormat.DEFAULT.print(sw);
printer.printRecord("a", "b\\c");
assertEquals("a,b\\c" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrintNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", null, "b");
assertEquals("a,,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testPrintCustomNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"));
printer.printRecord("a", null, "b");
assertEquals("a,NULL,b" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testParseCustomNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL");
final CSVPrinter printer = new CSVPrinter(sw, format);
printer.printRecord("a", null, "b");
printer.close();
final String csvString = sw.toString();
assertEquals("a,NULL,b" + recordSeparator, csvString);
final Iterable<CSVRecord> 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());
((CSVParser) iterable).close();
}
@Test
public void testQuoteAll() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuotePolicy(Quote.ALL));
printer.printRecord("a", "b\nc", "d");
assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testQuoteNonNumeric() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuotePolicy(Quote.NON_NUMERIC));
printer.printRecord("a", "b\nc", Integer.valueOf(1));
assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testRandom() throws Exception {
final int iter = 10000;
doRandom(CSVFormat.DEFAULT, iter);
doRandom(CSVFormat.EXCEL, iter);
doRandom(CSVFormat.MYSQL, iter);
}
@Test
public void testPlainQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("abc");
assertEquals("abc", sw.toString());
printer.close();
}
@Test
public void testSingleLineComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentStart('#'));
printer.printComment("This is a comment");
assertEquals("# This is a comment" + recordSeparator, sw.toString());
printer.close();
}
@Test
public void testSingleQuoteQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("a'b'c");
printer.print("xyz");
assertEquals("'a''b''c',xyz", sw.toString());
printer.close();
}
@Test
public void testDelimeterQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("a,b,c");
printer.print("xyz");
assertEquals("'a,b,c',xyz", sw.toString());
printer.close();
}
@Test
public void testDelimeterQuoteNONE() throws IOException {
final StringWriter sw = new StringWriter();
final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuotePolicy(Quote.NONE);
final CSVPrinter printer = new CSVPrinter(sw, format);
printer.print("a,b,c");
printer.print("xyz");
assertEquals("a!,b!,c,xyz", sw.toString());
printer.close();
}
@Test
public void testEOLQuoted() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\''));
printer.print("a\rb\nc");
printer.print("x\by\fz");
assertEquals("'a\rb\nc',x\by\fz", sw.toString());
printer.close();
}
@Test
public void testPlainEscaped() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null).withEscape('!'));
printer.print("abc");
printer.print("xyz");
assertEquals("abc,xyz", sw.toString());
printer.close();
}
@Test
public void testDelimiterEscaped() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuoteChar(null));
printer.print("a,b,c");
printer.print("xyz");
assertEquals("a!,b!,c,xyz", sw.toString());
printer.close();
}
@Test
public void testEOLEscaped() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null).withEscape('!'));
printer.print("a\rb\nc");
printer.print("x\fy\bz");
assertEquals("a!rb!nc,x\fy\bz", sw.toString());
printer.close();
}
@Test
public void testPlainPlain() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null));
printer.print("abc");
printer.print("xyz");
assertEquals("abc,xyz", sw.toString());
printer.close();
}
@Test
public void testDelimiterPlain() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null));
printer.print("a,b,c");
printer.print("xyz");
assertEquals("a,b,c,xyz", sw.toString());
printer.close();
}
@Test
public void testHeader() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(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());
printer.close();
}
@Test
public void testEOLPlain() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null));
printer.print("a\rb\nc");
printer.print("x\fy\bz");
assertEquals("a\rb\nc,x\fy\bz", sw.toString());
printer.close();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidFormat() throws Exception {
final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR);
new CSVPrinter(new StringWriter(), invalidFormat).close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCSVPrinterNullAppendableFormat() throws Exception {
new CSVPrinter(null, CSVFormat.DEFAULT).close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCsvPrinterAppendableNullFormat() throws Exception {
new CSVPrinter(new StringWriter(), null).close();
}
} |
||
public void testEmpty1256() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
String json = mapper.writeValueAsString(new Issue1256Bean());
assertEquals("{}", json);
} | com.fasterxml.jackson.databind.deser.TestJDKAtomicTypes::testEmpty1256 | src/test/java/com/fasterxml/jackson/databind/deser/TestJDKAtomicTypes.java | 268 | src/test/java/com/fasterxml/jackson/databind/deser/TestJDKAtomicTypes.java | testEmpty1256 | package com.fasterxml.jackson.databind.deser;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.concurrent.atomic.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class TestJDKAtomicTypes
extends com.fasterxml.jackson.databind.BaseMapTest
{
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({ @JsonSubTypes.Type(Impl.class) })
static abstract class Base { }
@JsonTypeName("I")
static class Impl extends Base {
public int value;
public Impl() { }
public Impl(int v) { value = v; }
}
static class RefWrapper
{
public AtomicReference<Base> w;
public RefWrapper() { }
public RefWrapper(Base b) {
w = new AtomicReference<Base>(b);
}
public RefWrapper(int i) {
w = new AtomicReference<Base>(new Impl(i));
}
}
static class SimpleWrapper {
public AtomicReference<Object> value;
public SimpleWrapper() { }
public SimpleWrapper(Object o) { value = new AtomicReference<Object>(o); }
}
static class RefiningWrapper {
@JsonDeserialize(contentAs=BigDecimal.class)
public AtomicReference<Serializable> value;
}
// Additional tests for improvements with [databind#932]
static class UnwrappingRefParent {
@JsonUnwrapped(prefix = "XX.")
public AtomicReference<Child> child = new AtomicReference<Child>(new Child());
}
static class Child {
public String name = "Bob";
}
static class Parent {
private Child child = new Child();
@JsonUnwrapped
public Child getChild() {
return child;
}
}
static class WrappedString {
String value;
public WrappedString(String s) { value = s; }
}
static class AtomicRefReadWrapper {
@JsonDeserialize(contentAs=WrappedString.class)
public AtomicReference<Object> value;
}
static class LCStringWrapper {
@JsonDeserialize(contentUsing=LowerCasingDeserializer.class)
public AtomicReference<String> value;
public LCStringWrapper() { }
}
@JsonPropertyOrder({ "a", "b" })
static class Issue1256Bean {
@JsonSerialize(as=AtomicReference.class)
public Object a = new AtomicReference<Object>();
public AtomicReference<Object> b = new AtomicReference<Object>();
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
public void testAtomicBoolean() throws Exception
{
AtomicBoolean b = MAPPER.readValue("true", AtomicBoolean.class);
assertTrue(b.get());
}
public void testAtomicInt() throws Exception
{
AtomicInteger value = MAPPER.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
}
public void testAtomicLong() throws Exception
{
AtomicLong value = MAPPER.readValue("12345678901", AtomicLong.class);
assertEquals(12345678901L, value.get());
}
public void testAtomicReference() throws Exception
{
AtomicReference<long[]> value = MAPPER.readValue("[1,2]",
new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { });
Object ob = value.get();
assertNotNull(ob);
assertEquals(long[].class, ob.getClass());
long[] longs = (long[]) ob;
assertNotNull(longs);
assertEquals(2, longs.length);
assertEquals(1, longs[0]);
assertEquals(2, longs[1]);
}
// for [databind#811]
public void testAbsentExclusion() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
assertEquals(aposToQuotes("{}"),
mapper.writeValueAsString(new SimpleWrapper(null)));
}
public void testSerPropInclusionAlways() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.ALWAYS);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
public void testSerPropInclusionNonNull() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.NON_NULL);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
public void testSerPropInclusionNonAbsent() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.NON_ABSENT);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
public void testSerPropInclusionNonEmpty() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.NON_EMPTY);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
// [databind#340]
public void testPolymorphicAtomicReference() throws Exception
{
RefWrapper input = new RefWrapper(13);
String json = MAPPER.writeValueAsString(input);
RefWrapper result = MAPPER.readValue(json, RefWrapper.class);
assertNotNull(result.w);
Object ob = result.w.get();
assertEquals(Impl.class, ob.getClass());
assertEquals(13, ((Impl) ob).value);
}
// [databind#740]
public void testFilteringOfAtomicReference() throws Exception
{
SimpleWrapper input = new SimpleWrapper(null);
ObjectMapper mapper = MAPPER;
// by default, include as null
assertEquals("{\"value\":null}", mapper.writeValueAsString(input));
// ditto with "no nulls"
mapper = new ObjectMapper().setSerializationInclusion(JsonInclude
.Include.NON_NULL);
assertEquals("{\"value\":null}", mapper.writeValueAsString(input));
// but not with "non empty"
mapper = new ObjectMapper().setSerializationInclusion(JsonInclude
.Include.NON_EMPTY);
assertEquals("{}", mapper.writeValueAsString(input));
}
public void testTypeRefinement() throws Exception
{
RefiningWrapper input = new RefiningWrapper();
BigDecimal bd = new BigDecimal("0.25");
input.value = new AtomicReference<Serializable>(bd);
String json = MAPPER.writeValueAsString(input);
// so far so good. But does it come back as expected?
RefiningWrapper result = MAPPER.readValue(json, RefiningWrapper.class);
assertNotNull(result.value);
Object ob = result.value.get();
assertEquals(BigDecimal.class, ob.getClass());
assertEquals(bd, ob);
}
// [databind#882]: verify `@JsonDeserialize(contentAs=)` works with AtomicReference
public void testDeserializeWithContentAs() throws Exception
{
AtomicRefReadWrapper result = MAPPER.readValue(aposToQuotes("{'value':'abc'}"),
AtomicRefReadWrapper.class);
Object v = result.value.get();
assertNotNull(v);
assertEquals(WrappedString.class, v.getClass());
assertEquals("abc", ((WrappedString)v).value);
}
// [databind#932]: support unwrapping too
public void testWithUnwrapping() throws Exception
{
String jsonExp = aposToQuotes("{'XX.name':'Bob'}");
String jsonAct = MAPPER.writeValueAsString(new UnwrappingRefParent());
assertEquals(jsonExp, jsonAct);
}
public void testWithCustomDeserializer() throws Exception
{
LCStringWrapper w = MAPPER.readValue(aposToQuotes("{'value':'FoobaR'}"),
LCStringWrapper.class);
assertEquals("foobar", w.value.get());
}
public void testEmpty1256() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
String json = mapper.writeValueAsString(new Issue1256Bean());
assertEquals("{}", json);
}
} | // You are a professional Java test case writer, please create a test case named `testEmpty1256` for the issue `JacksonDatabind-1256`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1256
//
// ## Issue-Title:
// Optional.empty() not excluded if property declared with type Object
//
// ## Issue-Description:
// Jackson version is 2.6.6
//
// **Here is the code:**
//
//
//
// ```
// ObjectMapper mapper = new ObjectMapper();
// mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
// mapper.registerModule(new Jdk8Module());
//
// JsonResult result = new JsonResult();
// result.setA(Optional.empty());
// result.setB(Optional.empty());
// System.out.println(mapper.writeValueAsString(result));
//
// ```
//
//
// ```
// @Data
// public class JsonResult {
// private Object a;
// private Optional<Object> b;
// }
//
// ```
//
// **Then I got the output: {"a":null}**
//
//
// **The real value of both is the same, why the results are different?**
//
//
// **How can I avoid null in such case?**
//
//
// By the way, I tried 'NON\_EMPTY'. It can work, but it also ignores zero and empty array. I want to keep them.
//
//
//
//
public void testEmpty1256() throws Exception {
| 268 | 54 | 261 | src/test/java/com/fasterxml/jackson/databind/deser/TestJDKAtomicTypes.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1256
## Issue-Title:
Optional.empty() not excluded if property declared with type Object
## Issue-Description:
Jackson version is 2.6.6
**Here is the code:**
```
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
mapper.registerModule(new Jdk8Module());
JsonResult result = new JsonResult();
result.setA(Optional.empty());
result.setB(Optional.empty());
System.out.println(mapper.writeValueAsString(result));
```
```
@Data
public class JsonResult {
private Object a;
private Optional<Object> b;
}
```
**Then I got the output: {"a":null}**
**The real value of both is the same, why the results are different?**
**How can I avoid null in such case?**
By the way, I tried 'NON\_EMPTY'. It can work, but it also ignores zero and empty array. I want to keep them.
```
You are a professional Java test case writer, please create a test case named `testEmpty1256` for the issue `JacksonDatabind-1256`, utilizing the provided issue report information and the following function signature.
```java
public void testEmpty1256() throws Exception {
```
| 261 | [
"com.fasterxml.jackson.databind.ser.PropertyBuilder"
] | 47a702a5e6824384812ab7be914fa6428b3bd3c74ac8755787d58223654fb058 | public void testEmpty1256() throws Exception
| // You are a professional Java test case writer, please create a test case named `testEmpty1256` for the issue `JacksonDatabind-1256`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1256
//
// ## Issue-Title:
// Optional.empty() not excluded if property declared with type Object
//
// ## Issue-Description:
// Jackson version is 2.6.6
//
// **Here is the code:**
//
//
//
// ```
// ObjectMapper mapper = new ObjectMapper();
// mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
// mapper.registerModule(new Jdk8Module());
//
// JsonResult result = new JsonResult();
// result.setA(Optional.empty());
// result.setB(Optional.empty());
// System.out.println(mapper.writeValueAsString(result));
//
// ```
//
//
// ```
// @Data
// public class JsonResult {
// private Object a;
// private Optional<Object> b;
// }
//
// ```
//
// **Then I got the output: {"a":null}**
//
//
// **The real value of both is the same, why the results are different?**
//
//
// **How can I avoid null in such case?**
//
//
// By the way, I tried 'NON\_EMPTY'. It can work, but it also ignores zero and empty array. I want to keep them.
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.deser;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.concurrent.atomic.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class TestJDKAtomicTypes
extends com.fasterxml.jackson.databind.BaseMapTest
{
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({ @JsonSubTypes.Type(Impl.class) })
static abstract class Base { }
@JsonTypeName("I")
static class Impl extends Base {
public int value;
public Impl() { }
public Impl(int v) { value = v; }
}
static class RefWrapper
{
public AtomicReference<Base> w;
public RefWrapper() { }
public RefWrapper(Base b) {
w = new AtomicReference<Base>(b);
}
public RefWrapper(int i) {
w = new AtomicReference<Base>(new Impl(i));
}
}
static class SimpleWrapper {
public AtomicReference<Object> value;
public SimpleWrapper() { }
public SimpleWrapper(Object o) { value = new AtomicReference<Object>(o); }
}
static class RefiningWrapper {
@JsonDeserialize(contentAs=BigDecimal.class)
public AtomicReference<Serializable> value;
}
// Additional tests for improvements with [databind#932]
static class UnwrappingRefParent {
@JsonUnwrapped(prefix = "XX.")
public AtomicReference<Child> child = new AtomicReference<Child>(new Child());
}
static class Child {
public String name = "Bob";
}
static class Parent {
private Child child = new Child();
@JsonUnwrapped
public Child getChild() {
return child;
}
}
static class WrappedString {
String value;
public WrappedString(String s) { value = s; }
}
static class AtomicRefReadWrapper {
@JsonDeserialize(contentAs=WrappedString.class)
public AtomicReference<Object> value;
}
static class LCStringWrapper {
@JsonDeserialize(contentUsing=LowerCasingDeserializer.class)
public AtomicReference<String> value;
public LCStringWrapper() { }
}
@JsonPropertyOrder({ "a", "b" })
static class Issue1256Bean {
@JsonSerialize(as=AtomicReference.class)
public Object a = new AtomicReference<Object>();
public AtomicReference<Object> b = new AtomicReference<Object>();
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = objectMapper();
public void testAtomicBoolean() throws Exception
{
AtomicBoolean b = MAPPER.readValue("true", AtomicBoolean.class);
assertTrue(b.get());
}
public void testAtomicInt() throws Exception
{
AtomicInteger value = MAPPER.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
}
public void testAtomicLong() throws Exception
{
AtomicLong value = MAPPER.readValue("12345678901", AtomicLong.class);
assertEquals(12345678901L, value.get());
}
public void testAtomicReference() throws Exception
{
AtomicReference<long[]> value = MAPPER.readValue("[1,2]",
new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { });
Object ob = value.get();
assertNotNull(ob);
assertEquals(long[].class, ob.getClass());
long[] longs = (long[]) ob;
assertNotNull(longs);
assertEquals(2, longs.length);
assertEquals(1, longs[0]);
assertEquals(2, longs[1]);
}
// for [databind#811]
public void testAbsentExclusion() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
assertEquals(aposToQuotes("{}"),
mapper.writeValueAsString(new SimpleWrapper(null)));
}
public void testSerPropInclusionAlways() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.ALWAYS);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
public void testSerPropInclusionNonNull() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.NON_NULL);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
public void testSerPropInclusionNonAbsent() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.NON_ABSENT);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
public void testSerPropInclusionNonEmpty() throws Exception
{
JsonInclude.Value incl =
JsonInclude.Value.construct(JsonInclude.Include.NON_ABSENT, JsonInclude.Include.NON_EMPTY);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyInclusion(incl);
assertEquals(aposToQuotes("{'value':true}"),
mapper.writeValueAsString(new SimpleWrapper(Boolean.TRUE)));
}
// [databind#340]
public void testPolymorphicAtomicReference() throws Exception
{
RefWrapper input = new RefWrapper(13);
String json = MAPPER.writeValueAsString(input);
RefWrapper result = MAPPER.readValue(json, RefWrapper.class);
assertNotNull(result.w);
Object ob = result.w.get();
assertEquals(Impl.class, ob.getClass());
assertEquals(13, ((Impl) ob).value);
}
// [databind#740]
public void testFilteringOfAtomicReference() throws Exception
{
SimpleWrapper input = new SimpleWrapper(null);
ObjectMapper mapper = MAPPER;
// by default, include as null
assertEquals("{\"value\":null}", mapper.writeValueAsString(input));
// ditto with "no nulls"
mapper = new ObjectMapper().setSerializationInclusion(JsonInclude
.Include.NON_NULL);
assertEquals("{\"value\":null}", mapper.writeValueAsString(input));
// but not with "non empty"
mapper = new ObjectMapper().setSerializationInclusion(JsonInclude
.Include.NON_EMPTY);
assertEquals("{}", mapper.writeValueAsString(input));
}
public void testTypeRefinement() throws Exception
{
RefiningWrapper input = new RefiningWrapper();
BigDecimal bd = new BigDecimal("0.25");
input.value = new AtomicReference<Serializable>(bd);
String json = MAPPER.writeValueAsString(input);
// so far so good. But does it come back as expected?
RefiningWrapper result = MAPPER.readValue(json, RefiningWrapper.class);
assertNotNull(result.value);
Object ob = result.value.get();
assertEquals(BigDecimal.class, ob.getClass());
assertEquals(bd, ob);
}
// [databind#882]: verify `@JsonDeserialize(contentAs=)` works with AtomicReference
public void testDeserializeWithContentAs() throws Exception
{
AtomicRefReadWrapper result = MAPPER.readValue(aposToQuotes("{'value':'abc'}"),
AtomicRefReadWrapper.class);
Object v = result.value.get();
assertNotNull(v);
assertEquals(WrappedString.class, v.getClass());
assertEquals("abc", ((WrappedString)v).value);
}
// [databind#932]: support unwrapping too
public void testWithUnwrapping() throws Exception
{
String jsonExp = aposToQuotes("{'XX.name':'Bob'}");
String jsonAct = MAPPER.writeValueAsString(new UnwrappingRefParent());
assertEquals(jsonExp, jsonAct);
}
public void testWithCustomDeserializer() throws Exception
{
LCStringWrapper w = MAPPER.readValue(aposToQuotes("{'value':'FoobaR'}"),
LCStringWrapper.class);
assertEquals("foobar", w.value.get());
}
public void testEmpty1256() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_ABSENT);
String json = mapper.writeValueAsString(new Issue1256Bean());
assertEquals("{}", json);
}
} |
||
public void testByteToStringVariations() throws DecoderException {
Base64 base64 = new Base64(0);
byte[] b1 = StringUtils.getBytesUtf8("Hello World");
byte[] b2 = new byte[0];
byte[] b3 = null;
byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests
assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1));
assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1));
assertEquals("byteToString \"\"", "", base64.encodeToString(b2));
assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2));
assertEquals("byteToString null", null, base64.encodeToString(b3));
assertEquals("byteToString static null", null, Base64.encodeBase64String(b3));
assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4));
assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4));
assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4));
} | org.apache.commons.codec.binary.Base64Test::testByteToStringVariations | src/test/org/apache/commons/codec/binary/Base64Test.java | 1,136 | src/test/org/apache/commons/codec/binary/Base64Test.java | testByteToStringVariations | /*
* 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.math.BigInteger;
import java.util.Arrays;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
/**
* Test cases for Base64 class.
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @author Apache Software Foundation
* @version $Id$
*/
public class Base64Test extends TestCase {
private Random _random = new Random();
/**
* Construct a new instance of this test case.
*
* @param name
* Name of the test case
*/
public Base64Test(String name) {
super(name);
}
/**
* @return Returns the _random.
*/
public Random getRandom() {
return this._random;
}
/**
* Test the Base64 implementation
*/
public void testBase64() {
String content = "Hello World";
String encodedContent;
byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
Base64 b64 = new Base64(Base64.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking
encodedBytes = b64.encode(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking
encodedBytes = b64.encode(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
// bogus characters to decode (to skip actually)
byte[] decode = b64.decode("SGVsbG{יייייי}8gV29ybGQ=");
String decodeString = StringUtils.newStringUtf8(decode);
assertTrue("decode hello world", decodeString.equals("Hello World"));
}
/**
* Tests Base64.encodeBase64().
*/
public void testChunkedEncodeMultipleOf76() {
byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true);
// convert to "\r\n" so we're equal to the old openssl encoding test stored
// in Base64TestData.ENCODED_76_CHARS_PER_LINE:
String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n");
byte[] actualEncode = StringUtils.getBytesUtf8(actualResult);
assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode));
}
/**
* CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some non-BASE64 bytes
*/
public void testCodec68() {
byte[] x = new byte[]{'n', 'A', '=', '=', (byte) 0x9c};
Base64.decodeBase64(x);
}
public void testCodeInteger1() throws UnsupportedEncodingException {
String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU=";
BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981");
assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1)));
assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes("UTF-8")));
}
public void testCodeInteger2() throws UnsupportedEncodingException {
String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs=";
BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611");
assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2)));
assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes("UTF-8")));
}
public void testCodeInteger3() throws UnsupportedEncodingException {
String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg==";
BigInteger bigInt3 = new BigInteger("10806548154093873461951748545"
+ "1196989136416448805819079363524309897749044958112417136240557"
+ "4495062430572478766856090958495998158114332651671116876320938126");
assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3)));
assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes("UTF-8")));
}
public void testCodeInteger4() throws UnsupportedEncodingException {
String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI"
+ "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o"
+ "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv"
+ "Q0=";
BigInteger bigInt4 = new BigInteger("80624726256040348115552042320"
+ "6968135001872753709424419772586693950232350200555646471175944"
+ "519297087885987040810778908507262272892702303774422853675597"
+ "748008534040890923814202286633163248086055216976551456088015"
+ "338880713818192088877057717530169381044092839402438015097654"
+ "53542091716518238707344493641683483917");
assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4)));
assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes("UTF-8")));
}
public void testCodeIntegerEdgeCases() {
// TODO
}
public void testCodeIntegerNull() {
try {
Base64.encodeInteger(null);
fail("Exception not thrown when passing in null to encodeInteger(BigInteger)");
} catch (NullPointerException npe) {
// expected
} catch (Exception e) {
fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)");
}
}
public void testConstructors() {
Base64 base64;
base64 = new Base64();
base64 = new Base64(-1);
base64 = new Base64(-1, new byte[]{});
base64 = new Base64(64, new byte[]{});
try {
base64 = new Base64(-1, new byte[]{'A'});
fail("Should have rejected attempt to use 'A' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
try {
base64 = new Base64(64, new byte[]{'A'});
fail("Should have rejected attempt to use 'A' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
try {
base64 = new Base64(64, new byte[]{'='});
fail("Should have rejected attempt to use '=' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
base64 = new Base64(64, new byte[]{'$'}); // OK
try {
base64 = new Base64(64, new byte[]{'A', '$'});
fail("Should have rejected attempt to use 'A$' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
base64 = new Base64(64, new byte[]{' ', '$', '\n', '\r', '\t'}); // OK
}
public void testConstructor_Int_ByteArray_Boolean() {
Base64 base64 = new Base64(65, new byte[]{'\t'}, false);
byte[] encoded = base64.encode(Base64TestData.DECODED);
String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE;
expectedResult = expectedResult.replace('\n', '\t');
String result = StringUtils.newStringUtf8(encoded);
assertEquals("new Base64(65, \\t, false)", expectedResult, result);
}
public void testConstructor_Int_ByteArray_Boolean_UrlSafe() {
// url-safe variation
Base64 base64 = new Base64(64, new byte[]{'\t'}, true);
byte[] encoded = base64.encode(Base64TestData.DECODED);
String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE;
expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no == padding.
expectedResult = expectedResult.replace('\n', '\t');
expectedResult = expectedResult.replace('+', '-');
expectedResult = expectedResult.replace('/', '_');
String result = StringUtils.newStringUtf8(encoded);
assertEquals("new Base64(64, \\t, true)", result, expectedResult);
}
/**
* Tests conditional true branch for "marker0" test.
*/
public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException {
assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes("UTF-8"))));
}
/**
* Tests conditional branches for "marker1" test.
*/
public void testDecodePadMarkerIndex3() throws UnsupportedEncodingException {
assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes("UTF-8"))));
assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes("UTF-8"))));
}
public void testDecodePadOnly() throws UnsupportedEncodingException {
assertTrue(Base64.decodeBase64("====".getBytes("UTF-8")).length == 0);
assertEquals("", new String(Base64.decodeBase64("====".getBytes("UTF-8"))));
// Test truncated padding
assertTrue(Base64.decodeBase64("===".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("==".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("=".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("".getBytes("UTF-8")).length == 0);
}
public void testDecodePadOnlyChunked() throws UnsupportedEncodingException {
assertTrue(Base64.decodeBase64("====\n".getBytes("UTF-8")).length == 0);
assertEquals("", new String(Base64.decodeBase64("====\n".getBytes("UTF-8"))));
// Test truncated padding
assertTrue(Base64.decodeBase64("===\n".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("==\n".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("=\n".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("\n".getBytes("UTF-8")).length == 0);
}
public void testDecodeWithWhitespace() throws Exception {
String orig = "I am a late night coder.";
byte[] encodedArray = Base64.encodeBase64(orig.getBytes("UTF-8"));
StringBuffer intermediate = new StringBuffer(new String(encodedArray));
intermediate.insert(2, ' ');
intermediate.insert(5, '\t');
intermediate.insert(10, '\r');
intermediate.insert(15, '\n');
byte[] encodedWithWS = intermediate.toString().getBytes("UTF-8");
byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS);
String dest = new String(decodedWithWS);
assertTrue("Dest string doesn't equal the original", dest.equals(orig));
}
public void testDiscardWhitespace() throws Exception {
String orig = "I am a late night coder.";
byte[] encodedArray = Base64.encodeBase64(orig.getBytes("UTF-8"));
StringBuffer intermediate = new StringBuffer(new String(encodedArray));
intermediate.insert(2, ' ');
intermediate.insert(5, '\t');
intermediate.insert(10, '\r');
intermediate.insert(15, '\n');
byte[] encodedWithWS = intermediate.toString().getBytes("UTF-8");
byte[] encodedNoWS = Base64.discardWhitespace(encodedWithWS);
byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS);
byte[] decodedNoWS = Base64.decodeBase64(encodedNoWS);
String destFromWS = new String(decodedWithWS);
String destFromNoWS = new String(decodedNoWS);
assertTrue("Dest string doesn't equal original", destFromWS.equals(orig));
assertTrue("Dest string doesn't equal original", destFromNoWS.equals(orig));
}
/**
* Test encode and decode of empty byte array.
*/
public void testEmptyBase64() {
byte[] empty = new byte[0];
byte[] result = Base64.encodeBase64(empty);
assertEquals("empty base64 encode", 0, result.length);
assertEquals("empty base64 encode", null, Base64.encodeBase64(null));
empty = new byte[0];
result = Base64.decodeBase64(empty);
assertEquals("empty base64 decode", 0, result.length);
assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null));
}
// encode/decode a large random array
public void testEncodeDecodeRandom() {
for (int i = 1; i < 5; i++) {
byte[] data = new byte[this.getRandom().nextInt(10000) + 1];
this.getRandom().nextBytes(data);
byte[] enc = Base64.encodeBase64(data);
assertTrue(Base64.isArrayByteBase64(enc));
byte[] data2 = Base64.decodeBase64(enc);
assertTrue(Arrays.equals(data, data2));
}
}
// encode/decode random arrays from size 0 to size 11
public void testEncodeDecodeSmall() {
for (int i = 0; i < 12; i++) {
byte[] data = new byte[i];
this.getRandom().nextBytes(data);
byte[] enc = Base64.encodeBase64(data);
assertTrue("\"" + (new String(enc)) + "\" is Base64 data.", Base64.isArrayByteBase64(enc));
byte[] data2 = Base64.decodeBase64(enc);
assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2));
}
}
public void testEncodeOverMaxSize() throws Exception {
testEncodeOverMaxSize(-1);
testEncodeOverMaxSize(0);
testEncodeOverMaxSize(1);
testEncodeOverMaxSize(2);
}
private void testEncodeOverMaxSize(int maxSize) throws Exception {
try {
Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize);
fail("Expected " + IllegalArgumentException.class.getName());
} catch (IllegalArgumentException e) {
// Expceted
}
}
public void testIgnoringNonBase64InDecode() throws Exception {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8"))));
}
public void testIsArrayByteBase64() {
assertFalse(Base64.isArrayByteBase64(new byte[]{Byte.MIN_VALUE}));
assertFalse(Base64.isArrayByteBase64(new byte[]{-125}));
assertFalse(Base64.isArrayByteBase64(new byte[]{-10}));
assertFalse(Base64.isArrayByteBase64(new byte[]{0}));
assertFalse(Base64.isArrayByteBase64(new byte[]{64, Byte.MAX_VALUE}));
assertFalse(Base64.isArrayByteBase64(new byte[]{Byte.MAX_VALUE}));
assertTrue(Base64.isArrayByteBase64(new byte[]{'A'}));
assertFalse(Base64.isArrayByteBase64(new byte[]{'A', Byte.MIN_VALUE}));
assertTrue(Base64.isArrayByteBase64(new byte[]{'A', 'Z', 'a'}));
assertTrue(Base64.isArrayByteBase64(new byte[]{'/', '=', '+'}));
assertFalse(Base64.isArrayByteBase64(new byte[]{'$'}));
}
/**
* Tests isUrlSafe.
*/
public void testIsUrlSafe() {
Base64 base64Standard = new Base64(false);
Base64 base64URLSafe = new Base64(true);
assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe());
assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe());
byte[] whiteSpace = {' ', '\n', '\r', '\t'};
assertTrue("Base64.isArrayByteBase64(whiteSpace)=true", Base64.isArrayByteBase64(whiteSpace));
}
public void testKnownDecodings() throws UnsupportedEncodingException {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8"))));
assertEquals("It was the best of times, it was the worst of times.", new String(Base64
.decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes("UTF-8"))));
assertEquals("http://jakarta.apache.org/commmons", new String(Base64
.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes("UTF-8"))));
assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64
.decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes("UTF-8"))));
assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0="
.getBytes("UTF-8"))));
assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes("UTF-8"))));
}
public void testKnownEncodings() throws UnsupportedEncodingException {
assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64
.encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes("UTF-8"))));
assertEquals(
"YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n",
new String(
Base64
.encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"
.getBytes("UTF-8"))));
assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64
.encodeBase64("It was the best of times, it was the worst of times.".getBytes("UTF-8"))));
assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64
.encodeBase64("http://jakarta.apache.org/commmons".getBytes("UTF-8"))));
assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64
.encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes("UTF-8"))));
assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }"
.getBytes("UTF-8"))));
assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes("UTF-8"))));
}
public void testNonBase64Test() throws Exception {
byte[] bArray = {'%'};
assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64
.isArrayByteBase64(bArray));
try {
Base64 b64 = new Base64();
byte[] result = b64.decode(bArray);
assertTrue("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters",
result.length == 0);
} catch (Exception e) {
fail("Exception was thrown when trying to decode "
+ "invalid base64 encoded data - RFC 2045 requires that all "
+ "non base64 character be discarded, an exception should not"
+ " have been thrown");
}
}
public void testObjectDecodeWithInvalidParameter() throws Exception {
Base64 b64 = new Base64();
try {
b64.decode(new Integer(5));
fail("decode(Object) didn't throw an exception when passed an Integer object");
} catch (DecoderException e) {
// ignored
}
}
public void testObjectDecodeWithValidParameter() throws Exception {
String original = "Hello World!";
Object o = Base64.encodeBase64(original.getBytes("UTF-8"));
Base64 b64 = new Base64();
Object oDecoded = b64.decode(o);
byte[] baDecoded = (byte[]) oDecoded;
String dest = new String(baDecoded);
assertTrue("dest string does not equal original", dest.equals(original));
}
public void testObjectEncodeWithInvalidParameter() throws Exception {
Base64 b64 = new Base64();
try {
b64.encode("Yadayadayada");
fail("encode(Object) didn't throw an exception when passed a String object");
} catch (EncoderException e) {
// Expected
}
}
public void testObjectEncodeWithValidParameter() throws Exception {
String original = "Hello World!";
Object origObj = original.getBytes("UTF-8");
Base64 b64 = new Base64();
Object oEncoded = b64.encode(origObj);
byte[] bArray = Base64.decodeBase64((byte[]) oEncoded);
String dest = new String(bArray);
assertTrue("dest string does not equal original", dest.equals(original));
}
public void testObjectEncode() throws Exception {
Base64 b64 = new Base64();
assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes("UTF-8"))));
}
public void testPairs() {
assertEquals("AAA=", new String(Base64.encodeBase64(new byte[]{0, 0})));
for (int i = -128; i <= 127; i++) {
byte test[] = {(byte) i, (byte) i};
assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test))));
}
}
/**
* Tests RFC 2045 section 2.1 CRLF definition.
*/
public void testRfc2045Section2Dot1CrLfDefinition() {
assertTrue(Arrays.equals(new byte[]{13, 10}, Base64.CHUNK_SEPARATOR));
}
/**
* Tests RFC 2045 section 6.8 chuck size definition.
*/
public void testRfc2045Section6Dot8ChunkSizeDefinition() {
assertEquals(76, Base64.MIME_CHUNK_SIZE);
}
/**
* Tests RFC 1421 section 4.3.2.4 chuck size definition.
*/
public void testRfc1421Section6Dot8ChunkSizeDefinition() {
assertEquals(64, Base64.PEM_CHUNK_SIZE);
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10Decode() {
assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("")));
assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==")));
assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=")));
assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v")));
assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==")));
assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=")));
assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy")));
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10DecodeWithCrLf() {
String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR);
assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF)));
assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF)));
assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF)));
assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF)));
assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF)));
assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF)));
assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF)));
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10Encode() {
assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8("")));
assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f")));
assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo")));
assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo")));
assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob")));
assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba")));
assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar")));
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10DecodeEncode() {
testDecodeEncode("");
//testDecodeEncode("Zg==");
//testDecodeEncode("Zm8=");
//testDecodeEncode("Zm9v");
//testDecodeEncode("Zm9vYg==");
//testDecodeEncode("Zm9vYmE=");
//testDecodeEncode("Zm9vYmFy");
}
private void testDecodeEncode(String encodedText) {
String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText));
String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText));
assertEquals(encodedText, encodedText2);
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10EncodeDecode() {
testEncodeDecode("");
testEncodeDecode("f");
testEncodeDecode("fo");
testEncodeDecode("foo");
testEncodeDecode("foob");
testEncodeDecode("fooba");
testEncodeDecode("foobar");
}
private void testEncodeDecode(String plainText) {
String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText));
String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText));
assertEquals(plainText, decodedText);
}
public void testSingletons() {
assertEquals("AA==", new String(Base64.encodeBase64(new byte[]{(byte) 0})));
assertEquals("AQ==", new String(Base64.encodeBase64(new byte[]{(byte) 1})));
assertEquals("Ag==", new String(Base64.encodeBase64(new byte[]{(byte) 2})));
assertEquals("Aw==", new String(Base64.encodeBase64(new byte[]{(byte) 3})));
assertEquals("BA==", new String(Base64.encodeBase64(new byte[]{(byte) 4})));
assertEquals("BQ==", new String(Base64.encodeBase64(new byte[]{(byte) 5})));
assertEquals("Bg==", new String(Base64.encodeBase64(new byte[]{(byte) 6})));
assertEquals("Bw==", new String(Base64.encodeBase64(new byte[]{(byte) 7})));
assertEquals("CA==", new String(Base64.encodeBase64(new byte[]{(byte) 8})));
assertEquals("CQ==", new String(Base64.encodeBase64(new byte[]{(byte) 9})));
assertEquals("Cg==", new String(Base64.encodeBase64(new byte[]{(byte) 10})));
assertEquals("Cw==", new String(Base64.encodeBase64(new byte[]{(byte) 11})));
assertEquals("DA==", new String(Base64.encodeBase64(new byte[]{(byte) 12})));
assertEquals("DQ==", new String(Base64.encodeBase64(new byte[]{(byte) 13})));
assertEquals("Dg==", new String(Base64.encodeBase64(new byte[]{(byte) 14})));
assertEquals("Dw==", new String(Base64.encodeBase64(new byte[]{(byte) 15})));
assertEquals("EA==", new String(Base64.encodeBase64(new byte[]{(byte) 16})));
assertEquals("EQ==", new String(Base64.encodeBase64(new byte[]{(byte) 17})));
assertEquals("Eg==", new String(Base64.encodeBase64(new byte[]{(byte) 18})));
assertEquals("Ew==", new String(Base64.encodeBase64(new byte[]{(byte) 19})));
assertEquals("FA==", new String(Base64.encodeBase64(new byte[]{(byte) 20})));
assertEquals("FQ==", new String(Base64.encodeBase64(new byte[]{(byte) 21})));
assertEquals("Fg==", new String(Base64.encodeBase64(new byte[]{(byte) 22})));
assertEquals("Fw==", new String(Base64.encodeBase64(new byte[]{(byte) 23})));
assertEquals("GA==", new String(Base64.encodeBase64(new byte[]{(byte) 24})));
assertEquals("GQ==", new String(Base64.encodeBase64(new byte[]{(byte) 25})));
assertEquals("Gg==", new String(Base64.encodeBase64(new byte[]{(byte) 26})));
assertEquals("Gw==", new String(Base64.encodeBase64(new byte[]{(byte) 27})));
assertEquals("HA==", new String(Base64.encodeBase64(new byte[]{(byte) 28})));
assertEquals("HQ==", new String(Base64.encodeBase64(new byte[]{(byte) 29})));
assertEquals("Hg==", new String(Base64.encodeBase64(new byte[]{(byte) 30})));
assertEquals("Hw==", new String(Base64.encodeBase64(new byte[]{(byte) 31})));
assertEquals("IA==", new String(Base64.encodeBase64(new byte[]{(byte) 32})));
assertEquals("IQ==", new String(Base64.encodeBase64(new byte[]{(byte) 33})));
assertEquals("Ig==", new String(Base64.encodeBase64(new byte[]{(byte) 34})));
assertEquals("Iw==", new String(Base64.encodeBase64(new byte[]{(byte) 35})));
assertEquals("JA==", new String(Base64.encodeBase64(new byte[]{(byte) 36})));
assertEquals("JQ==", new String(Base64.encodeBase64(new byte[]{(byte) 37})));
assertEquals("Jg==", new String(Base64.encodeBase64(new byte[]{(byte) 38})));
assertEquals("Jw==", new String(Base64.encodeBase64(new byte[]{(byte) 39})));
assertEquals("KA==", new String(Base64.encodeBase64(new byte[]{(byte) 40})));
assertEquals("KQ==", new String(Base64.encodeBase64(new byte[]{(byte) 41})));
assertEquals("Kg==", new String(Base64.encodeBase64(new byte[]{(byte) 42})));
assertEquals("Kw==", new String(Base64.encodeBase64(new byte[]{(byte) 43})));
assertEquals("LA==", new String(Base64.encodeBase64(new byte[]{(byte) 44})));
assertEquals("LQ==", new String(Base64.encodeBase64(new byte[]{(byte) 45})));
assertEquals("Lg==", new String(Base64.encodeBase64(new byte[]{(byte) 46})));
assertEquals("Lw==", new String(Base64.encodeBase64(new byte[]{(byte) 47})));
assertEquals("MA==", new String(Base64.encodeBase64(new byte[]{(byte) 48})));
assertEquals("MQ==", new String(Base64.encodeBase64(new byte[]{(byte) 49})));
assertEquals("Mg==", new String(Base64.encodeBase64(new byte[]{(byte) 50})));
assertEquals("Mw==", new String(Base64.encodeBase64(new byte[]{(byte) 51})));
assertEquals("NA==", new String(Base64.encodeBase64(new byte[]{(byte) 52})));
assertEquals("NQ==", new String(Base64.encodeBase64(new byte[]{(byte) 53})));
assertEquals("Ng==", new String(Base64.encodeBase64(new byte[]{(byte) 54})));
assertEquals("Nw==", new String(Base64.encodeBase64(new byte[]{(byte) 55})));
assertEquals("OA==", new String(Base64.encodeBase64(new byte[]{(byte) 56})));
assertEquals("OQ==", new String(Base64.encodeBase64(new byte[]{(byte) 57})));
assertEquals("Og==", new String(Base64.encodeBase64(new byte[]{(byte) 58})));
assertEquals("Ow==", new String(Base64.encodeBase64(new byte[]{(byte) 59})));
assertEquals("PA==", new String(Base64.encodeBase64(new byte[]{(byte) 60})));
assertEquals("PQ==", new String(Base64.encodeBase64(new byte[]{(byte) 61})));
assertEquals("Pg==", new String(Base64.encodeBase64(new byte[]{(byte) 62})));
assertEquals("Pw==", new String(Base64.encodeBase64(new byte[]{(byte) 63})));
assertEquals("QA==", new String(Base64.encodeBase64(new byte[]{(byte) 64})));
assertEquals("QQ==", new String(Base64.encodeBase64(new byte[]{(byte) 65})));
assertEquals("Qg==", new String(Base64.encodeBase64(new byte[]{(byte) 66})));
assertEquals("Qw==", new String(Base64.encodeBase64(new byte[]{(byte) 67})));
assertEquals("RA==", new String(Base64.encodeBase64(new byte[]{(byte) 68})));
assertEquals("RQ==", new String(Base64.encodeBase64(new byte[]{(byte) 69})));
assertEquals("Rg==", new String(Base64.encodeBase64(new byte[]{(byte) 70})));
assertEquals("Rw==", new String(Base64.encodeBase64(new byte[]{(byte) 71})));
assertEquals("SA==", new String(Base64.encodeBase64(new byte[]{(byte) 72})));
assertEquals("SQ==", new String(Base64.encodeBase64(new byte[]{(byte) 73})));
assertEquals("Sg==", new String(Base64.encodeBase64(new byte[]{(byte) 74})));
assertEquals("Sw==", new String(Base64.encodeBase64(new byte[]{(byte) 75})));
assertEquals("TA==", new String(Base64.encodeBase64(new byte[]{(byte) 76})));
assertEquals("TQ==", new String(Base64.encodeBase64(new byte[]{(byte) 77})));
assertEquals("Tg==", new String(Base64.encodeBase64(new byte[]{(byte) 78})));
assertEquals("Tw==", new String(Base64.encodeBase64(new byte[]{(byte) 79})));
assertEquals("UA==", new String(Base64.encodeBase64(new byte[]{(byte) 80})));
assertEquals("UQ==", new String(Base64.encodeBase64(new byte[]{(byte) 81})));
assertEquals("Ug==", new String(Base64.encodeBase64(new byte[]{(byte) 82})));
assertEquals("Uw==", new String(Base64.encodeBase64(new byte[]{(byte) 83})));
assertEquals("VA==", new String(Base64.encodeBase64(new byte[]{(byte) 84})));
assertEquals("VQ==", new String(Base64.encodeBase64(new byte[]{(byte) 85})));
assertEquals("Vg==", new String(Base64.encodeBase64(new byte[]{(byte) 86})));
assertEquals("Vw==", new String(Base64.encodeBase64(new byte[]{(byte) 87})));
assertEquals("WA==", new String(Base64.encodeBase64(new byte[]{(byte) 88})));
assertEquals("WQ==", new String(Base64.encodeBase64(new byte[]{(byte) 89})));
assertEquals("Wg==", new String(Base64.encodeBase64(new byte[]{(byte) 90})));
assertEquals("Ww==", new String(Base64.encodeBase64(new byte[]{(byte) 91})));
assertEquals("XA==", new String(Base64.encodeBase64(new byte[]{(byte) 92})));
assertEquals("XQ==", new String(Base64.encodeBase64(new byte[]{(byte) 93})));
assertEquals("Xg==", new String(Base64.encodeBase64(new byte[]{(byte) 94})));
assertEquals("Xw==", new String(Base64.encodeBase64(new byte[]{(byte) 95})));
assertEquals("YA==", new String(Base64.encodeBase64(new byte[]{(byte) 96})));
assertEquals("YQ==", new String(Base64.encodeBase64(new byte[]{(byte) 97})));
assertEquals("Yg==", new String(Base64.encodeBase64(new byte[]{(byte) 98})));
assertEquals("Yw==", new String(Base64.encodeBase64(new byte[]{(byte) 99})));
assertEquals("ZA==", new String(Base64.encodeBase64(new byte[]{(byte) 100})));
assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[]{(byte) 101})));
assertEquals("Zg==", new String(Base64.encodeBase64(new byte[]{(byte) 102})));
assertEquals("Zw==", new String(Base64.encodeBase64(new byte[]{(byte) 103})));
assertEquals("aA==", new String(Base64.encodeBase64(new byte[]{(byte) 104})));
for (int i = -128; i <= 127; i++) {
byte test[] = {(byte) i};
assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test))));
}
}
public void testSingletonsChunked() {
assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0})));
assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 1})));
assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 2})));
assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 3})));
assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 4})));
assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 5})));
assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 6})));
assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 7})));
assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 8})));
assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 9})));
assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 10})));
assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 11})));
assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 12})));
assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 13})));
assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 14})));
assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 15})));
assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 16})));
assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 17})));
assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 18})));
assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 19})));
assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 20})));
assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 21})));
assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 22})));
assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 23})));
assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 24})));
assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 25})));
assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 26})));
assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 27})));
assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 28})));
assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 29})));
assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 30})));
assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 31})));
assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 32})));
assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 33})));
assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 34})));
assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 35})));
assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 36})));
assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 37})));
assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 38})));
assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 39})));
assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 40})));
assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 41})));
assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 42})));
assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 43})));
assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 44})));
assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 45})));
assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 46})));
assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 47})));
assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 48})));
assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 49})));
assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 50})));
assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 51})));
assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 52})));
assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 53})));
assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 54})));
assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 55})));
assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 56})));
assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 57})));
assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 58})));
assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 59})));
assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 60})));
assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 61})));
assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 62})));
assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 63})));
assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 64})));
assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 65})));
assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 66})));
assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 67})));
assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 68})));
assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 69})));
assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 70})));
assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 71})));
assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 72})));
assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 73})));
assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 74})));
assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 75})));
assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 76})));
assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 77})));
assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 78})));
assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 79})));
assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 80})));
assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 81})));
assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 82})));
assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 83})));
assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 84})));
assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 85})));
assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 86})));
assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 87})));
assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 88})));
assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 89})));
assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 90})));
assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 91})));
assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 92})));
assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 93})));
assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 94})));
assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 95})));
assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 96})));
assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 97})));
assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 98})));
assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 99})));
assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 100})));
assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 101})));
assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 102})));
assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 103})));
assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 104})));
}
public void testTriplets() {
assertEquals("AAAA", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 0})));
assertEquals("AAAB", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 1})));
assertEquals("AAAC", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 2})));
assertEquals("AAAD", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 3})));
assertEquals("AAAE", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 4})));
assertEquals("AAAF", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 5})));
assertEquals("AAAG", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 6})));
assertEquals("AAAH", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 7})));
assertEquals("AAAI", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 8})));
assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 9})));
assertEquals("AAAK", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 10})));
assertEquals("AAAL", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 11})));
assertEquals("AAAM", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 12})));
assertEquals("AAAN", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 13})));
assertEquals("AAAO", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 14})));
assertEquals("AAAP", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 15})));
assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 16})));
assertEquals("AAAR", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 17})));
assertEquals("AAAS", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 18})));
assertEquals("AAAT", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 19})));
assertEquals("AAAU", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 20})));
assertEquals("AAAV", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 21})));
assertEquals("AAAW", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 22})));
assertEquals("AAAX", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 23})));
assertEquals("AAAY", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 24})));
assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 25})));
assertEquals("AAAa", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 26})));
assertEquals("AAAb", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 27})));
assertEquals("AAAc", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 28})));
assertEquals("AAAd", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 29})));
assertEquals("AAAe", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 30})));
assertEquals("AAAf", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 31})));
assertEquals("AAAg", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 32})));
assertEquals("AAAh", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 33})));
assertEquals("AAAi", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 34})));
assertEquals("AAAj", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 35})));
assertEquals("AAAk", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 36})));
assertEquals("AAAl", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 37})));
assertEquals("AAAm", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 38})));
assertEquals("AAAn", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 39})));
assertEquals("AAAo", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 40})));
assertEquals("AAAp", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 41})));
assertEquals("AAAq", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 42})));
assertEquals("AAAr", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 43})));
assertEquals("AAAs", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 44})));
assertEquals("AAAt", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 45})));
assertEquals("AAAu", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 46})));
assertEquals("AAAv", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 47})));
assertEquals("AAAw", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 48})));
assertEquals("AAAx", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 49})));
assertEquals("AAAy", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 50})));
assertEquals("AAAz", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 51})));
assertEquals("AAA0", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 52})));
assertEquals("AAA1", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 53})));
assertEquals("AAA2", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 54})));
assertEquals("AAA3", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 55})));
assertEquals("AAA4", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 56})));
assertEquals("AAA5", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 57})));
assertEquals("AAA6", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 58})));
assertEquals("AAA7", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 59})));
assertEquals("AAA8", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 60})));
assertEquals("AAA9", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 61})));
assertEquals("AAA+", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 62})));
assertEquals("AAA/", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 63})));
}
public void testTripletsChunked() {
assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 0})));
assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 1})));
assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 2})));
assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 3})));
assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 4})));
assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 5})));
assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 6})));
assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 7})));
assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 8})));
assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 9})));
assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 10})));
assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 11})));
assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 12})));
assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 13})));
assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 14})));
assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 15})));
assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 16})));
assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 17})));
assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 18})));
assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 19})));
assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 20})));
assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 21})));
assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 22})));
assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 23})));
assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 24})));
assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 25})));
assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 26})));
assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 27})));
assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 28})));
assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 29})));
assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 30})));
assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 31})));
assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 32})));
assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 33})));
assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 34})));
assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 35})));
assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 36})));
assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 37})));
assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 38})));
assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 39})));
assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 40})));
assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 41})));
assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 42})));
assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 43})));
assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 44})));
assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 45})));
assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 46})));
assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 47})));
assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 48})));
assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 49})));
assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 50})));
assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 51})));
assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 52})));
assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 53})));
assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 54})));
assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 55})));
assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 56})));
assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 57})));
assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 58})));
assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 59})));
assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 60})));
assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 61})));
assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 62})));
assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 63})));
}
/**
* Tests url-safe Base64 against random data, sizes 0 to 150.
*/
public void testUrlSafe() {
// test random data of sizes 0 thru 150
for (int i = 0; i <= 150; i++) {
byte[][] randomData = Base64TestData.randomData(i, true);
byte[] encoded = randomData[1];
byte[] decoded = randomData[0];
byte[] result = Base64.decodeBase64(encoded);
assertTrue("url-safe i=" + i, Arrays.equals(decoded, result));
assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '='));
assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\'));
assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+'));
}
}
/**
* Base64 encoding of UUID's is a common use-case, especially in URL-SAFE mode. This test case ends up being the
* "URL-SAFE" JUnit's.
*
* @throws DecoderException
* if Hex.decode() fails - a serious problem since Hex comes from our own commons-codec!
*/
public void testUUID() throws DecoderException {
// The 4 UUID's below contains mixtures of + and / to help us test the
// URL-SAFE encoding mode.
byte[][] ids = new byte[4][];
// ids[0] was chosen so that it encodes with at least one +.
ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370".toCharArray());
// ids[1] was chosen so that it encodes with both / and +.
ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray());
// ids[2] was chosen so that it encodes with at least one /.
ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca".toCharArray());
// ids[3] was chosen so that it encodes with both / and +, with /
// right at the beginning.
ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8".toCharArray());
byte[][] standard = new byte[4][];
standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA==");
standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA==");
standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg==");
standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A==");
byte[][] urlSafe1 = new byte[4][];
// regular padding (two '==' signs).
urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA==");
urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA==");
urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg==");
urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A==");
byte[][] urlSafe2 = new byte[4][];
// single padding (only one '=' sign).
urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=");
urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=");
urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=");
urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=");
byte[][] urlSafe3 = new byte[4][];
// no padding (no '=' signs).
urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA");
urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA");
urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg");
urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A");
for (int i = 0; i < 4; i++) {
byte[] encodedStandard = Base64.encodeBase64(ids[i]);
byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]);
byte[] decodedStandard = Base64.decodeBase64(standard[i]);
byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]);
byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]);
byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]);
// Very important debugging output should anyone
// ever need to delve closely into this stuff.
if (false) {
System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]");
System.out.println("standard: [" +
Hex.encodeHexString(decodedStandard) +
"] From: [" +
StringUtils.newStringUtf8(standard[i]) +
"]");
System.out.println("safe1: [" +
Hex.encodeHexString(decodedUrlSafe1) +
"] From: [" +
StringUtils.newStringUtf8(urlSafe1[i]) +
"]");
System.out.println("safe2: [" +
Hex.encodeHexString(decodedUrlSafe2) +
"] From: [" +
StringUtils.newStringUtf8(urlSafe2[i]) +
"]");
System.out.println("safe3: [" +
Hex.encodeHexString(decodedUrlSafe3) +
"] From: [" +
StringUtils.newStringUtf8(urlSafe3[i]) +
"]");
}
assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i]));
assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i]));
assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i]));
assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i]));
assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i]));
assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i]));
}
}
public void testByteToStringVariations() throws DecoderException {
Base64 base64 = new Base64(0);
byte[] b1 = StringUtils.getBytesUtf8("Hello World");
byte[] b2 = new byte[0];
byte[] b3 = null;
byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests
assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1));
assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1));
assertEquals("byteToString \"\"", "", base64.encodeToString(b2));
assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2));
assertEquals("byteToString null", null, base64.encodeToString(b3));
assertEquals("byteToString static null", null, Base64.encodeBase64String(b3));
assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4));
assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4));
assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4));
}
public void testStringToByteVariations() throws DecoderException {
Base64 base64 = new Base64();
String s1 = "SGVsbG8gV29ybGQ=\r\n";
String s2 = "";
String s3 = null;
String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n";
String s4b = "K_fMJwH-Q5e0nr7tWsxwkA";
byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests
assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1)));
assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[])base64.decode((Object)s1)));
assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1)));
assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2)));
assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2)));
assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3)));
assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3)));
assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b)));
assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a)));
assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b)));
}
private String toString(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
buf.append(data[i]);
if (i != data.length - 1) {
buf.append(",");
}
}
return buf.toString();
}
} | // You are a professional Java test case writer, please create a test case named `testByteToStringVariations` for the issue `Codec-CODEC-99`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-99
//
// ## Issue-Title:
// Base64.encodeBase64String() shouldn't chunk
//
// ## Issue-Description:
//
// Base64.encodeBase64String() shouldn't chunk.
//
//
// Change this:
//
//
//
//
// ```
// public static String encodeBase64String(byte[] binaryData) {
// return StringUtils.newStringUtf8(encodeBase64(binaryData, true));
// }
//
// ```
//
//
// To this:
//
//
//
//
// ```
// public static String encodeBase64String(byte[] binaryData) {
// return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
// }
//
// ```
//
//
// This will fix the following tests ggregory added a few minutes ago:
//
//
// //assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f")));
//
// //assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo")));
//
// //assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo")));
//
// //assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob")));
//
// //assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba")));
//
// //assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar")));
//
//
//
//
//
public void testByteToStringVariations() throws DecoderException {
| 1,136 | 7 | 1,120 | src/test/org/apache/commons/codec/binary/Base64Test.java | src/test | ```markdown
## Issue-ID: Codec-CODEC-99
## Issue-Title:
Base64.encodeBase64String() shouldn't chunk
## Issue-Description:
Base64.encodeBase64String() shouldn't chunk.
Change this:
```
public static String encodeBase64String(byte[] binaryData) {
return StringUtils.newStringUtf8(encodeBase64(binaryData, true));
}
```
To this:
```
public static String encodeBase64String(byte[] binaryData) {
return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
}
```
This will fix the following tests ggregory added a few minutes ago:
//assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f")));
//assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo")));
//assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo")));
//assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob")));
//assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba")));
//assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar")));
```
You are a professional Java test case writer, please create a test case named `testByteToStringVariations` for the issue `Codec-CODEC-99`, utilizing the provided issue report information and the following function signature.
```java
public void testByteToStringVariations() throws DecoderException {
```
| 1,120 | [
"org.apache.commons.codec.binary.Base64"
] | 4ae1c7527097f7e0339bd1e34ff7ea41e3af88c2c44d31a44ba3ab614f9a934e | public void testByteToStringVariations() throws DecoderException | // You are a professional Java test case writer, please create a test case named `testByteToStringVariations` for the issue `Codec-CODEC-99`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-99
//
// ## Issue-Title:
// Base64.encodeBase64String() shouldn't chunk
//
// ## Issue-Description:
//
// Base64.encodeBase64String() shouldn't chunk.
//
//
// Change this:
//
//
//
//
// ```
// public static String encodeBase64String(byte[] binaryData) {
// return StringUtils.newStringUtf8(encodeBase64(binaryData, true));
// }
//
// ```
//
//
// To this:
//
//
//
//
// ```
// public static String encodeBase64String(byte[] binaryData) {
// return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
// }
//
// ```
//
//
// This will fix the following tests ggregory added a few minutes ago:
//
//
// //assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f")));
//
// //assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo")));
//
// //assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo")));
//
// //assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob")));
//
// //assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba")));
//
// //assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar")));
//
//
//
//
//
| 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.math.BigInteger;
import java.util.Arrays;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
/**
* Test cases for Base64 class.
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @author Apache Software Foundation
* @version $Id$
*/
public class Base64Test extends TestCase {
private Random _random = new Random();
/**
* Construct a new instance of this test case.
*
* @param name
* Name of the test case
*/
public Base64Test(String name) {
super(name);
}
/**
* @return Returns the _random.
*/
public Random getRandom() {
return this._random;
}
/**
* Test the Base64 implementation
*/
public void testBase64() {
String content = "Hello World";
String encodedContent;
byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
Base64 b64 = new Base64(Base64.MIME_CHUNK_SIZE, null); // null lineSeparator same as saying no-chunking
encodedBytes = b64.encode(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
b64 = new Base64(0, null); // null lineSeparator same as saying no-chunking
encodedBytes = b64.encode(StringUtils.getBytesUtf8(content));
encodedContent = StringUtils.newStringUtf8(encodedBytes);
assertTrue("encoding hello world", encodedContent.equals("SGVsbG8gV29ybGQ="));
// bogus characters to decode (to skip actually)
byte[] decode = b64.decode("SGVsbG{יייייי}8gV29ybGQ=");
String decodeString = StringUtils.newStringUtf8(decode);
assertTrue("decode hello world", decodeString.equals("Hello World"));
}
/**
* Tests Base64.encodeBase64().
*/
public void testChunkedEncodeMultipleOf76() {
byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true);
// convert to "\r\n" so we're equal to the old openssl encoding test stored
// in Base64TestData.ENCODED_76_CHARS_PER_LINE:
String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n");
byte[] actualEncode = StringUtils.getBytesUtf8(actualResult);
assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode));
}
/**
* CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some non-BASE64 bytes
*/
public void testCodec68() {
byte[] x = new byte[]{'n', 'A', '=', '=', (byte) 0x9c};
Base64.decodeBase64(x);
}
public void testCodeInteger1() throws UnsupportedEncodingException {
String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU=";
BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981");
assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1)));
assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes("UTF-8")));
}
public void testCodeInteger2() throws UnsupportedEncodingException {
String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs=";
BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611");
assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2)));
assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes("UTF-8")));
}
public void testCodeInteger3() throws UnsupportedEncodingException {
String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg==";
BigInteger bigInt3 = new BigInteger("10806548154093873461951748545"
+ "1196989136416448805819079363524309897749044958112417136240557"
+ "4495062430572478766856090958495998158114332651671116876320938126");
assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3)));
assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes("UTF-8")));
}
public void testCodeInteger4() throws UnsupportedEncodingException {
String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI"
+ "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o"
+ "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv"
+ "Q0=";
BigInteger bigInt4 = new BigInteger("80624726256040348115552042320"
+ "6968135001872753709424419772586693950232350200555646471175944"
+ "519297087885987040810778908507262272892702303774422853675597"
+ "748008534040890923814202286633163248086055216976551456088015"
+ "338880713818192088877057717530169381044092839402438015097654"
+ "53542091716518238707344493641683483917");
assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4)));
assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes("UTF-8")));
}
public void testCodeIntegerEdgeCases() {
// TODO
}
public void testCodeIntegerNull() {
try {
Base64.encodeInteger(null);
fail("Exception not thrown when passing in null to encodeInteger(BigInteger)");
} catch (NullPointerException npe) {
// expected
} catch (Exception e) {
fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)");
}
}
public void testConstructors() {
Base64 base64;
base64 = new Base64();
base64 = new Base64(-1);
base64 = new Base64(-1, new byte[]{});
base64 = new Base64(64, new byte[]{});
try {
base64 = new Base64(-1, new byte[]{'A'});
fail("Should have rejected attempt to use 'A' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
try {
base64 = new Base64(64, new byte[]{'A'});
fail("Should have rejected attempt to use 'A' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
try {
base64 = new Base64(64, new byte[]{'='});
fail("Should have rejected attempt to use '=' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
base64 = new Base64(64, new byte[]{'$'}); // OK
try {
base64 = new Base64(64, new byte[]{'A', '$'});
fail("Should have rejected attempt to use 'A$' as a line separator");
} catch (IllegalArgumentException ignored) {
// Expected
}
base64 = new Base64(64, new byte[]{' ', '$', '\n', '\r', '\t'}); // OK
}
public void testConstructor_Int_ByteArray_Boolean() {
Base64 base64 = new Base64(65, new byte[]{'\t'}, false);
byte[] encoded = base64.encode(Base64TestData.DECODED);
String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE;
expectedResult = expectedResult.replace('\n', '\t');
String result = StringUtils.newStringUtf8(encoded);
assertEquals("new Base64(65, \\t, false)", expectedResult, result);
}
public void testConstructor_Int_ByteArray_Boolean_UrlSafe() {
// url-safe variation
Base64 base64 = new Base64(64, new byte[]{'\t'}, true);
byte[] encoded = base64.encode(Base64TestData.DECODED);
String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE;
expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no == padding.
expectedResult = expectedResult.replace('\n', '\t');
expectedResult = expectedResult.replace('+', '-');
expectedResult = expectedResult.replace('/', '_');
String result = StringUtils.newStringUtf8(encoded);
assertEquals("new Base64(64, \\t, true)", result, expectedResult);
}
/**
* Tests conditional true branch for "marker0" test.
*/
public void testDecodePadMarkerIndex2() throws UnsupportedEncodingException {
assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes("UTF-8"))));
}
/**
* Tests conditional branches for "marker1" test.
*/
public void testDecodePadMarkerIndex3() throws UnsupportedEncodingException {
assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes("UTF-8"))));
assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes("UTF-8"))));
}
public void testDecodePadOnly() throws UnsupportedEncodingException {
assertTrue(Base64.decodeBase64("====".getBytes("UTF-8")).length == 0);
assertEquals("", new String(Base64.decodeBase64("====".getBytes("UTF-8"))));
// Test truncated padding
assertTrue(Base64.decodeBase64("===".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("==".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("=".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("".getBytes("UTF-8")).length == 0);
}
public void testDecodePadOnlyChunked() throws UnsupportedEncodingException {
assertTrue(Base64.decodeBase64("====\n".getBytes("UTF-8")).length == 0);
assertEquals("", new String(Base64.decodeBase64("====\n".getBytes("UTF-8"))));
// Test truncated padding
assertTrue(Base64.decodeBase64("===\n".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("==\n".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("=\n".getBytes("UTF-8")).length == 0);
assertTrue(Base64.decodeBase64("\n".getBytes("UTF-8")).length == 0);
}
public void testDecodeWithWhitespace() throws Exception {
String orig = "I am a late night coder.";
byte[] encodedArray = Base64.encodeBase64(orig.getBytes("UTF-8"));
StringBuffer intermediate = new StringBuffer(new String(encodedArray));
intermediate.insert(2, ' ');
intermediate.insert(5, '\t');
intermediate.insert(10, '\r');
intermediate.insert(15, '\n');
byte[] encodedWithWS = intermediate.toString().getBytes("UTF-8");
byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS);
String dest = new String(decodedWithWS);
assertTrue("Dest string doesn't equal the original", dest.equals(orig));
}
public void testDiscardWhitespace() throws Exception {
String orig = "I am a late night coder.";
byte[] encodedArray = Base64.encodeBase64(orig.getBytes("UTF-8"));
StringBuffer intermediate = new StringBuffer(new String(encodedArray));
intermediate.insert(2, ' ');
intermediate.insert(5, '\t');
intermediate.insert(10, '\r');
intermediate.insert(15, '\n');
byte[] encodedWithWS = intermediate.toString().getBytes("UTF-8");
byte[] encodedNoWS = Base64.discardWhitespace(encodedWithWS);
byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS);
byte[] decodedNoWS = Base64.decodeBase64(encodedNoWS);
String destFromWS = new String(decodedWithWS);
String destFromNoWS = new String(decodedNoWS);
assertTrue("Dest string doesn't equal original", destFromWS.equals(orig));
assertTrue("Dest string doesn't equal original", destFromNoWS.equals(orig));
}
/**
* Test encode and decode of empty byte array.
*/
public void testEmptyBase64() {
byte[] empty = new byte[0];
byte[] result = Base64.encodeBase64(empty);
assertEquals("empty base64 encode", 0, result.length);
assertEquals("empty base64 encode", null, Base64.encodeBase64(null));
empty = new byte[0];
result = Base64.decodeBase64(empty);
assertEquals("empty base64 decode", 0, result.length);
assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null));
}
// encode/decode a large random array
public void testEncodeDecodeRandom() {
for (int i = 1; i < 5; i++) {
byte[] data = new byte[this.getRandom().nextInt(10000) + 1];
this.getRandom().nextBytes(data);
byte[] enc = Base64.encodeBase64(data);
assertTrue(Base64.isArrayByteBase64(enc));
byte[] data2 = Base64.decodeBase64(enc);
assertTrue(Arrays.equals(data, data2));
}
}
// encode/decode random arrays from size 0 to size 11
public void testEncodeDecodeSmall() {
for (int i = 0; i < 12; i++) {
byte[] data = new byte[i];
this.getRandom().nextBytes(data);
byte[] enc = Base64.encodeBase64(data);
assertTrue("\"" + (new String(enc)) + "\" is Base64 data.", Base64.isArrayByteBase64(enc));
byte[] data2 = Base64.decodeBase64(enc);
assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2));
}
}
public void testEncodeOverMaxSize() throws Exception {
testEncodeOverMaxSize(-1);
testEncodeOverMaxSize(0);
testEncodeOverMaxSize(1);
testEncodeOverMaxSize(2);
}
private void testEncodeOverMaxSize(int maxSize) throws Exception {
try {
Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize);
fail("Expected " + IllegalArgumentException.class.getName());
} catch (IllegalArgumentException e) {
// Expceted
}
}
public void testIgnoringNonBase64InDecode() throws Exception {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8"))));
}
public void testIsArrayByteBase64() {
assertFalse(Base64.isArrayByteBase64(new byte[]{Byte.MIN_VALUE}));
assertFalse(Base64.isArrayByteBase64(new byte[]{-125}));
assertFalse(Base64.isArrayByteBase64(new byte[]{-10}));
assertFalse(Base64.isArrayByteBase64(new byte[]{0}));
assertFalse(Base64.isArrayByteBase64(new byte[]{64, Byte.MAX_VALUE}));
assertFalse(Base64.isArrayByteBase64(new byte[]{Byte.MAX_VALUE}));
assertTrue(Base64.isArrayByteBase64(new byte[]{'A'}));
assertFalse(Base64.isArrayByteBase64(new byte[]{'A', Byte.MIN_VALUE}));
assertTrue(Base64.isArrayByteBase64(new byte[]{'A', 'Z', 'a'}));
assertTrue(Base64.isArrayByteBase64(new byte[]{'/', '=', '+'}));
assertFalse(Base64.isArrayByteBase64(new byte[]{'$'}));
}
/**
* Tests isUrlSafe.
*/
public void testIsUrlSafe() {
Base64 base64Standard = new Base64(false);
Base64 base64URLSafe = new Base64(true);
assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe());
assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe());
byte[] whiteSpace = {' ', '\n', '\r', '\t'};
assertTrue("Base64.isArrayByteBase64(whiteSpace)=true", Base64.isArrayByteBase64(whiteSpace));
}
public void testKnownDecodings() throws UnsupportedEncodingException {
assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64
.decodeBase64("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes("UTF-8"))));
assertEquals("It was the best of times, it was the worst of times.", new String(Base64
.decodeBase64("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes("UTF-8"))));
assertEquals("http://jakarta.apache.org/commmons", new String(Base64
.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes("UTF-8"))));
assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64
.decodeBase64("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes("UTF-8"))));
assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0="
.getBytes("UTF-8"))));
assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes("UTF-8"))));
}
public void testKnownEncodings() throws UnsupportedEncodingException {
assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String(Base64
.encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes("UTF-8"))));
assertEquals(
"YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n",
new String(
Base64
.encodeBase64Chunked("blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"
.getBytes("UTF-8"))));
assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String(Base64
.encodeBase64("It was the best of times, it was the worst of times.".getBytes("UTF-8"))));
assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64
.encodeBase64("http://jakarta.apache.org/commmons".getBytes("UTF-8"))));
assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String(Base64
.encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes("UTF-8"))));
assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }"
.getBytes("UTF-8"))));
assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes("UTF-8"))));
}
public void testNonBase64Test() throws Exception {
byte[] bArray = {'%'};
assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64
.isArrayByteBase64(bArray));
try {
Base64 b64 = new Base64();
byte[] result = b64.decode(bArray);
assertTrue("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters",
result.length == 0);
} catch (Exception e) {
fail("Exception was thrown when trying to decode "
+ "invalid base64 encoded data - RFC 2045 requires that all "
+ "non base64 character be discarded, an exception should not"
+ " have been thrown");
}
}
public void testObjectDecodeWithInvalidParameter() throws Exception {
Base64 b64 = new Base64();
try {
b64.decode(new Integer(5));
fail("decode(Object) didn't throw an exception when passed an Integer object");
} catch (DecoderException e) {
// ignored
}
}
public void testObjectDecodeWithValidParameter() throws Exception {
String original = "Hello World!";
Object o = Base64.encodeBase64(original.getBytes("UTF-8"));
Base64 b64 = new Base64();
Object oDecoded = b64.decode(o);
byte[] baDecoded = (byte[]) oDecoded;
String dest = new String(baDecoded);
assertTrue("dest string does not equal original", dest.equals(original));
}
public void testObjectEncodeWithInvalidParameter() throws Exception {
Base64 b64 = new Base64();
try {
b64.encode("Yadayadayada");
fail("encode(Object) didn't throw an exception when passed a String object");
} catch (EncoderException e) {
// Expected
}
}
public void testObjectEncodeWithValidParameter() throws Exception {
String original = "Hello World!";
Object origObj = original.getBytes("UTF-8");
Base64 b64 = new Base64();
Object oEncoded = b64.encode(origObj);
byte[] bArray = Base64.decodeBase64((byte[]) oEncoded);
String dest = new String(bArray);
assertTrue("dest string does not equal original", dest.equals(original));
}
public void testObjectEncode() throws Exception {
Base64 b64 = new Base64();
assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes("UTF-8"))));
}
public void testPairs() {
assertEquals("AAA=", new String(Base64.encodeBase64(new byte[]{0, 0})));
for (int i = -128; i <= 127; i++) {
byte test[] = {(byte) i, (byte) i};
assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test))));
}
}
/**
* Tests RFC 2045 section 2.1 CRLF definition.
*/
public void testRfc2045Section2Dot1CrLfDefinition() {
assertTrue(Arrays.equals(new byte[]{13, 10}, Base64.CHUNK_SEPARATOR));
}
/**
* Tests RFC 2045 section 6.8 chuck size definition.
*/
public void testRfc2045Section6Dot8ChunkSizeDefinition() {
assertEquals(76, Base64.MIME_CHUNK_SIZE);
}
/**
* Tests RFC 1421 section 4.3.2.4 chuck size definition.
*/
public void testRfc1421Section6Dot8ChunkSizeDefinition() {
assertEquals(64, Base64.PEM_CHUNK_SIZE);
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10Decode() {
assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("")));
assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==")));
assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=")));
assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v")));
assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==")));
assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=")));
assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy")));
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10DecodeWithCrLf() {
String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR);
assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF)));
assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF)));
assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF)));
assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF)));
assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF)));
assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF)));
assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF)));
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10Encode() {
assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8("")));
assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f")));
assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo")));
assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo")));
assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob")));
assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba")));
assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar")));
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10DecodeEncode() {
testDecodeEncode("");
//testDecodeEncode("Zg==");
//testDecodeEncode("Zm8=");
//testDecodeEncode("Zm9v");
//testDecodeEncode("Zm9vYg==");
//testDecodeEncode("Zm9vYmE=");
//testDecodeEncode("Zm9vYmFy");
}
private void testDecodeEncode(String encodedText) {
String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText));
String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText));
assertEquals(encodedText, encodedText2);
}
/**
* Tests RFC 4648 section 10 test vectors.
* <ul>
* <li>BASE64("") = ""</li>
* <li>BASE64("f") = "Zg=="</li>
* <li>BASE64("fo") = "Zm8="</li>
* <li>BASE64("foo") = "Zm9v"</li>
* <li>BASE64("foob") = "Zm9vYg=="</li>
* <li>BASE64("fooba") = "Zm9vYmE="</li>
* <li>BASE64("foobar") = "Zm9vYmFy"</li>
* </ul>
*
* @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/html/rfc4648</a>
*/
public void testRfc4648Section10EncodeDecode() {
testEncodeDecode("");
testEncodeDecode("f");
testEncodeDecode("fo");
testEncodeDecode("foo");
testEncodeDecode("foob");
testEncodeDecode("fooba");
testEncodeDecode("foobar");
}
private void testEncodeDecode(String plainText) {
String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText));
String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText));
assertEquals(plainText, decodedText);
}
public void testSingletons() {
assertEquals("AA==", new String(Base64.encodeBase64(new byte[]{(byte) 0})));
assertEquals("AQ==", new String(Base64.encodeBase64(new byte[]{(byte) 1})));
assertEquals("Ag==", new String(Base64.encodeBase64(new byte[]{(byte) 2})));
assertEquals("Aw==", new String(Base64.encodeBase64(new byte[]{(byte) 3})));
assertEquals("BA==", new String(Base64.encodeBase64(new byte[]{(byte) 4})));
assertEquals("BQ==", new String(Base64.encodeBase64(new byte[]{(byte) 5})));
assertEquals("Bg==", new String(Base64.encodeBase64(new byte[]{(byte) 6})));
assertEquals("Bw==", new String(Base64.encodeBase64(new byte[]{(byte) 7})));
assertEquals("CA==", new String(Base64.encodeBase64(new byte[]{(byte) 8})));
assertEquals("CQ==", new String(Base64.encodeBase64(new byte[]{(byte) 9})));
assertEquals("Cg==", new String(Base64.encodeBase64(new byte[]{(byte) 10})));
assertEquals("Cw==", new String(Base64.encodeBase64(new byte[]{(byte) 11})));
assertEquals("DA==", new String(Base64.encodeBase64(new byte[]{(byte) 12})));
assertEquals("DQ==", new String(Base64.encodeBase64(new byte[]{(byte) 13})));
assertEquals("Dg==", new String(Base64.encodeBase64(new byte[]{(byte) 14})));
assertEquals("Dw==", new String(Base64.encodeBase64(new byte[]{(byte) 15})));
assertEquals("EA==", new String(Base64.encodeBase64(new byte[]{(byte) 16})));
assertEquals("EQ==", new String(Base64.encodeBase64(new byte[]{(byte) 17})));
assertEquals("Eg==", new String(Base64.encodeBase64(new byte[]{(byte) 18})));
assertEquals("Ew==", new String(Base64.encodeBase64(new byte[]{(byte) 19})));
assertEquals("FA==", new String(Base64.encodeBase64(new byte[]{(byte) 20})));
assertEquals("FQ==", new String(Base64.encodeBase64(new byte[]{(byte) 21})));
assertEquals("Fg==", new String(Base64.encodeBase64(new byte[]{(byte) 22})));
assertEquals("Fw==", new String(Base64.encodeBase64(new byte[]{(byte) 23})));
assertEquals("GA==", new String(Base64.encodeBase64(new byte[]{(byte) 24})));
assertEquals("GQ==", new String(Base64.encodeBase64(new byte[]{(byte) 25})));
assertEquals("Gg==", new String(Base64.encodeBase64(new byte[]{(byte) 26})));
assertEquals("Gw==", new String(Base64.encodeBase64(new byte[]{(byte) 27})));
assertEquals("HA==", new String(Base64.encodeBase64(new byte[]{(byte) 28})));
assertEquals("HQ==", new String(Base64.encodeBase64(new byte[]{(byte) 29})));
assertEquals("Hg==", new String(Base64.encodeBase64(new byte[]{(byte) 30})));
assertEquals("Hw==", new String(Base64.encodeBase64(new byte[]{(byte) 31})));
assertEquals("IA==", new String(Base64.encodeBase64(new byte[]{(byte) 32})));
assertEquals("IQ==", new String(Base64.encodeBase64(new byte[]{(byte) 33})));
assertEquals("Ig==", new String(Base64.encodeBase64(new byte[]{(byte) 34})));
assertEquals("Iw==", new String(Base64.encodeBase64(new byte[]{(byte) 35})));
assertEquals("JA==", new String(Base64.encodeBase64(new byte[]{(byte) 36})));
assertEquals("JQ==", new String(Base64.encodeBase64(new byte[]{(byte) 37})));
assertEquals("Jg==", new String(Base64.encodeBase64(new byte[]{(byte) 38})));
assertEquals("Jw==", new String(Base64.encodeBase64(new byte[]{(byte) 39})));
assertEquals("KA==", new String(Base64.encodeBase64(new byte[]{(byte) 40})));
assertEquals("KQ==", new String(Base64.encodeBase64(new byte[]{(byte) 41})));
assertEquals("Kg==", new String(Base64.encodeBase64(new byte[]{(byte) 42})));
assertEquals("Kw==", new String(Base64.encodeBase64(new byte[]{(byte) 43})));
assertEquals("LA==", new String(Base64.encodeBase64(new byte[]{(byte) 44})));
assertEquals("LQ==", new String(Base64.encodeBase64(new byte[]{(byte) 45})));
assertEquals("Lg==", new String(Base64.encodeBase64(new byte[]{(byte) 46})));
assertEquals("Lw==", new String(Base64.encodeBase64(new byte[]{(byte) 47})));
assertEquals("MA==", new String(Base64.encodeBase64(new byte[]{(byte) 48})));
assertEquals("MQ==", new String(Base64.encodeBase64(new byte[]{(byte) 49})));
assertEquals("Mg==", new String(Base64.encodeBase64(new byte[]{(byte) 50})));
assertEquals("Mw==", new String(Base64.encodeBase64(new byte[]{(byte) 51})));
assertEquals("NA==", new String(Base64.encodeBase64(new byte[]{(byte) 52})));
assertEquals("NQ==", new String(Base64.encodeBase64(new byte[]{(byte) 53})));
assertEquals("Ng==", new String(Base64.encodeBase64(new byte[]{(byte) 54})));
assertEquals("Nw==", new String(Base64.encodeBase64(new byte[]{(byte) 55})));
assertEquals("OA==", new String(Base64.encodeBase64(new byte[]{(byte) 56})));
assertEquals("OQ==", new String(Base64.encodeBase64(new byte[]{(byte) 57})));
assertEquals("Og==", new String(Base64.encodeBase64(new byte[]{(byte) 58})));
assertEquals("Ow==", new String(Base64.encodeBase64(new byte[]{(byte) 59})));
assertEquals("PA==", new String(Base64.encodeBase64(new byte[]{(byte) 60})));
assertEquals("PQ==", new String(Base64.encodeBase64(new byte[]{(byte) 61})));
assertEquals("Pg==", new String(Base64.encodeBase64(new byte[]{(byte) 62})));
assertEquals("Pw==", new String(Base64.encodeBase64(new byte[]{(byte) 63})));
assertEquals("QA==", new String(Base64.encodeBase64(new byte[]{(byte) 64})));
assertEquals("QQ==", new String(Base64.encodeBase64(new byte[]{(byte) 65})));
assertEquals("Qg==", new String(Base64.encodeBase64(new byte[]{(byte) 66})));
assertEquals("Qw==", new String(Base64.encodeBase64(new byte[]{(byte) 67})));
assertEquals("RA==", new String(Base64.encodeBase64(new byte[]{(byte) 68})));
assertEquals("RQ==", new String(Base64.encodeBase64(new byte[]{(byte) 69})));
assertEquals("Rg==", new String(Base64.encodeBase64(new byte[]{(byte) 70})));
assertEquals("Rw==", new String(Base64.encodeBase64(new byte[]{(byte) 71})));
assertEquals("SA==", new String(Base64.encodeBase64(new byte[]{(byte) 72})));
assertEquals("SQ==", new String(Base64.encodeBase64(new byte[]{(byte) 73})));
assertEquals("Sg==", new String(Base64.encodeBase64(new byte[]{(byte) 74})));
assertEquals("Sw==", new String(Base64.encodeBase64(new byte[]{(byte) 75})));
assertEquals("TA==", new String(Base64.encodeBase64(new byte[]{(byte) 76})));
assertEquals("TQ==", new String(Base64.encodeBase64(new byte[]{(byte) 77})));
assertEquals("Tg==", new String(Base64.encodeBase64(new byte[]{(byte) 78})));
assertEquals("Tw==", new String(Base64.encodeBase64(new byte[]{(byte) 79})));
assertEquals("UA==", new String(Base64.encodeBase64(new byte[]{(byte) 80})));
assertEquals("UQ==", new String(Base64.encodeBase64(new byte[]{(byte) 81})));
assertEquals("Ug==", new String(Base64.encodeBase64(new byte[]{(byte) 82})));
assertEquals("Uw==", new String(Base64.encodeBase64(new byte[]{(byte) 83})));
assertEquals("VA==", new String(Base64.encodeBase64(new byte[]{(byte) 84})));
assertEquals("VQ==", new String(Base64.encodeBase64(new byte[]{(byte) 85})));
assertEquals("Vg==", new String(Base64.encodeBase64(new byte[]{(byte) 86})));
assertEquals("Vw==", new String(Base64.encodeBase64(new byte[]{(byte) 87})));
assertEquals("WA==", new String(Base64.encodeBase64(new byte[]{(byte) 88})));
assertEquals("WQ==", new String(Base64.encodeBase64(new byte[]{(byte) 89})));
assertEquals("Wg==", new String(Base64.encodeBase64(new byte[]{(byte) 90})));
assertEquals("Ww==", new String(Base64.encodeBase64(new byte[]{(byte) 91})));
assertEquals("XA==", new String(Base64.encodeBase64(new byte[]{(byte) 92})));
assertEquals("XQ==", new String(Base64.encodeBase64(new byte[]{(byte) 93})));
assertEquals("Xg==", new String(Base64.encodeBase64(new byte[]{(byte) 94})));
assertEquals("Xw==", new String(Base64.encodeBase64(new byte[]{(byte) 95})));
assertEquals("YA==", new String(Base64.encodeBase64(new byte[]{(byte) 96})));
assertEquals("YQ==", new String(Base64.encodeBase64(new byte[]{(byte) 97})));
assertEquals("Yg==", new String(Base64.encodeBase64(new byte[]{(byte) 98})));
assertEquals("Yw==", new String(Base64.encodeBase64(new byte[]{(byte) 99})));
assertEquals("ZA==", new String(Base64.encodeBase64(new byte[]{(byte) 100})));
assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[]{(byte) 101})));
assertEquals("Zg==", new String(Base64.encodeBase64(new byte[]{(byte) 102})));
assertEquals("Zw==", new String(Base64.encodeBase64(new byte[]{(byte) 103})));
assertEquals("aA==", new String(Base64.encodeBase64(new byte[]{(byte) 104})));
for (int i = -128; i <= 127; i++) {
byte test[] = {(byte) i};
assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test))));
}
}
public void testSingletonsChunked() {
assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0})));
assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 1})));
assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 2})));
assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 3})));
assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 4})));
assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 5})));
assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 6})));
assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 7})));
assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 8})));
assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 9})));
assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 10})));
assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 11})));
assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 12})));
assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 13})));
assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 14})));
assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 15})));
assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 16})));
assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 17})));
assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 18})));
assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 19})));
assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 20})));
assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 21})));
assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 22})));
assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 23})));
assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 24})));
assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 25})));
assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 26})));
assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 27})));
assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 28})));
assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 29})));
assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 30})));
assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 31})));
assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 32})));
assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 33})));
assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 34})));
assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 35})));
assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 36})));
assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 37})));
assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 38})));
assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 39})));
assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 40})));
assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 41})));
assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 42})));
assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 43})));
assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 44})));
assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 45})));
assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 46})));
assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 47})));
assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 48})));
assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 49})));
assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 50})));
assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 51})));
assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 52})));
assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 53})));
assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 54})));
assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 55})));
assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 56})));
assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 57})));
assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 58})));
assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 59})));
assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 60})));
assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 61})));
assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 62})));
assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 63})));
assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 64})));
assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 65})));
assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 66})));
assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 67})));
assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 68})));
assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 69})));
assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 70})));
assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 71})));
assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 72})));
assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 73})));
assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 74})));
assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 75})));
assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 76})));
assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 77})));
assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 78})));
assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 79})));
assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 80})));
assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 81})));
assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 82})));
assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 83})));
assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 84})));
assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 85})));
assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 86})));
assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 87})));
assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 88})));
assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 89})));
assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 90})));
assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 91})));
assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 92})));
assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 93})));
assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 94})));
assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 95})));
assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 96})));
assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 97})));
assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 98})));
assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 99})));
assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 100})));
assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 101})));
assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 102})));
assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 103})));
assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 104})));
}
public void testTriplets() {
assertEquals("AAAA", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 0})));
assertEquals("AAAB", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 1})));
assertEquals("AAAC", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 2})));
assertEquals("AAAD", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 3})));
assertEquals("AAAE", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 4})));
assertEquals("AAAF", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 5})));
assertEquals("AAAG", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 6})));
assertEquals("AAAH", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 7})));
assertEquals("AAAI", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 8})));
assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 9})));
assertEquals("AAAK", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 10})));
assertEquals("AAAL", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 11})));
assertEquals("AAAM", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 12})));
assertEquals("AAAN", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 13})));
assertEquals("AAAO", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 14})));
assertEquals("AAAP", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 15})));
assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 16})));
assertEquals("AAAR", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 17})));
assertEquals("AAAS", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 18})));
assertEquals("AAAT", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 19})));
assertEquals("AAAU", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 20})));
assertEquals("AAAV", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 21})));
assertEquals("AAAW", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 22})));
assertEquals("AAAX", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 23})));
assertEquals("AAAY", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 24})));
assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 25})));
assertEquals("AAAa", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 26})));
assertEquals("AAAb", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 27})));
assertEquals("AAAc", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 28})));
assertEquals("AAAd", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 29})));
assertEquals("AAAe", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 30})));
assertEquals("AAAf", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 31})));
assertEquals("AAAg", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 32})));
assertEquals("AAAh", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 33})));
assertEquals("AAAi", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 34})));
assertEquals("AAAj", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 35})));
assertEquals("AAAk", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 36})));
assertEquals("AAAl", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 37})));
assertEquals("AAAm", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 38})));
assertEquals("AAAn", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 39})));
assertEquals("AAAo", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 40})));
assertEquals("AAAp", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 41})));
assertEquals("AAAq", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 42})));
assertEquals("AAAr", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 43})));
assertEquals("AAAs", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 44})));
assertEquals("AAAt", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 45})));
assertEquals("AAAu", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 46})));
assertEquals("AAAv", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 47})));
assertEquals("AAAw", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 48})));
assertEquals("AAAx", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 49})));
assertEquals("AAAy", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 50})));
assertEquals("AAAz", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 51})));
assertEquals("AAA0", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 52})));
assertEquals("AAA1", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 53})));
assertEquals("AAA2", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 54})));
assertEquals("AAA3", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 55})));
assertEquals("AAA4", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 56})));
assertEquals("AAA5", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 57})));
assertEquals("AAA6", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 58})));
assertEquals("AAA7", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 59})));
assertEquals("AAA8", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 60})));
assertEquals("AAA9", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 61})));
assertEquals("AAA+", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 62})));
assertEquals("AAA/", new String(Base64.encodeBase64(new byte[]{(byte) 0, (byte) 0, (byte) 63})));
}
public void testTripletsChunked() {
assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 0})));
assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 1})));
assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 2})));
assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 3})));
assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 4})));
assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 5})));
assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 6})));
assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 7})));
assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 8})));
assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 9})));
assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 10})));
assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 11})));
assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 12})));
assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 13})));
assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 14})));
assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 15})));
assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 16})));
assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 17})));
assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 18})));
assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 19})));
assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 20})));
assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 21})));
assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 22})));
assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 23})));
assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 24})));
assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 25})));
assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 26})));
assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 27})));
assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 28})));
assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 29})));
assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 30})));
assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 31})));
assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 32})));
assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 33})));
assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 34})));
assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 35})));
assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 36})));
assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 37})));
assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 38})));
assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 39})));
assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 40})));
assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 41})));
assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 42})));
assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 43})));
assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 44})));
assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 45})));
assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 46})));
assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 47})));
assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 48})));
assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 49})));
assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 50})));
assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 51})));
assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 52})));
assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 53})));
assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 54})));
assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 55})));
assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 56})));
assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 57})));
assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 58})));
assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 59})));
assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 60})));
assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 61})));
assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 62})));
assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[]{(byte) 0, (byte) 0, (byte) 63})));
}
/**
* Tests url-safe Base64 against random data, sizes 0 to 150.
*/
public void testUrlSafe() {
// test random data of sizes 0 thru 150
for (int i = 0; i <= 150; i++) {
byte[][] randomData = Base64TestData.randomData(i, true);
byte[] encoded = randomData[1];
byte[] decoded = randomData[0];
byte[] result = Base64.decodeBase64(encoded);
assertTrue("url-safe i=" + i, Arrays.equals(decoded, result));
assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '='));
assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\'));
assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+'));
}
}
/**
* Base64 encoding of UUID's is a common use-case, especially in URL-SAFE mode. This test case ends up being the
* "URL-SAFE" JUnit's.
*
* @throws DecoderException
* if Hex.decode() fails - a serious problem since Hex comes from our own commons-codec!
*/
public void testUUID() throws DecoderException {
// The 4 UUID's below contains mixtures of + and / to help us test the
// URL-SAFE encoding mode.
byte[][] ids = new byte[4][];
// ids[0] was chosen so that it encodes with at least one +.
ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370".toCharArray());
// ids[1] was chosen so that it encodes with both / and +.
ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray());
// ids[2] was chosen so that it encodes with at least one /.
ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca".toCharArray());
// ids[3] was chosen so that it encodes with both / and +, with /
// right at the beginning.
ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8".toCharArray());
byte[][] standard = new byte[4][];
standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA==");
standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA==");
standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg==");
standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A==");
byte[][] urlSafe1 = new byte[4][];
// regular padding (two '==' signs).
urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA==");
urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA==");
urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg==");
urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A==");
byte[][] urlSafe2 = new byte[4][];
// single padding (only one '=' sign).
urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=");
urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=");
urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=");
urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=");
byte[][] urlSafe3 = new byte[4][];
// no padding (no '=' signs).
urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA");
urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA");
urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg");
urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A");
for (int i = 0; i < 4; i++) {
byte[] encodedStandard = Base64.encodeBase64(ids[i]);
byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]);
byte[] decodedStandard = Base64.decodeBase64(standard[i]);
byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]);
byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]);
byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]);
// Very important debugging output should anyone
// ever need to delve closely into this stuff.
if (false) {
System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]");
System.out.println("standard: [" +
Hex.encodeHexString(decodedStandard) +
"] From: [" +
StringUtils.newStringUtf8(standard[i]) +
"]");
System.out.println("safe1: [" +
Hex.encodeHexString(decodedUrlSafe1) +
"] From: [" +
StringUtils.newStringUtf8(urlSafe1[i]) +
"]");
System.out.println("safe2: [" +
Hex.encodeHexString(decodedUrlSafe2) +
"] From: [" +
StringUtils.newStringUtf8(urlSafe2[i]) +
"]");
System.out.println("safe3: [" +
Hex.encodeHexString(decodedUrlSafe3) +
"] From: [" +
StringUtils.newStringUtf8(urlSafe3[i]) +
"]");
}
assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i]));
assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i]));
assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i]));
assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i]));
assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i]));
assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i]));
}
}
public void testByteToStringVariations() throws DecoderException {
Base64 base64 = new Base64(0);
byte[] b1 = StringUtils.getBytesUtf8("Hello World");
byte[] b2 = new byte[0];
byte[] b3 = null;
byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests
assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1));
assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1));
assertEquals("byteToString \"\"", "", base64.encodeToString(b2));
assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2));
assertEquals("byteToString null", null, base64.encodeToString(b3));
assertEquals("byteToString static null", null, Base64.encodeBase64String(b3));
assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4));
assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4));
assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4));
}
public void testStringToByteVariations() throws DecoderException {
Base64 base64 = new Base64();
String s1 = "SGVsbG8gV29ybGQ=\r\n";
String s2 = "";
String s3 = null;
String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n";
String s4b = "K_fMJwH-Q5e0nr7tWsxwkA";
byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090".toCharArray()); // for url-safe tests
assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1)));
assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[])base64.decode((Object)s1)));
assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1)));
assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2)));
assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2)));
assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3)));
assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3)));
assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b)));
assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a)));
assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b)));
}
private String toString(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
buf.append(data[i]);
if (i != data.length - 1) {
buf.append(",");
}
}
return buf.toString();
}
} |
||
public void testJavaVersionAsInt() {
assertEquals(0, SystemUtils.toJavaVersionInt(null));
assertEquals(0, SystemUtils.toJavaVersionInt(""));
assertEquals(0, SystemUtils.toJavaVersionInt("0"));
assertEquals(110, SystemUtils.toJavaVersionInt("1.1"));
assertEquals(120, SystemUtils.toJavaVersionInt("1.2"));
assertEquals(130, SystemUtils.toJavaVersionInt("1.3.0"));
assertEquals(131, SystemUtils.toJavaVersionInt("1.3.1"));
assertEquals(140, SystemUtils.toJavaVersionInt("1.4.0"));
assertEquals(141, SystemUtils.toJavaVersionInt("1.4.1"));
assertEquals(142, SystemUtils.toJavaVersionInt("1.4.2"));
assertEquals(150, SystemUtils.toJavaVersionInt("1.5.0"));
assertEquals(160, SystemUtils.toJavaVersionInt("1.6.0"));
assertEquals(131, SystemUtils.toJavaVersionInt("JavaVM-1.3.1"));
assertEquals(131, SystemUtils.toJavaVersionInt("1.3.1 subset"));
// This used to return 0f in [lang] version 2.5:
assertEquals(130, SystemUtils.toJavaVersionInt("XXX-1.3.x"));
} | org.apache.commons.lang3.SystemUtilsTest::testJavaVersionAsInt | src/test/java/org/apache/commons/lang3/SystemUtilsTest.java | 225 | src/test/java/org/apache/commons/lang3/SystemUtilsTest.java | testJavaVersionAsInt | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.lang3;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Locale;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Unit tests {@link org.apache.commons.lang3.SystemUtils}.
*
* Only limited testing can be performed.
*
* @author Apache Software Foundation
* @author Tetsuya Kaneuchi
* @author Gary D. Gregory
* @version $Id$
*/
public class SystemUtilsTest extends TestCase {
public SystemUtilsTest(String name) {
super(name);
}
public void testConstructor() {
assertNotNull(new SystemUtils());
Constructor<?>[] cons = SystemUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
assertEquals(true, Modifier.isPublic(SystemUtils.class.getModifiers()));
assertEquals(false, Modifier.isFinal(SystemUtils.class.getModifiers()));
}
/**
* Assums no security manager exists.
*/
public void testGetJavaHome() {
File dir = SystemUtils.getJavaHome();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
/**
* Assums no security manager exists.
*/
public void testGetJavaIoTmpDir() {
File dir = SystemUtils.getJavaIoTmpDir();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
/**
* Assums no security manager exists.
*/
public void testGetUserDir() {
File dir = SystemUtils.getUserDir();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
/**
* Assums no security manager exists.
*/
public void testGetUserHome() {
File dir = SystemUtils.getUserHome();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
public void testIS_JAVA() {
String javaVersion = System.getProperty("java.version");
if (javaVersion == null) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.1")) {
assertEquals(true, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.2")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(true, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.3")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(true, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.4")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(true, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.5")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(true, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.6")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(true, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else {
System.out.println("Can't test IS_JAVA value");
}
}
public void testIS_OS() {
String osName = System.getProperty("os.name");
if (osName == null) {
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
assertEquals(false, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_SOLARIS);
assertEquals(false, SystemUtils.IS_OS_LINUX);
assertEquals(false, SystemUtils.IS_OS_MAC_OSX);
} else if (osName.startsWith("Windows")) {
assertEquals(false, SystemUtils.IS_OS_UNIX);
assertEquals(true, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("Solaris")) {
assertEquals(true, SystemUtils.IS_OS_SOLARIS);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.toLowerCase(Locale.ENGLISH).startsWith("linux")) {
assertEquals(true, SystemUtils.IS_OS_LINUX);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("Mac OS X")) {
assertEquals(true, SystemUtils.IS_OS_MAC_OSX);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("OS/2")) {
assertEquals(true, SystemUtils.IS_OS_OS2);
assertEquals(false, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("SunOS")) {
assertEquals(true, SystemUtils.IS_OS_SUN_OS);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else {
System.out.println("Can't test IS_OS value");
}
}
public void testJavaVersionAsFloat() {
assertEquals(0f, SystemUtils.toJavaVersionFloat(null), 0.000001f);
assertEquals(0f, SystemUtils.toJavaVersionFloat(""), 0.000001f);
assertEquals(0f, SystemUtils.toJavaVersionFloat("0"), 0.000001f);
assertEquals(1.1f, SystemUtils.toJavaVersionFloat("1.1"), 0.000001f);
assertEquals(1.2f, SystemUtils.toJavaVersionFloat("1.2"), 0.000001f);
assertEquals(1.3f, SystemUtils.toJavaVersionFloat("1.3.0"), 0.000001f);
assertEquals(1.31f, SystemUtils.toJavaVersionFloat("1.3.1"), 0.000001f);
assertEquals(1.4f, SystemUtils.toJavaVersionFloat("1.4.0"), 0.000001f);
assertEquals(1.41f, SystemUtils.toJavaVersionFloat("1.4.1"), 0.000001f);
assertEquals(1.42f, SystemUtils.toJavaVersionFloat("1.4.2"), 0.000001f);
assertEquals(1.5f, SystemUtils.toJavaVersionFloat("1.5.0"), 0.000001f);
assertEquals(1.6f, SystemUtils.toJavaVersionFloat("1.6.0"), 0.000001f);
assertEquals(1.31f, SystemUtils.toJavaVersionFloat("JavaVM-1.3.1"), 0.000001f);
assertEquals(1.3f, SystemUtils.toJavaVersionFloat("1.3.0 subset"), 0.000001f);
// This used to return 0f in [lang] version 2.5:
assertEquals(1.3f, SystemUtils.toJavaVersionFloat("XXX-1.3.x"), 0.000001f);
}
public void testJavaVersionAsInt() {
assertEquals(0, SystemUtils.toJavaVersionInt(null));
assertEquals(0, SystemUtils.toJavaVersionInt(""));
assertEquals(0, SystemUtils.toJavaVersionInt("0"));
assertEquals(110, SystemUtils.toJavaVersionInt("1.1"));
assertEquals(120, SystemUtils.toJavaVersionInt("1.2"));
assertEquals(130, SystemUtils.toJavaVersionInt("1.3.0"));
assertEquals(131, SystemUtils.toJavaVersionInt("1.3.1"));
assertEquals(140, SystemUtils.toJavaVersionInt("1.4.0"));
assertEquals(141, SystemUtils.toJavaVersionInt("1.4.1"));
assertEquals(142, SystemUtils.toJavaVersionInt("1.4.2"));
assertEquals(150, SystemUtils.toJavaVersionInt("1.5.0"));
assertEquals(160, SystemUtils.toJavaVersionInt("1.6.0"));
assertEquals(131, SystemUtils.toJavaVersionInt("JavaVM-1.3.1"));
assertEquals(131, SystemUtils.toJavaVersionInt("1.3.1 subset"));
// This used to return 0f in [lang] version 2.5:
assertEquals(130, SystemUtils.toJavaVersionInt("XXX-1.3.x"));
}
public void testJavaVersionAtLeastFloat() {
float version = SystemUtils.JAVA_VERSION_FLOAT;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version -= 0.1f;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version += 0.2f;
assertEquals(false, SystemUtils.isJavaVersionAtLeast(version));
}
public void testJavaVersionAtLeastInt() {
int version = SystemUtils.JAVA_VERSION_INT;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version -= 10;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version += 20;
assertEquals(false, SystemUtils.isJavaVersionAtLeast(version));
}
public void testJavaVersionMatches() {
String javaVersion = null;
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.0";
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.1";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.2";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.3.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.3.1";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.4.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.4.1";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.4.2";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.5.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.6.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.7.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
}
public void testOSMatchesName() {
String osName = null;
assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "";
assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "Windows 95";
assertEquals(true, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "Windows NT";
assertEquals(true, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "OS/2";
assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
}
public void testOSMatchesNameAndVersion() {
String osName = null;
String osVersion = null;
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "";
osVersion = "";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows 95";
osVersion = "4.0";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows 95";
osVersion = "4.1";
assertEquals(true, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows 98";
osVersion = "4.1";
assertEquals(true, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows NT";
osVersion = "4.0";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "OS/2";
osVersion = "4.0";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
}
public void testJavaAwtHeadless() {
boolean atLeastJava14 = SystemUtils.isJavaVersionAtLeast(140);
String expectedStringValue = System.getProperty("java.awt.headless");
String expectedStringValueWithDefault = System.getProperty("java.awt.headless", "false");
assertNotNull(expectedStringValueWithDefault);
if (atLeastJava14) {
boolean expectedValue = Boolean.valueOf(expectedStringValue).booleanValue();
if (expectedStringValue != null) {
assertEquals(expectedStringValue, SystemUtils.JAVA_AWT_HEADLESS);
}
assertEquals(expectedValue, SystemUtils.isJavaAwtHeadless());
} else {
assertNull(expectedStringValue);
assertNull(SystemUtils.JAVA_AWT_HEADLESS);
assertEquals(expectedStringValueWithDefault, "" + SystemUtils.isJavaAwtHeadless());
}
assertEquals(expectedStringValueWithDefault, "" + SystemUtils.isJavaAwtHeadless());
}
} | // You are a professional Java test case writer, please create a test case named `testJavaVersionAsInt` for the issue `Lang-LANG-624`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-624
//
// ## Issue-Title:
// SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM
//
// ## Issue-Description:
//
// Can be replicated in the Android emulator quite easily.
//
//
// Stack trace:
//
//
//
//
// ```
//
// at org.apache.commons.lang.builder.ToStringBuilder.<clinit>(ToStringBuilder.java:98)
// E/AndroidRuntime( 1681): ... 17 more
// E/AndroidRuntime( 1681): Caused by: java.lang.ExceptionInInitializerError
// E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.<init>(ToStringStyle.java:2276)
// E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle.<clinit>(ToStringStyle.java:94)
// E/AndroidRuntime( 1681): ... 18 more
// E/AndroidRuntime( 1681): Caused by: java.lang.StringIndexOutOfBoundsException
// E/AndroidRuntime( 1681): at java.lang.String.substring(String.java:1571)
// E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.getJavaVersionAsFloat(SystemUtils.java:1153)
// E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.<clinit>(SystemUtils.java:818)
//
// ```
//
//
//
//
//
public void testJavaVersionAsInt() {
| 225 | 29 | 208 | src/test/java/org/apache/commons/lang3/SystemUtilsTest.java | src/test/java | ```markdown
## Issue-ID: Lang-LANG-624
## Issue-Title:
SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM
## Issue-Description:
Can be replicated in the Android emulator quite easily.
Stack trace:
```
at org.apache.commons.lang.builder.ToStringBuilder.<clinit>(ToStringBuilder.java:98)
E/AndroidRuntime( 1681): ... 17 more
E/AndroidRuntime( 1681): Caused by: java.lang.ExceptionInInitializerError
E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.<init>(ToStringStyle.java:2276)
E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle.<clinit>(ToStringStyle.java:94)
E/AndroidRuntime( 1681): ... 18 more
E/AndroidRuntime( 1681): Caused by: java.lang.StringIndexOutOfBoundsException
E/AndroidRuntime( 1681): at java.lang.String.substring(String.java:1571)
E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.getJavaVersionAsFloat(SystemUtils.java:1153)
E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.<clinit>(SystemUtils.java:818)
```
```
You are a professional Java test case writer, please create a test case named `testJavaVersionAsInt` for the issue `Lang-LANG-624`, utilizing the provided issue report information and the following function signature.
```java
public void testJavaVersionAsInt() {
```
| 208 | [
"org.apache.commons.lang3.SystemUtils"
] | 4b6705adaca3d5a103e923b2ce5e54bf87d0d13c9f21f55d09d46aa8a1b5d47c | public void testJavaVersionAsInt() | // You are a professional Java test case writer, please create a test case named `testJavaVersionAsInt` for the issue `Lang-LANG-624`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-624
//
// ## Issue-Title:
// SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM
//
// ## Issue-Description:
//
// Can be replicated in the Android emulator quite easily.
//
//
// Stack trace:
//
//
//
//
// ```
//
// at org.apache.commons.lang.builder.ToStringBuilder.<clinit>(ToStringBuilder.java:98)
// E/AndroidRuntime( 1681): ... 17 more
// E/AndroidRuntime( 1681): Caused by: java.lang.ExceptionInInitializerError
// E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.<init>(ToStringStyle.java:2276)
// E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle.<clinit>(ToStringStyle.java:94)
// E/AndroidRuntime( 1681): ... 18 more
// E/AndroidRuntime( 1681): Caused by: java.lang.StringIndexOutOfBoundsException
// E/AndroidRuntime( 1681): at java.lang.String.substring(String.java:1571)
// E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.getJavaVersionAsFloat(SystemUtils.java:1153)
// E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.<clinit>(SystemUtils.java:818)
//
// ```
//
//
//
//
//
| Lang | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.lang3;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Locale;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Unit tests {@link org.apache.commons.lang3.SystemUtils}.
*
* Only limited testing can be performed.
*
* @author Apache Software Foundation
* @author Tetsuya Kaneuchi
* @author Gary D. Gregory
* @version $Id$
*/
public class SystemUtilsTest extends TestCase {
public SystemUtilsTest(String name) {
super(name);
}
public void testConstructor() {
assertNotNull(new SystemUtils());
Constructor<?>[] cons = SystemUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
assertEquals(true, Modifier.isPublic(SystemUtils.class.getModifiers()));
assertEquals(false, Modifier.isFinal(SystemUtils.class.getModifiers()));
}
/**
* Assums no security manager exists.
*/
public void testGetJavaHome() {
File dir = SystemUtils.getJavaHome();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
/**
* Assums no security manager exists.
*/
public void testGetJavaIoTmpDir() {
File dir = SystemUtils.getJavaIoTmpDir();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
/**
* Assums no security manager exists.
*/
public void testGetUserDir() {
File dir = SystemUtils.getUserDir();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
/**
* Assums no security manager exists.
*/
public void testGetUserHome() {
File dir = SystemUtils.getUserHome();
Assert.assertNotNull(dir);
Assert.assertTrue(dir.exists());
}
public void testIS_JAVA() {
String javaVersion = System.getProperty("java.version");
if (javaVersion == null) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.1")) {
assertEquals(true, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.2")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(true, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.3")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(true, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.4")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(true, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.5")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(true, SystemUtils.IS_JAVA_1_5);
assertEquals(false, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else if (javaVersion.startsWith("1.6")) {
assertEquals(false, SystemUtils.IS_JAVA_1_1);
assertEquals(false, SystemUtils.IS_JAVA_1_2);
assertEquals(false, SystemUtils.IS_JAVA_1_3);
assertEquals(false, SystemUtils.IS_JAVA_1_4);
assertEquals(false, SystemUtils.IS_JAVA_1_5);
assertEquals(true, SystemUtils.IS_JAVA_1_6);
assertEquals(false, SystemUtils.IS_JAVA_1_7);
} else {
System.out.println("Can't test IS_JAVA value");
}
}
public void testIS_OS() {
String osName = System.getProperty("os.name");
if (osName == null) {
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
assertEquals(false, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_SOLARIS);
assertEquals(false, SystemUtils.IS_OS_LINUX);
assertEquals(false, SystemUtils.IS_OS_MAC_OSX);
} else if (osName.startsWith("Windows")) {
assertEquals(false, SystemUtils.IS_OS_UNIX);
assertEquals(true, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("Solaris")) {
assertEquals(true, SystemUtils.IS_OS_SOLARIS);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.toLowerCase(Locale.ENGLISH).startsWith("linux")) {
assertEquals(true, SystemUtils.IS_OS_LINUX);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("Mac OS X")) {
assertEquals(true, SystemUtils.IS_OS_MAC_OSX);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("OS/2")) {
assertEquals(true, SystemUtils.IS_OS_OS2);
assertEquals(false, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else if (osName.startsWith("SunOS")) {
assertEquals(true, SystemUtils.IS_OS_SUN_OS);
assertEquals(true, SystemUtils.IS_OS_UNIX);
assertEquals(false, SystemUtils.IS_OS_WINDOWS);
} else {
System.out.println("Can't test IS_OS value");
}
}
public void testJavaVersionAsFloat() {
assertEquals(0f, SystemUtils.toJavaVersionFloat(null), 0.000001f);
assertEquals(0f, SystemUtils.toJavaVersionFloat(""), 0.000001f);
assertEquals(0f, SystemUtils.toJavaVersionFloat("0"), 0.000001f);
assertEquals(1.1f, SystemUtils.toJavaVersionFloat("1.1"), 0.000001f);
assertEquals(1.2f, SystemUtils.toJavaVersionFloat("1.2"), 0.000001f);
assertEquals(1.3f, SystemUtils.toJavaVersionFloat("1.3.0"), 0.000001f);
assertEquals(1.31f, SystemUtils.toJavaVersionFloat("1.3.1"), 0.000001f);
assertEquals(1.4f, SystemUtils.toJavaVersionFloat("1.4.0"), 0.000001f);
assertEquals(1.41f, SystemUtils.toJavaVersionFloat("1.4.1"), 0.000001f);
assertEquals(1.42f, SystemUtils.toJavaVersionFloat("1.4.2"), 0.000001f);
assertEquals(1.5f, SystemUtils.toJavaVersionFloat("1.5.0"), 0.000001f);
assertEquals(1.6f, SystemUtils.toJavaVersionFloat("1.6.0"), 0.000001f);
assertEquals(1.31f, SystemUtils.toJavaVersionFloat("JavaVM-1.3.1"), 0.000001f);
assertEquals(1.3f, SystemUtils.toJavaVersionFloat("1.3.0 subset"), 0.000001f);
// This used to return 0f in [lang] version 2.5:
assertEquals(1.3f, SystemUtils.toJavaVersionFloat("XXX-1.3.x"), 0.000001f);
}
public void testJavaVersionAsInt() {
assertEquals(0, SystemUtils.toJavaVersionInt(null));
assertEquals(0, SystemUtils.toJavaVersionInt(""));
assertEquals(0, SystemUtils.toJavaVersionInt("0"));
assertEquals(110, SystemUtils.toJavaVersionInt("1.1"));
assertEquals(120, SystemUtils.toJavaVersionInt("1.2"));
assertEquals(130, SystemUtils.toJavaVersionInt("1.3.0"));
assertEquals(131, SystemUtils.toJavaVersionInt("1.3.1"));
assertEquals(140, SystemUtils.toJavaVersionInt("1.4.0"));
assertEquals(141, SystemUtils.toJavaVersionInt("1.4.1"));
assertEquals(142, SystemUtils.toJavaVersionInt("1.4.2"));
assertEquals(150, SystemUtils.toJavaVersionInt("1.5.0"));
assertEquals(160, SystemUtils.toJavaVersionInt("1.6.0"));
assertEquals(131, SystemUtils.toJavaVersionInt("JavaVM-1.3.1"));
assertEquals(131, SystemUtils.toJavaVersionInt("1.3.1 subset"));
// This used to return 0f in [lang] version 2.5:
assertEquals(130, SystemUtils.toJavaVersionInt("XXX-1.3.x"));
}
public void testJavaVersionAtLeastFloat() {
float version = SystemUtils.JAVA_VERSION_FLOAT;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version -= 0.1f;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version += 0.2f;
assertEquals(false, SystemUtils.isJavaVersionAtLeast(version));
}
public void testJavaVersionAtLeastInt() {
int version = SystemUtils.JAVA_VERSION_INT;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version -= 10;
assertEquals(true, SystemUtils.isJavaVersionAtLeast(version));
version += 20;
assertEquals(false, SystemUtils.isJavaVersionAtLeast(version));
}
public void testJavaVersionMatches() {
String javaVersion = null;
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.0";
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.1";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.2";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.3.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.3.1";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.4.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.4.1";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.4.2";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.5.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.6.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
javaVersion = "1.7.0";
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.0"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.1"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.2"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.3"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.4"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.5"));
assertEquals(false, SystemUtils.isJavaVersionMatch(javaVersion, "1.6"));
assertEquals(true, SystemUtils.isJavaVersionMatch(javaVersion, "1.7"));
}
public void testOSMatchesName() {
String osName = null;
assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "";
assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "Windows 95";
assertEquals(true, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "Windows NT";
assertEquals(true, SystemUtils.isOSNameMatch(osName, "Windows"));
osName = "OS/2";
assertEquals(false, SystemUtils.isOSNameMatch(osName, "Windows"));
}
public void testOSMatchesNameAndVersion() {
String osName = null;
String osVersion = null;
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "";
osVersion = "";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows 95";
osVersion = "4.0";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows 95";
osVersion = "4.1";
assertEquals(true, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows 98";
osVersion = "4.1";
assertEquals(true, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "Windows NT";
osVersion = "4.0";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
osName = "OS/2";
osVersion = "4.0";
assertEquals(false, SystemUtils.isOSMatch(osName, osVersion, "Windows 9", "4.1"));
}
public void testJavaAwtHeadless() {
boolean atLeastJava14 = SystemUtils.isJavaVersionAtLeast(140);
String expectedStringValue = System.getProperty("java.awt.headless");
String expectedStringValueWithDefault = System.getProperty("java.awt.headless", "false");
assertNotNull(expectedStringValueWithDefault);
if (atLeastJava14) {
boolean expectedValue = Boolean.valueOf(expectedStringValue).booleanValue();
if (expectedStringValue != null) {
assertEquals(expectedStringValue, SystemUtils.JAVA_AWT_HEADLESS);
}
assertEquals(expectedValue, SystemUtils.isJavaAwtHeadless());
} else {
assertNull(expectedStringValue);
assertNull(SystemUtils.JAVA_AWT_HEADLESS);
assertEquals(expectedStringValueWithDefault, "" + SystemUtils.isJavaAwtHeadless());
}
assertEquals(expectedStringValueWithDefault, "" + SystemUtils.isJavaAwtHeadless());
}
} |
||
@Test public void handlesHeaderEncodingOnRequest() {
Connection.Request req = new HttpConnection.Request();
req.addHeader("xxx", "é");
} | org.jsoup.helper.HttpConnectionTest::handlesHeaderEncodingOnRequest | src/test/java/org/jsoup/helper/HttpConnectionTest.java | 256 | src/test/java/org/jsoup/helper/HttpConnectionTest.java | handlesHeaderEncodingOnRequest | package org.jsoup.helper;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.MultiLocaleRule;
import org.jsoup.MultiLocaleRule.MultiLocaleTest;
import org.jsoup.integration.ParseTest;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HttpConnectionTest {
/* most actual network http connection tests are in integration */
@Rule public MultiLocaleRule rule = new MultiLocaleRule();
@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 @MultiLocaleTest public void caseInsensitiveHeaders() {
Connection.Response res = new HttpConnection.Response();
res.header("Accept-Encoding", "gzip");
res.header("content-type", "text/html");
res.header("refErrer", "http://example.com");
assertTrue(res.hasHeader("Accept-Encoding"));
assertTrue(res.hasHeader("accept-encoding"));
assertTrue(res.hasHeader("accept-Encoding"));
assertTrue(res.hasHeader("ACCEPT-ENCODING"));
assertEquals("gzip", res.header("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.removeHeader("ACCEPT-ENCODING");
assertFalse(res.hasHeader("Accept-Encoding"));
res.header("ACCEPT-ENCODING", "deflate");
assertEquals("deflate", res.header("Accept-Encoding"));
assertEquals("deflate", res.header("accept-Encoding"));
}
@Test public void headers() {
Connection con = HttpConnection.connect("http://example.com");
Map<String, String> headers = new HashMap<>();
headers.put("content-type", "text/html");
headers.put("Connection", "keep-alive");
headers.put("Host", "http://example.com");
con.headers(headers);
assertEquals("text/html", con.request().header("content-type"));
assertEquals("keep-alive", con.request().header("Connection"));
assertEquals("http://example.com", con.request().header("Host"));
}
@Test public void sameHeadersCombineWithComma() {
Map<String, List<String>> headers = new HashMap<>();
List<String> values = new ArrayList<>();
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 multipleHeaders() {
Connection.Request req = new HttpConnection.Request();
req.addHeader("Accept", "Something");
req.addHeader("Accept", "Everything");
req.addHeader("Foo", "Bar");
assertTrue(req.hasHeader("Accept"));
assertTrue(req.hasHeader("ACCEpt"));
assertEquals("Something, Everything", req.header("accept"));
assertTrue(req.hasHeader("fOO"));
assertEquals("Bar", req.header("foo"));
List<String> accept = req.headers("accept");
assertEquals(2, accept.size());
assertEquals("Something", accept.get(0));
assertEquals("Everything", accept.get(1));
Map<String, List<String>> headers = req.multiHeaders();
assertEquals(accept, headers.get("Accept"));
assertEquals("Bar", headers.get("Foo").get(0));
assertTrue(req.hasHeader("Accept"));
assertTrue(req.hasHeaderWithValue("accept", "Something"));
assertTrue(req.hasHeaderWithValue("accept", "Everything"));
assertFalse(req.hasHeaderWithValue("accept", "Something for nothing"));
req.removeHeader("accept");
headers = req.multiHeaders();
assertEquals("Bar", headers.get("Foo").get(0));
assertFalse(req.hasHeader("Accept"));
assertTrue(headers.get("Accept") == null);
}
@Test public void ignoresEmptySetCookies() {
// prep http response header map
Map<String, List<String>> headers = new HashMap<>();
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<>();
List<String> cookieStrings = new ArrayList<>();
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/");
assertEquals(HttpConnection.DEFAULT_UA, con.request().header("User-Agent"));
con.userAgent("Mozilla");
assertEquals("Mozilla", con.request().header("User-Agent"));
}
@Test public void timeout() {
Connection con = HttpConnection.connect("http://example.com/");
assertEquals(30 * 1000, con.request().timeout());
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 throwsOnOddData() {
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());
}
@Test public void requestBody() {
Connection con = HttpConnection.connect("http://example.com/");
con.requestBody("foo");
assertEquals("foo", con.request().requestBody());
}
@Test public void encodeUrl() throws MalformedURLException {
URL url1 = new URL("http://test.com/?q=white space");
URL url2 = HttpConnection.encodeUrl(url1);
assertEquals("http://test.com/?q=white%20space", url2.toExternalForm());
}
@Test public void noUrlThrowsValidationError() throws IOException {
HttpConnection con = new HttpConnection();
boolean threw = false;
try {
con.execute();
} catch (IllegalArgumentException e) {
threw = true;
assertEquals("URL must be specified to connect", e.getMessage());
}
assertTrue(threw);
}
@Test public void handlesHeaderEncodingOnRequest() {
Connection.Request req = new HttpConnection.Request();
req.addHeader("xxx", "é");
}
} | // You are a professional Java test case writer, please create a test case named `handlesHeaderEncodingOnRequest` for the issue `Jsoup-1172`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-1172
//
// ## Issue-Title:
// ArrayIndexOutOfBoundsException when parsing with some URL
//
// ## Issue-Description:
// ### error
//
//
//
// ```
// Caused by: java.lang.ArrayIndexOutOfBoundsException: 11
// at org.jsoup.helper.HttpConnection$Base.looksLikeUtf8(HttpConnection.java:437)
// at org.jsoup.helper.HttpConnection$Base.fixHeaderEncoding(HttpConnection.java:400)
// at org.jsoup.helper.HttpConnection$Base.addHeader(HttpConnection.java:386)
// at org.jsoup.helper.HttpConnection$Response.processResponseHeaders(HttpConnection.java:1075)
// at org.jsoup.helper.HttpConnection$Response.setupFromConnection(HttpConnection.java:1019)
// at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:752)
// at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:722)
// at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:306)
//
// ```
//
// ### code
//
//
//
// ```
// try {
// String url = "https://www.colisprive.com/moncolis/pages/detailColis.aspx?numColis=P4000000037777930";
// Connection connection = Jsoup.connect(url).referrer(url).
// userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
// .ignoreContentType(true).timeout(20000);
//
// connection.method(Method.GET);
// return connection.execute().parse();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
//
// ```
//
//
//
@Test public void handlesHeaderEncodingOnRequest() {
| 256 | 90 | 253 | src/test/java/org/jsoup/helper/HttpConnectionTest.java | src/test/java | ```markdown
## Issue-ID: Jsoup-1172
## Issue-Title:
ArrayIndexOutOfBoundsException when parsing with some URL
## Issue-Description:
### error
```
Caused by: java.lang.ArrayIndexOutOfBoundsException: 11
at org.jsoup.helper.HttpConnection$Base.looksLikeUtf8(HttpConnection.java:437)
at org.jsoup.helper.HttpConnection$Base.fixHeaderEncoding(HttpConnection.java:400)
at org.jsoup.helper.HttpConnection$Base.addHeader(HttpConnection.java:386)
at org.jsoup.helper.HttpConnection$Response.processResponseHeaders(HttpConnection.java:1075)
at org.jsoup.helper.HttpConnection$Response.setupFromConnection(HttpConnection.java:1019)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:752)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:722)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:306)
```
### code
```
try {
String url = "https://www.colisprive.com/moncolis/pages/detailColis.aspx?numColis=P4000000037777930";
Connection connection = Jsoup.connect(url).referrer(url).
userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
.ignoreContentType(true).timeout(20000);
connection.method(Method.GET);
return connection.execute().parse();
} catch (Exception e) {
throw new RuntimeException(e);
}
```
```
You are a professional Java test case writer, please create a test case named `handlesHeaderEncodingOnRequest` for the issue `Jsoup-1172`, utilizing the provided issue report information and the following function signature.
```java
@Test public void handlesHeaderEncodingOnRequest() {
```
| 253 | [
"org.jsoup.helper.HttpConnection"
] | 4bf60726598bb065e9323390e4bafdeeb5d0a6764bd425090ac8e8a794b8dce5 | @Test public void handlesHeaderEncodingOnRequest() | // You are a professional Java test case writer, please create a test case named `handlesHeaderEncodingOnRequest` for the issue `Jsoup-1172`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-1172
//
// ## Issue-Title:
// ArrayIndexOutOfBoundsException when parsing with some URL
//
// ## Issue-Description:
// ### error
//
//
//
// ```
// Caused by: java.lang.ArrayIndexOutOfBoundsException: 11
// at org.jsoup.helper.HttpConnection$Base.looksLikeUtf8(HttpConnection.java:437)
// at org.jsoup.helper.HttpConnection$Base.fixHeaderEncoding(HttpConnection.java:400)
// at org.jsoup.helper.HttpConnection$Base.addHeader(HttpConnection.java:386)
// at org.jsoup.helper.HttpConnection$Response.processResponseHeaders(HttpConnection.java:1075)
// at org.jsoup.helper.HttpConnection$Response.setupFromConnection(HttpConnection.java:1019)
// at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:752)
// at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:722)
// at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:306)
//
// ```
//
// ### code
//
//
//
// ```
// try {
// String url = "https://www.colisprive.com/moncolis/pages/detailColis.aspx?numColis=P4000000037777930";
// Connection connection = Jsoup.connect(url).referrer(url).
// userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
// .ignoreContentType(true).timeout(20000);
//
// connection.method(Method.GET);
// return connection.execute().parse();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
//
// ```
//
//
//
| Jsoup | package org.jsoup.helper;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.MultiLocaleRule;
import org.jsoup.MultiLocaleRule.MultiLocaleTest;
import org.jsoup.integration.ParseTest;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class HttpConnectionTest {
/* most actual network http connection tests are in integration */
@Rule public MultiLocaleRule rule = new MultiLocaleRule();
@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 @MultiLocaleTest public void caseInsensitiveHeaders() {
Connection.Response res = new HttpConnection.Response();
res.header("Accept-Encoding", "gzip");
res.header("content-type", "text/html");
res.header("refErrer", "http://example.com");
assertTrue(res.hasHeader("Accept-Encoding"));
assertTrue(res.hasHeader("accept-encoding"));
assertTrue(res.hasHeader("accept-Encoding"));
assertTrue(res.hasHeader("ACCEPT-ENCODING"));
assertEquals("gzip", res.header("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.removeHeader("ACCEPT-ENCODING");
assertFalse(res.hasHeader("Accept-Encoding"));
res.header("ACCEPT-ENCODING", "deflate");
assertEquals("deflate", res.header("Accept-Encoding"));
assertEquals("deflate", res.header("accept-Encoding"));
}
@Test public void headers() {
Connection con = HttpConnection.connect("http://example.com");
Map<String, String> headers = new HashMap<>();
headers.put("content-type", "text/html");
headers.put("Connection", "keep-alive");
headers.put("Host", "http://example.com");
con.headers(headers);
assertEquals("text/html", con.request().header("content-type"));
assertEquals("keep-alive", con.request().header("Connection"));
assertEquals("http://example.com", con.request().header("Host"));
}
@Test public void sameHeadersCombineWithComma() {
Map<String, List<String>> headers = new HashMap<>();
List<String> values = new ArrayList<>();
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 multipleHeaders() {
Connection.Request req = new HttpConnection.Request();
req.addHeader("Accept", "Something");
req.addHeader("Accept", "Everything");
req.addHeader("Foo", "Bar");
assertTrue(req.hasHeader("Accept"));
assertTrue(req.hasHeader("ACCEpt"));
assertEquals("Something, Everything", req.header("accept"));
assertTrue(req.hasHeader("fOO"));
assertEquals("Bar", req.header("foo"));
List<String> accept = req.headers("accept");
assertEquals(2, accept.size());
assertEquals("Something", accept.get(0));
assertEquals("Everything", accept.get(1));
Map<String, List<String>> headers = req.multiHeaders();
assertEquals(accept, headers.get("Accept"));
assertEquals("Bar", headers.get("Foo").get(0));
assertTrue(req.hasHeader("Accept"));
assertTrue(req.hasHeaderWithValue("accept", "Something"));
assertTrue(req.hasHeaderWithValue("accept", "Everything"));
assertFalse(req.hasHeaderWithValue("accept", "Something for nothing"));
req.removeHeader("accept");
headers = req.multiHeaders();
assertEquals("Bar", headers.get("Foo").get(0));
assertFalse(req.hasHeader("Accept"));
assertTrue(headers.get("Accept") == null);
}
@Test public void ignoresEmptySetCookies() {
// prep http response header map
Map<String, List<String>> headers = new HashMap<>();
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<>();
List<String> cookieStrings = new ArrayList<>();
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/");
assertEquals(HttpConnection.DEFAULT_UA, con.request().header("User-Agent"));
con.userAgent("Mozilla");
assertEquals("Mozilla", con.request().header("User-Agent"));
}
@Test public void timeout() {
Connection con = HttpConnection.connect("http://example.com/");
assertEquals(30 * 1000, con.request().timeout());
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 throwsOnOddData() {
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());
}
@Test public void requestBody() {
Connection con = HttpConnection.connect("http://example.com/");
con.requestBody("foo");
assertEquals("foo", con.request().requestBody());
}
@Test public void encodeUrl() throws MalformedURLException {
URL url1 = new URL("http://test.com/?q=white space");
URL url2 = HttpConnection.encodeUrl(url1);
assertEquals("http://test.com/?q=white%20space", url2.toExternalForm());
}
@Test public void noUrlThrowsValidationError() throws IOException {
HttpConnection con = new HttpConnection();
boolean threw = false;
try {
con.execute();
} catch (IllegalArgumentException e) {
threw = true;
assertEquals("URL must be specified to connect", e.getMessage());
}
assertTrue(threw);
}
@Test public void handlesHeaderEncodingOnRequest() {
Connection.Request req = new HttpConnection.Request();
req.addHeader("xxx", "é");
}
} |
||
@Test
public void testRevert() {
// setup
Line line = new Line(new Vector3D(1653345.6696423641, 6170370.041579291, 90000),
new Vector3D(1650757.5050732433, 6160710.879908984, 0.9));
Vector3D expected = line.getDirection().negate();
// action
Line reverted = line.revert();
// verify
Assert.assertArrayEquals(expected.toArray(), reverted.getDirection().toArray(), 0);
} | org.apache.commons.math3.geometry.euclidean.threed.LineTest::testRevert | src/test/java/org/apache/commons/math3/geometry/euclidean/threed/LineTest.java | 145 | src/test/java/org/apache/commons/math3/geometry/euclidean/threed/LineTest.java | testRevert | /*
* 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.geometry.euclidean.threed;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.geometry.euclidean.threed.Line;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
public class LineTest {
@Test
public void testContains() throws MathIllegalArgumentException, MathArithmeticException {
Vector3D p1 = new Vector3D(0, 0, 1);
Line l = new Line(p1, new Vector3D(0, 0, 2));
Assert.assertTrue(l.contains(p1));
Assert.assertTrue(l.contains(new Vector3D(1.0, p1, 0.3, l.getDirection())));
Vector3D u = l.getDirection().orthogonal();
Vector3D v = Vector3D.crossProduct(l.getDirection(), u);
for (double alpha = 0; alpha < 2 * FastMath.PI; alpha += 0.3) {
Assert.assertTrue(! l.contains(p1.add(new Vector3D(FastMath.cos(alpha), u,
FastMath.sin(alpha), v))));
}
}
@Test
public void testSimilar() throws MathIllegalArgumentException, MathArithmeticException {
Vector3D p1 = new Vector3D (1.2, 3.4, -5.8);
Vector3D p2 = new Vector3D (3.4, -5.8, 1.2);
Line lA = new Line(p1, p2);
Line lB = new Line(p2, p1);
Assert.assertTrue(lA.isSimilarTo(lB));
Assert.assertTrue(! lA.isSimilarTo(new Line(p1, p1.add(lA.getDirection().orthogonal()))));
}
@Test
public void testPointDistance() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertEquals(FastMath.sqrt(3.0 / 2.0), l.distance(new Vector3D(1, 0, 1)), 1.0e-10);
Assert.assertEquals(0, l.distance(new Vector3D(0, -4, -4)), 1.0e-10);
}
@Test
public void testLineDistance() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertEquals(1.0,
l.distance(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))),
1.0e-10);
Assert.assertEquals(0.5,
l.distance(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(l),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))),
1.0e-10);
Assert.assertEquals(FastMath.sqrt(8),
l.distance(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))),
1.0e-10);
}
@Test
public void testClosest() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.5,
l.closestPoint(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))).distance(new Vector3D(-0.5, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(l).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))).distance(new Vector3D(0, -2, -2)),
1.0e-10);
}
@Test
public void testIntersection() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertNull(l.intersection(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))));
Assert.assertNull(l.intersection(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))));
Assert.assertEquals(0.0,
l.intersection(l).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.intersection(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.intersection(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertEquals(0.0,
l.intersection(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertNull(l.intersection(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))));
}
@Test
public void testRevert() {
// setup
Line line = new Line(new Vector3D(1653345.6696423641, 6170370.041579291, 90000),
new Vector3D(1650757.5050732433, 6160710.879908984, 0.9));
Vector3D expected = line.getDirection().negate();
// action
Line reverted = line.revert();
// verify
Assert.assertArrayEquals(expected.toArray(), reverted.getDirection().toArray(), 0);
}
} | // You are a professional Java test case writer, please create a test case named `testRevert` for the issue `Math-MATH-938`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-938
//
// ## Issue-Title:
// Line.revert() is imprecise
//
// ## Issue-Description:
//
// Line.revert() only maintains ~10 digits for the direction. This becomes an issue when the line's position is evaluated far from the origin. A simple fix would be to use Vector3D.negate() for the direction.
//
//
// Also, is there a reason why Line is not immutable? It is just comprised of two vectors.
//
//
//
//
//
@Test
public void testRevert() {
| 145 | 9 | 131 | src/test/java/org/apache/commons/math3/geometry/euclidean/threed/LineTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-938
## Issue-Title:
Line.revert() is imprecise
## Issue-Description:
Line.revert() only maintains ~10 digits for the direction. This becomes an issue when the line's position is evaluated far from the origin. A simple fix would be to use Vector3D.negate() for the direction.
Also, is there a reason why Line is not immutable? It is just comprised of two vectors.
```
You are a professional Java test case writer, please create a test case named `testRevert` for the issue `Math-MATH-938`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testRevert() {
```
| 131 | [
"org.apache.commons.math3.geometry.euclidean.threed.Line"
] | 4c65097b47211a990ed77ae46dd439485d871d880f25f079bfb36a7ff3929f0b | @Test
public void testRevert() | // You are a professional Java test case writer, please create a test case named `testRevert` for the issue `Math-MATH-938`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-938
//
// ## Issue-Title:
// Line.revert() is imprecise
//
// ## Issue-Description:
//
// Line.revert() only maintains ~10 digits for the direction. This becomes an issue when the line's position is evaluated far from the origin. A simple fix would be to use Vector3D.negate() for the direction.
//
//
// Also, is there a reason why Line is not immutable? It is just comprised of two vectors.
//
//
//
//
//
| 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.geometry.euclidean.threed;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.geometry.euclidean.threed.Line;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
public class LineTest {
@Test
public void testContains() throws MathIllegalArgumentException, MathArithmeticException {
Vector3D p1 = new Vector3D(0, 0, 1);
Line l = new Line(p1, new Vector3D(0, 0, 2));
Assert.assertTrue(l.contains(p1));
Assert.assertTrue(l.contains(new Vector3D(1.0, p1, 0.3, l.getDirection())));
Vector3D u = l.getDirection().orthogonal();
Vector3D v = Vector3D.crossProduct(l.getDirection(), u);
for (double alpha = 0; alpha < 2 * FastMath.PI; alpha += 0.3) {
Assert.assertTrue(! l.contains(p1.add(new Vector3D(FastMath.cos(alpha), u,
FastMath.sin(alpha), v))));
}
}
@Test
public void testSimilar() throws MathIllegalArgumentException, MathArithmeticException {
Vector3D p1 = new Vector3D (1.2, 3.4, -5.8);
Vector3D p2 = new Vector3D (3.4, -5.8, 1.2);
Line lA = new Line(p1, p2);
Line lB = new Line(p2, p1);
Assert.assertTrue(lA.isSimilarTo(lB));
Assert.assertTrue(! lA.isSimilarTo(new Line(p1, p1.add(lA.getDirection().orthogonal()))));
}
@Test
public void testPointDistance() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertEquals(FastMath.sqrt(3.0 / 2.0), l.distance(new Vector3D(1, 0, 1)), 1.0e-10);
Assert.assertEquals(0, l.distance(new Vector3D(0, -4, -4)), 1.0e-10);
}
@Test
public void testLineDistance() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertEquals(1.0,
l.distance(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))),
1.0e-10);
Assert.assertEquals(0.5,
l.distance(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(l),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))),
1.0e-10);
Assert.assertEquals(0.0,
l.distance(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))),
1.0e-10);
Assert.assertEquals(FastMath.sqrt(8),
l.distance(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))),
1.0e-10);
}
@Test
public void testClosest() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.5,
l.closestPoint(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))).distance(new Vector3D(-0.5, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(l).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertEquals(0.0,
l.closestPoint(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))).distance(new Vector3D(0, -2, -2)),
1.0e-10);
}
@Test
public void testIntersection() throws MathIllegalArgumentException {
Line l = new Line(new Vector3D(0, 1, 1), new Vector3D(0, 2, 2));
Assert.assertNull(l.intersection(new Line(new Vector3D(1, 0, 1), new Vector3D(1, 0, 2))));
Assert.assertNull(l.intersection(new Line(new Vector3D(-0.5, 0, 0), new Vector3D(-0.5, -1, -1))));
Assert.assertEquals(0.0,
l.intersection(l).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.intersection(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -5, -5))).distance(new Vector3D(0, 0, 0)),
1.0e-10);
Assert.assertEquals(0.0,
l.intersection(new Line(new Vector3D(0, -4, -4), new Vector3D(0, -3, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertEquals(0.0,
l.intersection(new Line(new Vector3D(0, -4, -4), new Vector3D(1, -4, -4))).distance(new Vector3D(0, -4, -4)),
1.0e-10);
Assert.assertNull(l.intersection(new Line(new Vector3D(0, -4, 0), new Vector3D(1, -4, 0))));
}
@Test
public void testRevert() {
// setup
Line line = new Line(new Vector3D(1653345.6696423641, 6170370.041579291, 90000),
new Vector3D(1650757.5050732433, 6160710.879908984, 0.9));
Vector3D expected = line.getDirection().negate();
// action
Line reverted = line.revert();
// verify
Assert.assertArrayEquals(expected.toArray(), reverted.getDirection().toArray(), 0);
}
} |
||
public void testCheckSymbolsOverrideForQuiet() {
args.add("--warning_level=QUIET");
args.add("--jscomp_error=undefinedVars");
test("x = 3;", VarCheck.UNDEFINED_VAR_ERROR);
} | com.google.javascript.jscomp.CommandLineRunnerTest::testCheckSymbolsOverrideForQuiet | test/com/google/javascript/jscomp/CommandLineRunnerTest.java | 230 | test/com/google/javascript/jscomp/CommandLineRunnerTest.java | testCheckSymbolsOverrideForQuiet | /*
* 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.javascript.jscomp.CompilerOptions.LanguageMode;
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 nicksantos@google.com (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 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 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 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 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;", SyntacticScopeCreator.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 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 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.TYPE_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.DEFAULT,
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);
}
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() {
test("var x = f.function", RhinoErrorReporter.PARSE_ERROR);
}
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);
}
/* 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]));
}
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;
}
} | // You are a professional Java test case writer, please create a test case named `testCheckSymbolsOverrideForQuiet` for the issue `Closure-467`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-467
//
// ## Issue-Title:
// checkVars / undefinedVars diagnostics not working from command line
//
// ## Issue-Description:
// It seems that setting neither checkVars nor undefinedVars via the jscomp\_warning command line argument does anything. The check(s) do work when "warning\_level VERBOSE" is set though. Other diagnostic groups, such as globalThis, do work however.
//
// Here's what I'm seeing on the console:
//
// ---------------------
//
// >java -jar compiler.jar --js test.js
// foo={bar:function(){alert(this.baz)}};
//
// >java -jar compiler.jar --js test.js --warning\_level VERBOSE
// test.js:2: WARNING - dangerous use of the global this object
//
// test.js:1: ERROR - variable foo is undefined
// foo = {};
// ^
//
// 1 error(s), 1 warning(s)
//
// >java -jar compiler.jar --js test.js --jscomp\_warning globalThis
// test.js:2: WARNING - dangerous use of the global this object
//
// 0 error(s), 1 warning(s)
// foo={bar:function(){alert(this.baz)}};
//
// >java -jar compiler.jar --js test.js --jscomp\_warning checkVars
// foo={bar:function(){alert(this.baz)}};
//
// >java -jar compiler.jar --js test.js --jscomp\_warning undefinedVars
// foo={bar:function(){alert(this.baz)}};
//
// ---------------------
//
// My test.js file looks like this:
//
// ---------------------
//
// foo = {};
// foo.bar = function() { alert(this.baz); };
//
// ---------------------
//
// Tested against r1123 which was committed 5/20/11.
//
//
public void testCheckSymbolsOverrideForQuiet() {
| 230 | 160 | 226 | test/com/google/javascript/jscomp/CommandLineRunnerTest.java | test | ```markdown
## Issue-ID: Closure-467
## Issue-Title:
checkVars / undefinedVars diagnostics not working from command line
## Issue-Description:
It seems that setting neither checkVars nor undefinedVars via the jscomp\_warning command line argument does anything. The check(s) do work when "warning\_level VERBOSE" is set though. Other diagnostic groups, such as globalThis, do work however.
Here's what I'm seeing on the console:
---------------------
>java -jar compiler.jar --js test.js
foo={bar:function(){alert(this.baz)}};
>java -jar compiler.jar --js test.js --warning\_level VERBOSE
test.js:2: WARNING - dangerous use of the global this object
test.js:1: ERROR - variable foo is undefined
foo = {};
^
1 error(s), 1 warning(s)
>java -jar compiler.jar --js test.js --jscomp\_warning globalThis
test.js:2: WARNING - dangerous use of the global this object
0 error(s), 1 warning(s)
foo={bar:function(){alert(this.baz)}};
>java -jar compiler.jar --js test.js --jscomp\_warning checkVars
foo={bar:function(){alert(this.baz)}};
>java -jar compiler.jar --js test.js --jscomp\_warning undefinedVars
foo={bar:function(){alert(this.baz)}};
---------------------
My test.js file looks like this:
---------------------
foo = {};
foo.bar = function() { alert(this.baz); };
---------------------
Tested against r1123 which was committed 5/20/11.
```
You are a professional Java test case writer, please create a test case named `testCheckSymbolsOverrideForQuiet` for the issue `Closure-467`, utilizing the provided issue report information and the following function signature.
```java
public void testCheckSymbolsOverrideForQuiet() {
```
| 226 | [
"com.google.javascript.jscomp.Compiler"
] | 4d74a94a6aa37ba369ca80810d36ac1d70ddfd10b9ff50e09c2c8dcebd737430 | public void testCheckSymbolsOverrideForQuiet() | // You are a professional Java test case writer, please create a test case named `testCheckSymbolsOverrideForQuiet` for the issue `Closure-467`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-467
//
// ## Issue-Title:
// checkVars / undefinedVars diagnostics not working from command line
//
// ## Issue-Description:
// It seems that setting neither checkVars nor undefinedVars via the jscomp\_warning command line argument does anything. The check(s) do work when "warning\_level VERBOSE" is set though. Other diagnostic groups, such as globalThis, do work however.
//
// Here's what I'm seeing on the console:
//
// ---------------------
//
// >java -jar compiler.jar --js test.js
// foo={bar:function(){alert(this.baz)}};
//
// >java -jar compiler.jar --js test.js --warning\_level VERBOSE
// test.js:2: WARNING - dangerous use of the global this object
//
// test.js:1: ERROR - variable foo is undefined
// foo = {};
// ^
//
// 1 error(s), 1 warning(s)
//
// >java -jar compiler.jar --js test.js --jscomp\_warning globalThis
// test.js:2: WARNING - dangerous use of the global this object
//
// 0 error(s), 1 warning(s)
// foo={bar:function(){alert(this.baz)}};
//
// >java -jar compiler.jar --js test.js --jscomp\_warning checkVars
// foo={bar:function(){alert(this.baz)}};
//
// >java -jar compiler.jar --js test.js --jscomp\_warning undefinedVars
// foo={bar:function(){alert(this.baz)}};
//
// ---------------------
//
// My test.js file looks like this:
//
// ---------------------
//
// foo = {};
// foo.bar = function() { alert(this.baz); };
//
// ---------------------
//
// Tested against r1123 which was committed 5/20/11.
//
//
| 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.javascript.jscomp.CompilerOptions.LanguageMode;
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 nicksantos@google.com (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 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 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 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 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;", SyntacticScopeCreator.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 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 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.TYPE_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.DEFAULT,
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);
}
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() {
test("var x = f.function", RhinoErrorReporter.PARSE_ERROR);
}
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);
}
/* 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]));
}
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;
}
} |
||
public void testNoThisInference() {
JSType thisType = createNullableType(OBJECT_TYPE);
assumingThisType(thisType);
inFunction("var out = 3; if (goog.isNull(this)) out = this;");
verify("out", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
} | com.google.javascript.jscomp.TypeInferenceTest::testNoThisInference | test/com/google/javascript/jscomp/TypeInferenceTest.java | 1,004 | test/com/google/javascript/jscomp/TypeInferenceTest.java | testNoThisInference | /*
* 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;
import static com.google.javascript.rhino.jstype.JSTypeNative.ALL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.FUNCTION_INSTANCE_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.DataFlowAnalysis.BranchedFlowState;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.EnumType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.StaticSlot;
import com.google.javascript.rhino.testing.Asserts;
import junit.framework.TestCase;
import java.util.Map;
/**
* Tests {@link TypeInference}.
*
*/
public class TypeInferenceTest extends TestCase {
private Compiler compiler;
private JSTypeRegistry registry;
private Map<String, JSType> assumptions;
private JSType assumedThisType;
private FlowScope returnScope;
private static final Map<String, AssertionFunctionSpec>
ASSERTION_FUNCTION_MAP = Maps.newHashMap();
static {
for (AssertionFunctionSpec func :
new ClosureCodingConvention().getAssertionFunctions()) {
ASSERTION_FUNCTION_MAP.put(func.getFunctionName(), func);
}
}
@Override
public void setUp() {
compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
options.setClosurePass(true);
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
compiler.initOptions(options);
registry = compiler.getTypeRegistry();
assumptions = Maps.newHashMap();
returnScope = null;
}
private void assumingThisType(JSType type) {
assumedThisType = type;
}
private void assuming(String name, JSType type) {
assumptions.put(name, type);
}
private void assuming(String name, JSTypeNative type) {
assuming(name, registry.getNativeType(type));
}
private void inFunction(String js) {
// Parse the body of the function.
String thisBlock = assumedThisType == null
? ""
: "/** @this {" + assumedThisType + "} */";
Node root = compiler.parseTestCode(
"(" + thisBlock + " function() {" + js + "});");
assertEquals("parsing error: " +
Joiner.on(", ").join(compiler.getErrors()),
0, compiler.getErrorCount());
Node n = root.getFirstChild().getFirstChild();
// Create the scope with the assumptions.
TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler);
Scope assumedScope = scopeCreator.createScope(
n, scopeCreator.createScope(root, null));
for (Map.Entry<String,JSType> entry : assumptions.entrySet()) {
assumedScope.declare(entry.getKey(), null, entry.getValue(), null, false);
}
// Create the control graph.
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, n);
ControlFlowGraph<Node> cfg = cfa.getCfg();
// Create a simple reverse abstract interpreter.
ReverseAbstractInterpreter rai = compiler.getReverseAbstractInterpreter();
// Do the type inference by data-flow analysis.
TypeInference dfa = new TypeInference(compiler, cfg, rai, assumedScope,
ASSERTION_FUNCTION_MAP);
dfa.analyze();
// Get the scope of the implicit return.
BranchedFlowState<FlowScope> rtnState =
cfg.getImplicitReturn().getAnnotation();
returnScope = rtnState.getIn();
}
private JSType getType(String name) {
assertTrue("The return scope should not be null.", returnScope != null);
StaticSlot<JSType> var = returnScope.getSlot(name);
assertTrue("The variable " + name + " is missing from the scope.",
var != null);
return var.getType();
}
private void verify(String name, JSType type) {
Asserts.assertTypeEquals(type, getType(name));
}
private void verify(String name, JSTypeNative type) {
verify(name, registry.getNativeType(type));
}
private void verifySubtypeOf(String name, JSType type) {
JSType varType = getType(name);
assertTrue("The variable " + name + " is missing a type.", varType != null);
assertTrue("The type " + varType + " of variable " + name +
" is not a subtype of " + type +".", varType.isSubtype(type));
}
private void verifySubtypeOf(String name, JSTypeNative type) {
verifySubtypeOf(name, registry.getNativeType(type));
}
private EnumType createEnumType(String name, JSTypeNative elemType) {
return createEnumType(name, registry.getNativeType(elemType));
}
private EnumType createEnumType(String name, JSType elemType) {
return registry.createEnumType(name, null, elemType);
}
private JSType createUndefinableType(JSTypeNative type) {
return registry.createUnionType(
registry.getNativeType(type), registry.getNativeType(VOID_TYPE));
}
private JSType createNullableType(JSTypeNative type) {
return createNullableType(registry.getNativeType(type));
}
private JSType createNullableType(JSType type) {
return registry.createNullableType(type);
}
private JSType createUnionType(JSTypeNative type1, JSTypeNative type2) {
return registry.createUnionType(
registry.getNativeType(type1), registry.getNativeType(type2));
}
public void testAssumption() {
assuming("x", NUMBER_TYPE);
inFunction("");
verify("x", NUMBER_TYPE);
}
public void testVar() {
inFunction("var x = 1;");
verify("x", NUMBER_TYPE);
}
public void testEmptyVar() {
inFunction("var x;");
verify("x", VOID_TYPE);
}
public void testAssignment() {
assuming("x", OBJECT_TYPE);
inFunction("x = 1;");
verify("x", NUMBER_TYPE);
}
public void testGetProp() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("x.y();");
verify("x", OBJECT_TYPE);
}
public void testGetElemDereference() {
assuming("x", createUndefinableType(OBJECT_TYPE));
inFunction("x['z'] = 3;");
verify("x", OBJECT_TYPE);
}
public void testIf1() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = {}; if (x) { y = x; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testIf1a() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = {}; if (x != null) { y = x; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testIf2() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = x; if (x) { y = x; } else { y = {}; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testIf3() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 1; if (x) { y = x; }");
verify("y", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
}
public void testPropertyInference1() {
ObjectType thisType = registry.createAnonymousObjectType();
thisType.defineDeclaredProperty("foo",
createUndefinableType(STRING_TYPE), null);
assumingThisType(thisType);
inFunction("var y = 1; if (this.foo) { y = this.foo; }");
verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE));
}
public void testPropertyInference2() {
ObjectType thisType = registry.createAnonymousObjectType();
thisType.defineDeclaredProperty("foo",
createUndefinableType(STRING_TYPE), null);
assumingThisType(thisType);
inFunction("var y = 1; this.foo = 'x'; y = this.foo;");
verify("y", STRING_TYPE);
}
public void testPropertyInference3() {
ObjectType thisType = registry.createAnonymousObjectType();
thisType.defineDeclaredProperty("foo",
createUndefinableType(STRING_TYPE), null);
assumingThisType(thisType);
inFunction("var y = 1; this.foo = x; y = this.foo;");
verify("y", CHECKED_UNKNOWN_TYPE);
}
public void testAssert1() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assert(x); out2 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert1a() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assert(x !== null); out2 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert2() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("goog.asserts.assert(1, x); out1 = x;");
verify("out1", startType);
}
public void testAssert3() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("out1 = x; goog.asserts.assert(x && y); out2 = x; out3 = y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
verify("out3", OBJECT_TYPE);
}
public void testAssert4() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("out1 = x; goog.asserts.assert(x && !y); out2 = x; out3 = y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
verify("out3", NULL_TYPE);
}
public void testAssert5() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("goog.asserts.assert(x || y); out1 = x; out2 = y;");
verify("out1", startType);
verify("out2", startType);
}
public void testAssert6() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x.y", startType);
inFunction("out1 = x.y; goog.asserts.assert(x.y); out2 = x.y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert7() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(x);");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert8() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(x != null);");
verify("out1", startType);
verify("out2", BOOLEAN_TYPE);
}
public void testAssert9() {
JSType startType = createNullableType(NUMBER_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(y = x);");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssert10() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(x && y); out3 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
verify("out3", OBJECT_TYPE);
}
public void testAssertNumber() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertNumber(x); out2 = x;");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssertNumber2() {
// Make sure it ignores expressions.
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("goog.asserts.assertNumber(x + x); out1 = x;");
verify("out1", startType);
}
public void testAssertNumber3() {
// Make sure it ignores expressions.
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assertNumber(x + x);");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssertString() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertString(x); out2 = x;");
verify("out1", startType);
verify("out2", STRING_TYPE);
}
public void testAssertFunction() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertFunction(x); out2 = x;");
verify("out1", startType);
verifySubtypeOf("out2", FUNCTION_INSTANCE_TYPE);
}
public void testAssertObject() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;");
verify("out1", startType);
verifySubtypeOf("out2", OBJECT_TYPE);
}
public void testAssertObject2() {
JSType startType = createNullableType(ARRAY_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;");
verify("out1", startType);
verify("out2", ARRAY_TYPE);
}
public void testAssertObject3() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x.y", startType);
inFunction("out1 = x.y; goog.asserts.assertObject(x.y); out2 = x.y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssertObject4() {
JSType startType = createNullableType(ARRAY_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assertObject(x);");
verify("out1", startType);
verify("out2", ARRAY_TYPE);
}
public void testAssertObject5() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction(
"out1 = x;" +
"out2 = /** @type {!Array} */ (goog.asserts.assertObject(x));");
verify("out1", startType);
verify("out2", ARRAY_TYPE);
}
public void testAssertArray() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertArray(x); out2 = x;");
verify("out1", startType);
verifySubtypeOf("out2", ARRAY_TYPE);
}
public void testAssertInstanceof1() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x); out2 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssertInstanceof2() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;");
verify("out1", startType);
verify("out2", STRING_OBJECT_TYPE);
}
public void testAssertInstanceof3() {
JSType startType = registry.getNativeType(UNKNOWN_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;");
verify("out1", startType);
verify("out2", UNKNOWN_TYPE);
}
public void testAssertInstanceof4() {
JSType startType = registry.getNativeType(STRING_OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x, Object); out2 = x;");
verify("out1", startType);
verify("out2", STRING_OBJECT_TYPE);
}
public void testAssertInstanceof5() {
JSType startType = registry.getNativeType(ALL_TYPE);
assuming("x", startType);
inFunction(
"out1 = x; goog.asserts.assertInstanceof(x, String); var r = x;");
verify("out1", startType);
verify("x", STRING_OBJECT_TYPE);
}
public void testAssertWithIsDef() {
JSType startType = createNullableType(NUMBER_TYPE);
assuming("x", startType);
inFunction(
"out1 = x;" +
"goog.asserts.assert(goog.isDefAndNotNull(x));" +
"out2 = x;");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssertWithNotIsNull() {
JSType startType = createNullableType(NUMBER_TYPE);
assuming("x", startType);
inFunction(
"out1 = x;" +
"goog.asserts.assert(!goog.isNull(x));" +
"out2 = x;");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testReturn1() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("if (x) { return x; }\nx = {};\nreturn x;");
verify("x", OBJECT_TYPE);
}
public void testReturn2() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("if (!x) { x = 0; }\nreturn x;");
verify("x", NUMBER_TYPE);
}
public void testWhile1() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("while (!x) { if (x == null) { x = 0; } else { x = 1; } }");
verify("x", NUMBER_TYPE);
}
public void testWhile2() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("while (!x) { x = {}; }");
verifySubtypeOf("x", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
}
public void testDo() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("do { x = 1; } while (!x);");
verify("x", NUMBER_TYPE);
}
public void testFor1() {
assuming("y", NUMBER_TYPE);
inFunction("var x = null; var i = null; for (i=y; !i; i=1) { x = 1; }");
verify("x", createNullableType(NUMBER_TYPE));
verify("i", NUMBER_TYPE);
}
public void testFor2() {
assuming("y", OBJECT_TYPE);
inFunction("var x = null; var i = null; for (i in y) { x = 1; }");
verify("x", createNullableType(NUMBER_TYPE));
verify("i", createNullableType(STRING_TYPE));
}
public void testFor3() {
assuming("y", OBJECT_TYPE);
inFunction("var x = null; var i = null; for (var i in y) { x = 1; }");
verify("x", createNullableType(NUMBER_TYPE));
verify("i", createNullableType(STRING_TYPE));
}
public void testFor4() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = {};\n" +
"if (x) { for (var i = 0; i < 10; i++) { break; } y = x; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testSwitch1() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; switch(x) {\n" +
"case 1: y = 1; break;\n" +
"case 2: y = {};\n" +
"case 3: y = {};\n" +
"default: y = 0;}");
verify("y", NUMBER_TYPE);
}
public void testSwitch2() {
assuming("x", ALL_TYPE);
inFunction("var y = null; switch (typeof x) {\n" +
"case 'string':\n" +
" y = x;\n" +
" return;" +
"default:\n" +
" y = 'a';\n" +
"}");
verify("y", STRING_TYPE);
}
public void testSwitch3() {
assuming("x",
createNullableType(createUnionType(NUMBER_TYPE, STRING_TYPE)));
inFunction("var y; var z; switch (typeof x) {\n" +
"case 'string':\n" +
" y = 1; z = null;\n" +
" return;\n" +
"case 'number':\n" +
" y = x; z = null;\n" +
" return;" +
"default:\n" +
" y = 1; z = x;\n" +
"}");
verify("y", NUMBER_TYPE);
verify("z", NULL_TYPE);
}
public void testSwitch4() {
assuming("x", ALL_TYPE);
inFunction("var y = null; switch (typeof x) {\n" +
"case 'string':\n" +
"case 'number':\n" +
" y = x;\n" +
" return;\n" +
"default:\n" +
" y = 1;\n" +
"}\n");
verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE));
}
public void testCall1() {
assuming("x",
createNullableType(
registry.createFunctionType(registry.getNativeType(NUMBER_TYPE))));
inFunction("var y = x();");
verify("y", NUMBER_TYPE);
}
public void testNew1() {
assuming("x",
createNullableType(
registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE)));
inFunction("var y = new x();");
verify("y", JSTypeNative.NO_OBJECT_TYPE);
}
public void testInnerFunction1() {
inFunction("var x = 1; function f() { x = null; };");
verify("x", NUMBER_TYPE);
}
public void testInnerFunction2() {
inFunction("var x = 1; var f = function() { x = null; };");
verify("x", NUMBER_TYPE);
}
public void testHook() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = x ? x : {};");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testThrow() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("var y = 1;\n" +
"if (x == null) { throw new Error('x is null') }\n" +
"y = x;");
verify("y", NUMBER_TYPE);
}
public void testTry1() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; try { y = null; } finally { y = x; }");
verify("y", NUMBER_TYPE);
}
public void testTry2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null;\n" +
"try { } catch (e) { y = null; } finally { y = x; }");
verify("y", NUMBER_TYPE);
}
public void testTry3() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; try { y = x; } catch (e) { }");
verify("y", NUMBER_TYPE);
}
public void testCatch1() {
inFunction("var y = null; try { foo(); } catch (e) { y = e; }");
verify("y", UNKNOWN_TYPE);
}
public void testCatch2() {
inFunction("var y = null; var e = 3; try { foo(); } catch (e) { y = e; }");
verify("y", UNKNOWN_TYPE);
}
public void testUnknownType1() {
inFunction("var y = 3; y = x;");
verify("y", UNKNOWN_TYPE);
}
public void testUnknownType2() {
assuming("x", ARRAY_TYPE);
inFunction("var y = 5; y = x[0];");
verify("y", UNKNOWN_TYPE);
}
public void testInfiniteLoop1() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("x = {}; while(x != null) { x = {}; }");
}
public void testInfiniteLoop2() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("x = {}; do { x = null; } while (x == null);");
}
public void testJoin1() {
JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE);
assuming("x", BOOLEAN_TYPE);
assuming("unknownOrNull", unknownOrNull);
inFunction("var y; if (x) y = unknownOrNull; else y = null;");
verify("y", unknownOrNull);
}
public void testJoin2() {
JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE);
assuming("x", BOOLEAN_TYPE);
assuming("unknownOrNull", unknownOrNull);
inFunction("var y; if (x) y = null; else y = unknownOrNull;");
verify("y", unknownOrNull);
}
public void testArrayLit() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 3; if (x) { x = [y = x]; }");
verify("x", createUnionType(NULL_TYPE, ARRAY_TYPE));
verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE));
}
public void testGetElem() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 3; if (x) { x = x[y = x]; }");
verify("x", UNKNOWN_TYPE);
verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE));
}
public void testEnumRAI1() {
JSType enumType = createEnumType("MyEnum", ARRAY_TYPE).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (x) y = x;");
verify("y", createNullableType(enumType));
}
public void testEnumRAI2() {
JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (typeof x == 'number') y = x;");
verify("y", createNullableType(enumType));
}
public void testEnumRAI3() {
JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (x && typeof x == 'number') y = x;");
verify("y", createNullableType(enumType));
}
public void testEnumRAI4() {
JSType enumType = createEnumType("MyEnum",
createUnionType(STRING_TYPE, NUMBER_TYPE)).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (typeof x == 'number') y = x;");
verify("y", createNullableType(NUMBER_TYPE));
}
public void testShortCircuitingAnd() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; if (x && (y = 3)) { }");
verify("y", createNullableType(NUMBER_TYPE));
}
public void testShortCircuitingAnd2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; var z = 4; if (x && (y = 3)) { z = y; }");
verify("z", NUMBER_TYPE);
}
public void testShortCircuitingOr() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; if (x || (y = 3)) { }");
verify("y", createNullableType(NUMBER_TYPE));
}
public void testShortCircuitingOr2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; var z = 4; if (x || (y = 3)) { z = y; }");
verify("z", createNullableType(NUMBER_TYPE));
}
public void testAssignInCondition() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("var y; if (!(y = x)) { y = 3; }");
verify("y", NUMBER_TYPE);
}
public void testInstanceOf1() {
assuming("x", OBJECT_TYPE);
inFunction("var y = null; if (x instanceof String) y = x;");
verify("y", createNullableType(STRING_OBJECT_TYPE));
}
public void testInstanceOf2() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 1; if (x instanceof String) y = x;");
verify("y", createUnionType(STRING_OBJECT_TYPE, NUMBER_TYPE));
}
public void testInstanceOf3() {
assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE));
inFunction("var y = null; if (x instanceof String) y = x;");
verify("y", createNullableType(STRING_OBJECT_TYPE));
}
public void testInstanceOf4() {
assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE));
inFunction("var y = null; if (x instanceof String); else y = x;");
verify("y", createNullableType(NUMBER_OBJECT_TYPE));
}
public void testInstanceOf5() {
assuming("x", OBJECT_TYPE);
inFunction("var y = null; if (x instanceof String); else y = x;");
verify("y", createNullableType(OBJECT_TYPE));
}
public void testInstanceOf6() {
// Here we are using "instanceof" to restrict the unknown type to
// the type of the instance. This has the following problems:
// 1) The type may actually be any sub-type
// 2) The type may implement any interface
// After the instanceof we will require casts for methods that require
// sub-type or unrelated interfaces which would not have been required
// before.
JSType startType = registry.getNativeType(UNKNOWN_TYPE);
assuming("x", startType);
inFunction("out1 = x; if (x instanceof String) out2 = x;");
verify("out1", startType);
verify("out2", STRING_OBJECT_TYPE);
}
public void testFlattening() {
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
assuming("s" + i, ALL_TYPE);
}
assuming("b", JSTypeNative.BOOLEAN_TYPE);
StringBuilder body = new StringBuilder();
body.append("if (b) {");
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
body.append("s");
body.append(i);
body.append(" = 1;\n");
}
body.append(" } else { ");
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
body.append("s");
body.append(i);
body.append(" = 'ONE';\n");
}
body.append("}");
JSType numberORString = createUnionType(NUMBER_TYPE, STRING_TYPE);
inFunction(body.toString());
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
verify("s" + i, numberORString);
}
}
public void testUnary() {
assuming("x", NUMBER_TYPE);
inFunction("var y = +x;");
verify("y", NUMBER_TYPE);
inFunction("var z = -x;");
verify("z", NUMBER_TYPE);
}
public void testAdd1() {
assuming("x", NUMBER_TYPE);
inFunction("var y = x + 5;");
verify("y", NUMBER_TYPE);
}
public void testAdd2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = x + '5';");
verify("y", STRING_TYPE);
}
public void testAdd3() {
assuming("x", NUMBER_TYPE);
inFunction("var y = '5' + x;");
verify("y", STRING_TYPE);
}
public void testAssignAdd() {
assuming("x", NUMBER_TYPE);
inFunction("x += '5';");
verify("x", STRING_TYPE);
}
public void testComparison() {
inFunction("var x = 'foo'; var y = (x = 3) < 4;");
verify("x", NUMBER_TYPE);
inFunction("var x = 'foo'; var y = (x = 3) > 4;");
verify("x", NUMBER_TYPE);
inFunction("var x = 'foo'; var y = (x = 3) <= 4;");
verify("x", NUMBER_TYPE);
inFunction("var x = 'foo'; var y = (x = 3) >= 4;");
verify("x", NUMBER_TYPE);
}
public void testThrownExpression() {
inFunction("var x = 'foo'; "
+ "try { throw new Error(x = 3); } catch (ex) {}");
verify("x", NUMBER_TYPE);
}
public void testObjectLit() {
inFunction("var x = {}; var out = x.a;");
verify("out", UNKNOWN_TYPE); // Shouldn't this be 'undefined'?
inFunction("var x = {a:1}; var out = x.a;");
verify("out", NUMBER_TYPE);
inFunction("var x = {a:1}; var out = x.a; x.a = 'string'; var out2 = x.a;");
verify("out", NUMBER_TYPE);
verify("out2", STRING_TYPE);
inFunction("var x = { get a() {return 1} }; var out = x.a;");
verify("out", UNKNOWN_TYPE);
inFunction(
"var x = {" +
" /** @return {number} */ get a() {return 1}" +
"};" +
"var out = x.a;");
verify("out", NUMBER_TYPE);
inFunction("var x = { set a(b) {} }; var out = x.a;");
verify("out", UNKNOWN_TYPE);
inFunction("var x = { " +
"/** @param {number} b */ set a(b) {} };" +
"var out = x.a;");
verify("out", NUMBER_TYPE);
}
public void testCast1() {
inFunction("var x = /** @type {Object} */ (this);");
verify("x", createNullableType(OBJECT_TYPE));
}
public void testCast2() {
inFunction(
"/** @return {boolean} */" +
"Object.prototype.method = function() { return true; };" +
"var x = /** @type {Object} */ (this).method;");
verify(
"x",
registry.createFunctionType(
registry.getNativeObjectType(OBJECT_TYPE),
registry.getNativeType(BOOLEAN_TYPE),
ImmutableList.<JSType>of() /* params */));
}
public void testBackwardsInferenceCall() {
inFunction(
"/** @param {{foo: (number|undefined)}} x */" +
"function f(x) {}" +
"var y = {};" +
"f(y);");
assertEquals("{foo: (number|undefined)}", getType("y").toString());
}
public void testBackwardsInferenceNew() {
inFunction(
"/**\n" +
" * @constructor\n" +
" * @param {{foo: (number|undefined)}} x\n" +
" */" +
"function F(x) {}" +
"var y = {};" +
"new F(y);");
assertEquals("{foo: (number|undefined)}", getType("y").toString());
}
public void testNoThisInference() {
JSType thisType = createNullableType(OBJECT_TYPE);
assumingThisType(thisType);
inFunction("var out = 3; if (goog.isNull(this)) out = this;");
verify("out", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
}
} | // You are a professional Java test case writer, please create a test case named `testNoThisInference` for the issue `Closure-769`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-769
//
// ## Issue-Title:
// Type refining of 'this' raises IllegalArgumentException
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. goog.isFunction(this) or goog.isObject(this) or goog.isNull(this) etc.
//
// **What is the expected output? What do you see instead?**
//
// Expected: normal compilation, checking the type of this
// Actual output:
//
// 23: java.lang.IllegalArgumentException: Node cannot be refined.
// THIS 1 [source\_file: Input\_0] : global this
//
// at com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter.declareNameInScope(ChainableReverseAbstractInterpreter.java:172)
// at com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter.restrictParameter(ClosureReverseAbstractInterpreter.java:240)
// at com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter.getPreciserScopeKnowingConditionOutcome(ClosureReverseAbstractInterpreter.java:221)
// at com.google.javascript.jscomp.TypeInference.branchedFlowThrough(TypeInference.java:239)
// at com.google.javascript.jscomp.TypeInference.branchedFlowThrough(TypeInference.java:59)
// at com.google.javascript.jscomp.DataFlowAnalysis$BranchedForwardDataFlowAnalysis.flow(DataFlowAnalysis.java:448)
// at com.google.javascript.jscomp.DataFlowAnalysis.analyze(DataFlowAnalysis.java:213)
// at com.google.javascript.jscomp.DataFlowAnalysis.analyze(DataFlowAnalysis.java:181)
// at com.google.javascript.jscomp.TypeInferencePass.inferTypes(TypeInferencePass.java:90)
// at com.google.javascript.jscomp.TypeInferencePass$TypeInferringCallback.enterScope(TypeInferencePass.java:106)
// at com.google.javascript.jscomp.NodeTraversal.pushScope(NodeTraversal.java:581)
// at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:345)
// at com.google.javascript.jscomp.TypeInferencePass.inferTypes(TypeInferencePass.java:81)
// at com.google.javascript.jscomp.TypeInferencePass.process(TypeInferencePass.java:74)
// at com.google.javascript.jscomp.DefaultPassConfig$24$1.process(DefaultPassConfig.java:1119)
// at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(PhaseOptimizer.java:296)
// at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:273)
// at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:187)
// at com.google.javascript.jscomp.Compiler.check(Compiler.java:768)
// at com.google.javascript.jscomp.Compiler.compileInternal(Compiler.java:683)
// at com.google.javascript.jscomp.Compiler.access$000(Compiler.java:79)
// at com.google.javascript.jscomp.Compiler$1.call(Compiler.java:586)
// at com.google.javascript.jscomp.Compiler$1.call(Compiler.java:583)
// at com.google.javascript.jscomp.Compiler$2.run(Compiler.java:628)
// at com.google.javascript.jscomp.Compiler.runCallable(Compiler.java:651)
// at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:601)
// at com.google.javascript.jscomp.Compiler.compile(Compiler.java:583)
//
// **What version of the product are you using? On what operating system?**
//
// Any version (local and http://closure-compiler.appspot.com/).
//
// **
public void testNoThisInference() {
| 1,004 | 19 | 999 | test/com/google/javascript/jscomp/TypeInferenceTest.java | test | ```markdown
## Issue-ID: Closure-769
## Issue-Title:
Type refining of 'this' raises IllegalArgumentException
## Issue-Description:
**What steps will reproduce the problem?**
1. goog.isFunction(this) or goog.isObject(this) or goog.isNull(this) etc.
**What is the expected output? What do you see instead?**
Expected: normal compilation, checking the type of this
Actual output:
23: java.lang.IllegalArgumentException: Node cannot be refined.
THIS 1 [source\_file: Input\_0] : global this
at com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter.declareNameInScope(ChainableReverseAbstractInterpreter.java:172)
at com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter.restrictParameter(ClosureReverseAbstractInterpreter.java:240)
at com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter.getPreciserScopeKnowingConditionOutcome(ClosureReverseAbstractInterpreter.java:221)
at com.google.javascript.jscomp.TypeInference.branchedFlowThrough(TypeInference.java:239)
at com.google.javascript.jscomp.TypeInference.branchedFlowThrough(TypeInference.java:59)
at com.google.javascript.jscomp.DataFlowAnalysis$BranchedForwardDataFlowAnalysis.flow(DataFlowAnalysis.java:448)
at com.google.javascript.jscomp.DataFlowAnalysis.analyze(DataFlowAnalysis.java:213)
at com.google.javascript.jscomp.DataFlowAnalysis.analyze(DataFlowAnalysis.java:181)
at com.google.javascript.jscomp.TypeInferencePass.inferTypes(TypeInferencePass.java:90)
at com.google.javascript.jscomp.TypeInferencePass$TypeInferringCallback.enterScope(TypeInferencePass.java:106)
at com.google.javascript.jscomp.NodeTraversal.pushScope(NodeTraversal.java:581)
at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:345)
at com.google.javascript.jscomp.TypeInferencePass.inferTypes(TypeInferencePass.java:81)
at com.google.javascript.jscomp.TypeInferencePass.process(TypeInferencePass.java:74)
at com.google.javascript.jscomp.DefaultPassConfig$24$1.process(DefaultPassConfig.java:1119)
at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(PhaseOptimizer.java:296)
at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:273)
at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:187)
at com.google.javascript.jscomp.Compiler.check(Compiler.java:768)
at com.google.javascript.jscomp.Compiler.compileInternal(Compiler.java:683)
at com.google.javascript.jscomp.Compiler.access$000(Compiler.java:79)
at com.google.javascript.jscomp.Compiler$1.call(Compiler.java:586)
at com.google.javascript.jscomp.Compiler$1.call(Compiler.java:583)
at com.google.javascript.jscomp.Compiler$2.run(Compiler.java:628)
at com.google.javascript.jscomp.Compiler.runCallable(Compiler.java:651)
at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:601)
at com.google.javascript.jscomp.Compiler.compile(Compiler.java:583)
**What version of the product are you using? On what operating system?**
Any version (local and http://closure-compiler.appspot.com/).
**
```
You are a professional Java test case writer, please create a test case named `testNoThisInference` for the issue `Closure-769`, utilizing the provided issue report information and the following function signature.
```java
public void testNoThisInference() {
```
| 999 | [
"com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter"
] | 4ebbeb9843ffa0ef77f188c2a866582a7a74a68b67397b5955a3aef5afe75b95 | public void testNoThisInference() | // You are a professional Java test case writer, please create a test case named `testNoThisInference` for the issue `Closure-769`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-769
//
// ## Issue-Title:
// Type refining of 'this' raises IllegalArgumentException
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. goog.isFunction(this) or goog.isObject(this) or goog.isNull(this) etc.
//
// **What is the expected output? What do you see instead?**
//
// Expected: normal compilation, checking the type of this
// Actual output:
//
// 23: java.lang.IllegalArgumentException: Node cannot be refined.
// THIS 1 [source\_file: Input\_0] : global this
//
// at com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter.declareNameInScope(ChainableReverseAbstractInterpreter.java:172)
// at com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter.restrictParameter(ClosureReverseAbstractInterpreter.java:240)
// at com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter.getPreciserScopeKnowingConditionOutcome(ClosureReverseAbstractInterpreter.java:221)
// at com.google.javascript.jscomp.TypeInference.branchedFlowThrough(TypeInference.java:239)
// at com.google.javascript.jscomp.TypeInference.branchedFlowThrough(TypeInference.java:59)
// at com.google.javascript.jscomp.DataFlowAnalysis$BranchedForwardDataFlowAnalysis.flow(DataFlowAnalysis.java:448)
// at com.google.javascript.jscomp.DataFlowAnalysis.analyze(DataFlowAnalysis.java:213)
// at com.google.javascript.jscomp.DataFlowAnalysis.analyze(DataFlowAnalysis.java:181)
// at com.google.javascript.jscomp.TypeInferencePass.inferTypes(TypeInferencePass.java:90)
// at com.google.javascript.jscomp.TypeInferencePass$TypeInferringCallback.enterScope(TypeInferencePass.java:106)
// at com.google.javascript.jscomp.NodeTraversal.pushScope(NodeTraversal.java:581)
// at com.google.javascript.jscomp.NodeTraversal.traverseWithScope(NodeTraversal.java:345)
// at com.google.javascript.jscomp.TypeInferencePass.inferTypes(TypeInferencePass.java:81)
// at com.google.javascript.jscomp.TypeInferencePass.process(TypeInferencePass.java:74)
// at com.google.javascript.jscomp.DefaultPassConfig$24$1.process(DefaultPassConfig.java:1119)
// at com.google.javascript.jscomp.PhaseOptimizer$PassFactoryDelegate.processInternal(PhaseOptimizer.java:296)
// at com.google.javascript.jscomp.PhaseOptimizer$NamedPass.process(PhaseOptimizer.java:273)
// at com.google.javascript.jscomp.PhaseOptimizer.process(PhaseOptimizer.java:187)
// at com.google.javascript.jscomp.Compiler.check(Compiler.java:768)
// at com.google.javascript.jscomp.Compiler.compileInternal(Compiler.java:683)
// at com.google.javascript.jscomp.Compiler.access$000(Compiler.java:79)
// at com.google.javascript.jscomp.Compiler$1.call(Compiler.java:586)
// at com.google.javascript.jscomp.Compiler$1.call(Compiler.java:583)
// at com.google.javascript.jscomp.Compiler$2.run(Compiler.java:628)
// at com.google.javascript.jscomp.Compiler.runCallable(Compiler.java:651)
// at com.google.javascript.jscomp.Compiler.runInCompilerThread(Compiler.java:601)
// at com.google.javascript.jscomp.Compiler.compile(Compiler.java:583)
//
// **What version of the product are you using? On what operating system?**
//
// Any version (local and http://closure-compiler.appspot.com/).
//
// **
| 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;
import static com.google.javascript.rhino.jstype.JSTypeNative.ALL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.ARRAY_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.CHECKED_UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.FUNCTION_INSTANCE_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NULL_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.UNKNOWN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.VOID_TYPE;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.DataFlowAnalysis.BranchedFlowState;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.jscomp.type.ReverseAbstractInterpreter;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.EnumType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.StaticSlot;
import com.google.javascript.rhino.testing.Asserts;
import junit.framework.TestCase;
import java.util.Map;
/**
* Tests {@link TypeInference}.
*
*/
public class TypeInferenceTest extends TestCase {
private Compiler compiler;
private JSTypeRegistry registry;
private Map<String, JSType> assumptions;
private JSType assumedThisType;
private FlowScope returnScope;
private static final Map<String, AssertionFunctionSpec>
ASSERTION_FUNCTION_MAP = Maps.newHashMap();
static {
for (AssertionFunctionSpec func :
new ClosureCodingConvention().getAssertionFunctions()) {
ASSERTION_FUNCTION_MAP.put(func.getFunctionName(), func);
}
}
@Override
public void setUp() {
compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
options.setClosurePass(true);
options.setLanguageIn(LanguageMode.ECMASCRIPT5);
compiler.initOptions(options);
registry = compiler.getTypeRegistry();
assumptions = Maps.newHashMap();
returnScope = null;
}
private void assumingThisType(JSType type) {
assumedThisType = type;
}
private void assuming(String name, JSType type) {
assumptions.put(name, type);
}
private void assuming(String name, JSTypeNative type) {
assuming(name, registry.getNativeType(type));
}
private void inFunction(String js) {
// Parse the body of the function.
String thisBlock = assumedThisType == null
? ""
: "/** @this {" + assumedThisType + "} */";
Node root = compiler.parseTestCode(
"(" + thisBlock + " function() {" + js + "});");
assertEquals("parsing error: " +
Joiner.on(", ").join(compiler.getErrors()),
0, compiler.getErrorCount());
Node n = root.getFirstChild().getFirstChild();
// Create the scope with the assumptions.
TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler);
Scope assumedScope = scopeCreator.createScope(
n, scopeCreator.createScope(root, null));
for (Map.Entry<String,JSType> entry : assumptions.entrySet()) {
assumedScope.declare(entry.getKey(), null, entry.getValue(), null, false);
}
// Create the control graph.
ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, false);
cfa.process(null, n);
ControlFlowGraph<Node> cfg = cfa.getCfg();
// Create a simple reverse abstract interpreter.
ReverseAbstractInterpreter rai = compiler.getReverseAbstractInterpreter();
// Do the type inference by data-flow analysis.
TypeInference dfa = new TypeInference(compiler, cfg, rai, assumedScope,
ASSERTION_FUNCTION_MAP);
dfa.analyze();
// Get the scope of the implicit return.
BranchedFlowState<FlowScope> rtnState =
cfg.getImplicitReturn().getAnnotation();
returnScope = rtnState.getIn();
}
private JSType getType(String name) {
assertTrue("The return scope should not be null.", returnScope != null);
StaticSlot<JSType> var = returnScope.getSlot(name);
assertTrue("The variable " + name + " is missing from the scope.",
var != null);
return var.getType();
}
private void verify(String name, JSType type) {
Asserts.assertTypeEquals(type, getType(name));
}
private void verify(String name, JSTypeNative type) {
verify(name, registry.getNativeType(type));
}
private void verifySubtypeOf(String name, JSType type) {
JSType varType = getType(name);
assertTrue("The variable " + name + " is missing a type.", varType != null);
assertTrue("The type " + varType + " of variable " + name +
" is not a subtype of " + type +".", varType.isSubtype(type));
}
private void verifySubtypeOf(String name, JSTypeNative type) {
verifySubtypeOf(name, registry.getNativeType(type));
}
private EnumType createEnumType(String name, JSTypeNative elemType) {
return createEnumType(name, registry.getNativeType(elemType));
}
private EnumType createEnumType(String name, JSType elemType) {
return registry.createEnumType(name, null, elemType);
}
private JSType createUndefinableType(JSTypeNative type) {
return registry.createUnionType(
registry.getNativeType(type), registry.getNativeType(VOID_TYPE));
}
private JSType createNullableType(JSTypeNative type) {
return createNullableType(registry.getNativeType(type));
}
private JSType createNullableType(JSType type) {
return registry.createNullableType(type);
}
private JSType createUnionType(JSTypeNative type1, JSTypeNative type2) {
return registry.createUnionType(
registry.getNativeType(type1), registry.getNativeType(type2));
}
public void testAssumption() {
assuming("x", NUMBER_TYPE);
inFunction("");
verify("x", NUMBER_TYPE);
}
public void testVar() {
inFunction("var x = 1;");
verify("x", NUMBER_TYPE);
}
public void testEmptyVar() {
inFunction("var x;");
verify("x", VOID_TYPE);
}
public void testAssignment() {
assuming("x", OBJECT_TYPE);
inFunction("x = 1;");
verify("x", NUMBER_TYPE);
}
public void testGetProp() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("x.y();");
verify("x", OBJECT_TYPE);
}
public void testGetElemDereference() {
assuming("x", createUndefinableType(OBJECT_TYPE));
inFunction("x['z'] = 3;");
verify("x", OBJECT_TYPE);
}
public void testIf1() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = {}; if (x) { y = x; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testIf1a() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = {}; if (x != null) { y = x; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testIf2() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = x; if (x) { y = x; } else { y = {}; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testIf3() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 1; if (x) { y = x; }");
verify("y", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
}
public void testPropertyInference1() {
ObjectType thisType = registry.createAnonymousObjectType();
thisType.defineDeclaredProperty("foo",
createUndefinableType(STRING_TYPE), null);
assumingThisType(thisType);
inFunction("var y = 1; if (this.foo) { y = this.foo; }");
verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE));
}
public void testPropertyInference2() {
ObjectType thisType = registry.createAnonymousObjectType();
thisType.defineDeclaredProperty("foo",
createUndefinableType(STRING_TYPE), null);
assumingThisType(thisType);
inFunction("var y = 1; this.foo = 'x'; y = this.foo;");
verify("y", STRING_TYPE);
}
public void testPropertyInference3() {
ObjectType thisType = registry.createAnonymousObjectType();
thisType.defineDeclaredProperty("foo",
createUndefinableType(STRING_TYPE), null);
assumingThisType(thisType);
inFunction("var y = 1; this.foo = x; y = this.foo;");
verify("y", CHECKED_UNKNOWN_TYPE);
}
public void testAssert1() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assert(x); out2 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert1a() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assert(x !== null); out2 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert2() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("goog.asserts.assert(1, x); out1 = x;");
verify("out1", startType);
}
public void testAssert3() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("out1 = x; goog.asserts.assert(x && y); out2 = x; out3 = y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
verify("out3", OBJECT_TYPE);
}
public void testAssert4() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("out1 = x; goog.asserts.assert(x && !y); out2 = x; out3 = y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
verify("out3", NULL_TYPE);
}
public void testAssert5() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("goog.asserts.assert(x || y); out1 = x; out2 = y;");
verify("out1", startType);
verify("out2", startType);
}
public void testAssert6() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x.y", startType);
inFunction("out1 = x.y; goog.asserts.assert(x.y); out2 = x.y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert7() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(x);");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssert8() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(x != null);");
verify("out1", startType);
verify("out2", BOOLEAN_TYPE);
}
public void testAssert9() {
JSType startType = createNullableType(NUMBER_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(y = x);");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssert10() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x", startType);
assuming("y", startType);
inFunction("out1 = x; out2 = goog.asserts.assert(x && y); out3 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
verify("out3", OBJECT_TYPE);
}
public void testAssertNumber() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertNumber(x); out2 = x;");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssertNumber2() {
// Make sure it ignores expressions.
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("goog.asserts.assertNumber(x + x); out1 = x;");
verify("out1", startType);
}
public void testAssertNumber3() {
// Make sure it ignores expressions.
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assertNumber(x + x);");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssertString() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertString(x); out2 = x;");
verify("out1", startType);
verify("out2", STRING_TYPE);
}
public void testAssertFunction() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertFunction(x); out2 = x;");
verify("out1", startType);
verifySubtypeOf("out2", FUNCTION_INSTANCE_TYPE);
}
public void testAssertObject() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;");
verify("out1", startType);
verifySubtypeOf("out2", OBJECT_TYPE);
}
public void testAssertObject2() {
JSType startType = createNullableType(ARRAY_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertObject(x); out2 = x;");
verify("out1", startType);
verify("out2", ARRAY_TYPE);
}
public void testAssertObject3() {
JSType startType = createNullableType(OBJECT_TYPE);
assuming("x.y", startType);
inFunction("out1 = x.y; goog.asserts.assertObject(x.y); out2 = x.y;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssertObject4() {
JSType startType = createNullableType(ARRAY_TYPE);
assuming("x", startType);
inFunction("out1 = x; out2 = goog.asserts.assertObject(x);");
verify("out1", startType);
verify("out2", ARRAY_TYPE);
}
public void testAssertObject5() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction(
"out1 = x;" +
"out2 = /** @type {!Array} */ (goog.asserts.assertObject(x));");
verify("out1", startType);
verify("out2", ARRAY_TYPE);
}
public void testAssertArray() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertArray(x); out2 = x;");
verify("out1", startType);
verifySubtypeOf("out2", ARRAY_TYPE);
}
public void testAssertInstanceof1() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x); out2 = x;");
verify("out1", startType);
verify("out2", OBJECT_TYPE);
}
public void testAssertInstanceof2() {
JSType startType = createNullableType(ALL_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;");
verify("out1", startType);
verify("out2", STRING_OBJECT_TYPE);
}
public void testAssertInstanceof3() {
JSType startType = registry.getNativeType(UNKNOWN_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;");
verify("out1", startType);
verify("out2", UNKNOWN_TYPE);
}
public void testAssertInstanceof4() {
JSType startType = registry.getNativeType(STRING_OBJECT_TYPE);
assuming("x", startType);
inFunction("out1 = x; goog.asserts.assertInstanceof(x, Object); out2 = x;");
verify("out1", startType);
verify("out2", STRING_OBJECT_TYPE);
}
public void testAssertInstanceof5() {
JSType startType = registry.getNativeType(ALL_TYPE);
assuming("x", startType);
inFunction(
"out1 = x; goog.asserts.assertInstanceof(x, String); var r = x;");
verify("out1", startType);
verify("x", STRING_OBJECT_TYPE);
}
public void testAssertWithIsDef() {
JSType startType = createNullableType(NUMBER_TYPE);
assuming("x", startType);
inFunction(
"out1 = x;" +
"goog.asserts.assert(goog.isDefAndNotNull(x));" +
"out2 = x;");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testAssertWithNotIsNull() {
JSType startType = createNullableType(NUMBER_TYPE);
assuming("x", startType);
inFunction(
"out1 = x;" +
"goog.asserts.assert(!goog.isNull(x));" +
"out2 = x;");
verify("out1", startType);
verify("out2", NUMBER_TYPE);
}
public void testReturn1() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("if (x) { return x; }\nx = {};\nreturn x;");
verify("x", OBJECT_TYPE);
}
public void testReturn2() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("if (!x) { x = 0; }\nreturn x;");
verify("x", NUMBER_TYPE);
}
public void testWhile1() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("while (!x) { if (x == null) { x = 0; } else { x = 1; } }");
verify("x", NUMBER_TYPE);
}
public void testWhile2() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("while (!x) { x = {}; }");
verifySubtypeOf("x", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
}
public void testDo() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("do { x = 1; } while (!x);");
verify("x", NUMBER_TYPE);
}
public void testFor1() {
assuming("y", NUMBER_TYPE);
inFunction("var x = null; var i = null; for (i=y; !i; i=1) { x = 1; }");
verify("x", createNullableType(NUMBER_TYPE));
verify("i", NUMBER_TYPE);
}
public void testFor2() {
assuming("y", OBJECT_TYPE);
inFunction("var x = null; var i = null; for (i in y) { x = 1; }");
verify("x", createNullableType(NUMBER_TYPE));
verify("i", createNullableType(STRING_TYPE));
}
public void testFor3() {
assuming("y", OBJECT_TYPE);
inFunction("var x = null; var i = null; for (var i in y) { x = 1; }");
verify("x", createNullableType(NUMBER_TYPE));
verify("i", createNullableType(STRING_TYPE));
}
public void testFor4() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = {};\n" +
"if (x) { for (var i = 0; i < 10; i++) { break; } y = x; }");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testSwitch1() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; switch(x) {\n" +
"case 1: y = 1; break;\n" +
"case 2: y = {};\n" +
"case 3: y = {};\n" +
"default: y = 0;}");
verify("y", NUMBER_TYPE);
}
public void testSwitch2() {
assuming("x", ALL_TYPE);
inFunction("var y = null; switch (typeof x) {\n" +
"case 'string':\n" +
" y = x;\n" +
" return;" +
"default:\n" +
" y = 'a';\n" +
"}");
verify("y", STRING_TYPE);
}
public void testSwitch3() {
assuming("x",
createNullableType(createUnionType(NUMBER_TYPE, STRING_TYPE)));
inFunction("var y; var z; switch (typeof x) {\n" +
"case 'string':\n" +
" y = 1; z = null;\n" +
" return;\n" +
"case 'number':\n" +
" y = x; z = null;\n" +
" return;" +
"default:\n" +
" y = 1; z = x;\n" +
"}");
verify("y", NUMBER_TYPE);
verify("z", NULL_TYPE);
}
public void testSwitch4() {
assuming("x", ALL_TYPE);
inFunction("var y = null; switch (typeof x) {\n" +
"case 'string':\n" +
"case 'number':\n" +
" y = x;\n" +
" return;\n" +
"default:\n" +
" y = 1;\n" +
"}\n");
verify("y", createUnionType(NUMBER_TYPE, STRING_TYPE));
}
public void testCall1() {
assuming("x",
createNullableType(
registry.createFunctionType(registry.getNativeType(NUMBER_TYPE))));
inFunction("var y = x();");
verify("y", NUMBER_TYPE);
}
public void testNew1() {
assuming("x",
createNullableType(
registry.getNativeType(JSTypeNative.U2U_CONSTRUCTOR_TYPE)));
inFunction("var y = new x();");
verify("y", JSTypeNative.NO_OBJECT_TYPE);
}
public void testInnerFunction1() {
inFunction("var x = 1; function f() { x = null; };");
verify("x", NUMBER_TYPE);
}
public void testInnerFunction2() {
inFunction("var x = 1; var f = function() { x = null; };");
verify("x", NUMBER_TYPE);
}
public void testHook() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = x ? x : {};");
verifySubtypeOf("y", OBJECT_TYPE);
}
public void testThrow() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("var y = 1;\n" +
"if (x == null) { throw new Error('x is null') }\n" +
"y = x;");
verify("y", NUMBER_TYPE);
}
public void testTry1() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; try { y = null; } finally { y = x; }");
verify("y", NUMBER_TYPE);
}
public void testTry2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null;\n" +
"try { } catch (e) { y = null; } finally { y = x; }");
verify("y", NUMBER_TYPE);
}
public void testTry3() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; try { y = x; } catch (e) { }");
verify("y", NUMBER_TYPE);
}
public void testCatch1() {
inFunction("var y = null; try { foo(); } catch (e) { y = e; }");
verify("y", UNKNOWN_TYPE);
}
public void testCatch2() {
inFunction("var y = null; var e = 3; try { foo(); } catch (e) { y = e; }");
verify("y", UNKNOWN_TYPE);
}
public void testUnknownType1() {
inFunction("var y = 3; y = x;");
verify("y", UNKNOWN_TYPE);
}
public void testUnknownType2() {
assuming("x", ARRAY_TYPE);
inFunction("var y = 5; y = x[0];");
verify("y", UNKNOWN_TYPE);
}
public void testInfiniteLoop1() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("x = {}; while(x != null) { x = {}; }");
}
public void testInfiniteLoop2() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("x = {}; do { x = null; } while (x == null);");
}
public void testJoin1() {
JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE);
assuming("x", BOOLEAN_TYPE);
assuming("unknownOrNull", unknownOrNull);
inFunction("var y; if (x) y = unknownOrNull; else y = null;");
verify("y", unknownOrNull);
}
public void testJoin2() {
JSType unknownOrNull = createUnionType(NULL_TYPE, UNKNOWN_TYPE);
assuming("x", BOOLEAN_TYPE);
assuming("unknownOrNull", unknownOrNull);
inFunction("var y; if (x) y = null; else y = unknownOrNull;");
verify("y", unknownOrNull);
}
public void testArrayLit() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 3; if (x) { x = [y = x]; }");
verify("x", createUnionType(NULL_TYPE, ARRAY_TYPE));
verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE));
}
public void testGetElem() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 3; if (x) { x = x[y = x]; }");
verify("x", UNKNOWN_TYPE);
verify("y", createUnionType(NUMBER_TYPE, OBJECT_TYPE));
}
public void testEnumRAI1() {
JSType enumType = createEnumType("MyEnum", ARRAY_TYPE).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (x) y = x;");
verify("y", createNullableType(enumType));
}
public void testEnumRAI2() {
JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (typeof x == 'number') y = x;");
verify("y", createNullableType(enumType));
}
public void testEnumRAI3() {
JSType enumType = createEnumType("MyEnum", NUMBER_TYPE).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (x && typeof x == 'number') y = x;");
verify("y", createNullableType(enumType));
}
public void testEnumRAI4() {
JSType enumType = createEnumType("MyEnum",
createUnionType(STRING_TYPE, NUMBER_TYPE)).getElementsType();
assuming("x", enumType);
inFunction("var y = null; if (typeof x == 'number') y = x;");
verify("y", createNullableType(NUMBER_TYPE));
}
public void testShortCircuitingAnd() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; if (x && (y = 3)) { }");
verify("y", createNullableType(NUMBER_TYPE));
}
public void testShortCircuitingAnd2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; var z = 4; if (x && (y = 3)) { z = y; }");
verify("z", NUMBER_TYPE);
}
public void testShortCircuitingOr() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; if (x || (y = 3)) { }");
verify("y", createNullableType(NUMBER_TYPE));
}
public void testShortCircuitingOr2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = null; var z = 4; if (x || (y = 3)) { z = y; }");
verify("z", createNullableType(NUMBER_TYPE));
}
public void testAssignInCondition() {
assuming("x", createNullableType(NUMBER_TYPE));
inFunction("var y; if (!(y = x)) { y = 3; }");
verify("y", NUMBER_TYPE);
}
public void testInstanceOf1() {
assuming("x", OBJECT_TYPE);
inFunction("var y = null; if (x instanceof String) y = x;");
verify("y", createNullableType(STRING_OBJECT_TYPE));
}
public void testInstanceOf2() {
assuming("x", createNullableType(OBJECT_TYPE));
inFunction("var y = 1; if (x instanceof String) y = x;");
verify("y", createUnionType(STRING_OBJECT_TYPE, NUMBER_TYPE));
}
public void testInstanceOf3() {
assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE));
inFunction("var y = null; if (x instanceof String) y = x;");
verify("y", createNullableType(STRING_OBJECT_TYPE));
}
public void testInstanceOf4() {
assuming("x", createUnionType(STRING_OBJECT_TYPE, NUMBER_OBJECT_TYPE));
inFunction("var y = null; if (x instanceof String); else y = x;");
verify("y", createNullableType(NUMBER_OBJECT_TYPE));
}
public void testInstanceOf5() {
assuming("x", OBJECT_TYPE);
inFunction("var y = null; if (x instanceof String); else y = x;");
verify("y", createNullableType(OBJECT_TYPE));
}
public void testInstanceOf6() {
// Here we are using "instanceof" to restrict the unknown type to
// the type of the instance. This has the following problems:
// 1) The type may actually be any sub-type
// 2) The type may implement any interface
// After the instanceof we will require casts for methods that require
// sub-type or unrelated interfaces which would not have been required
// before.
JSType startType = registry.getNativeType(UNKNOWN_TYPE);
assuming("x", startType);
inFunction("out1 = x; if (x instanceof String) out2 = x;");
verify("out1", startType);
verify("out2", STRING_OBJECT_TYPE);
}
public void testFlattening() {
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
assuming("s" + i, ALL_TYPE);
}
assuming("b", JSTypeNative.BOOLEAN_TYPE);
StringBuilder body = new StringBuilder();
body.append("if (b) {");
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
body.append("s");
body.append(i);
body.append(" = 1;\n");
}
body.append(" } else { ");
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
body.append("s");
body.append(i);
body.append(" = 'ONE';\n");
}
body.append("}");
JSType numberORString = createUnionType(NUMBER_TYPE, STRING_TYPE);
inFunction(body.toString());
for (int i = 0; i < LinkedFlowScope.MAX_DEPTH + 1; i++) {
verify("s" + i, numberORString);
}
}
public void testUnary() {
assuming("x", NUMBER_TYPE);
inFunction("var y = +x;");
verify("y", NUMBER_TYPE);
inFunction("var z = -x;");
verify("z", NUMBER_TYPE);
}
public void testAdd1() {
assuming("x", NUMBER_TYPE);
inFunction("var y = x + 5;");
verify("y", NUMBER_TYPE);
}
public void testAdd2() {
assuming("x", NUMBER_TYPE);
inFunction("var y = x + '5';");
verify("y", STRING_TYPE);
}
public void testAdd3() {
assuming("x", NUMBER_TYPE);
inFunction("var y = '5' + x;");
verify("y", STRING_TYPE);
}
public void testAssignAdd() {
assuming("x", NUMBER_TYPE);
inFunction("x += '5';");
verify("x", STRING_TYPE);
}
public void testComparison() {
inFunction("var x = 'foo'; var y = (x = 3) < 4;");
verify("x", NUMBER_TYPE);
inFunction("var x = 'foo'; var y = (x = 3) > 4;");
verify("x", NUMBER_TYPE);
inFunction("var x = 'foo'; var y = (x = 3) <= 4;");
verify("x", NUMBER_TYPE);
inFunction("var x = 'foo'; var y = (x = 3) >= 4;");
verify("x", NUMBER_TYPE);
}
public void testThrownExpression() {
inFunction("var x = 'foo'; "
+ "try { throw new Error(x = 3); } catch (ex) {}");
verify("x", NUMBER_TYPE);
}
public void testObjectLit() {
inFunction("var x = {}; var out = x.a;");
verify("out", UNKNOWN_TYPE); // Shouldn't this be 'undefined'?
inFunction("var x = {a:1}; var out = x.a;");
verify("out", NUMBER_TYPE);
inFunction("var x = {a:1}; var out = x.a; x.a = 'string'; var out2 = x.a;");
verify("out", NUMBER_TYPE);
verify("out2", STRING_TYPE);
inFunction("var x = { get a() {return 1} }; var out = x.a;");
verify("out", UNKNOWN_TYPE);
inFunction(
"var x = {" +
" /** @return {number} */ get a() {return 1}" +
"};" +
"var out = x.a;");
verify("out", NUMBER_TYPE);
inFunction("var x = { set a(b) {} }; var out = x.a;");
verify("out", UNKNOWN_TYPE);
inFunction("var x = { " +
"/** @param {number} b */ set a(b) {} };" +
"var out = x.a;");
verify("out", NUMBER_TYPE);
}
public void testCast1() {
inFunction("var x = /** @type {Object} */ (this);");
verify("x", createNullableType(OBJECT_TYPE));
}
public void testCast2() {
inFunction(
"/** @return {boolean} */" +
"Object.prototype.method = function() { return true; };" +
"var x = /** @type {Object} */ (this).method;");
verify(
"x",
registry.createFunctionType(
registry.getNativeObjectType(OBJECT_TYPE),
registry.getNativeType(BOOLEAN_TYPE),
ImmutableList.<JSType>of() /* params */));
}
public void testBackwardsInferenceCall() {
inFunction(
"/** @param {{foo: (number|undefined)}} x */" +
"function f(x) {}" +
"var y = {};" +
"f(y);");
assertEquals("{foo: (number|undefined)}", getType("y").toString());
}
public void testBackwardsInferenceNew() {
inFunction(
"/**\n" +
" * @constructor\n" +
" * @param {{foo: (number|undefined)}} x\n" +
" */" +
"function F(x) {}" +
"var y = {};" +
"new F(y);");
assertEquals("{foo: (number|undefined)}", getType("y").toString());
}
public void testNoThisInference() {
JSType thisType = createNullableType(OBJECT_TYPE);
assumingThisType(thisType);
inFunction("var out = 3; if (goog.isNull(this)) out = this;");
verify("out", createUnionType(OBJECT_TYPE, NUMBER_TYPE));
}
} |
||
public void testClassKey() throws IOException
{
Map<Class<?>,Integer> map = new LinkedHashMap<Class<?>,Integer>();
map.put(String.class, 2);
String json = MAPPER.writeValueAsString(map);
assertEquals(aposToQuotes("{'java.lang.String':2}"), json);
} | com.fasterxml.jackson.databind.ser.TestMapSerialization::testClassKey | src/test/java/com/fasterxml/jackson/databind/ser/TestMapSerialization.java | 256 | src/test/java/com/fasterxml/jackson/databind/ser/TestMapSerialization.java | testClassKey | package com.fasterxml.jackson.databind.ser;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SuppressWarnings("serial")
public class TestMapSerialization
extends BaseMapTest
{
/**
* Class needed for testing [JACKSON-220]
*/
@JsonSerialize(using=MapSerializer.class)
static class PseudoMap extends LinkedHashMap<String,String>
{
public PseudoMap(String... values) {
for (int i = 0, len = values.length; i < len; i += 2) {
put(values[i], values[i+1]);
}
}
}
static class MapSerializer extends JsonSerializer<Map<String,String>>
{
@Override
public void serialize(Map<String,String> value,
JsonGenerator jgen,
SerializerProvider provider)
throws IOException
{
// just use standard Map.toString(), output as JSON String
jgen.writeString(value.toString());
}
}
// For [JACKSON-574]
static class DefaultKeySerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException
{
jgen.writeFieldName("DEFAULT:"+value);
}
}
// [#335]
static class MapOrderingBean {
@JsonPropertyOrder(alphabetic=true)
public LinkedHashMap<String,Integer> map;
public MapOrderingBean(String... keys) {
map = new LinkedHashMap<String,Integer>();
int ix = 1;
for (String key : keys) {
map.put(key, ix++);
}
}
}
// [Databind#565]: Support ser/deser of Map.Entry
static class StringIntMapEntry implements Map.Entry<String,Integer> {
public final String k;
public final Integer v;
public StringIntMapEntry(String k, Integer v) {
this.k = k;
this.v = v;
}
@Override
public String getKey() {
return k;
}
@Override
public Integer getValue() {
return v;
}
@Override
public Integer setValue(Integer value) {
throw new UnsupportedOperationException();
}
}
// [databind#527]
static class NoNullValuesMapContainer {
@JsonInclude(content=JsonInclude.Include.NON_NULL)
public Map<String,String> stuff = new LinkedHashMap<String,String>();
public NoNullValuesMapContainer add(String key, String value) {
stuff.put(key, value);
return this;
}
}
// [databind#527]
@JsonInclude(content=JsonInclude.Include.NON_NULL)
static class NoNullsStringMap extends LinkedHashMap<String,String> {
public NoNullsStringMap add(String key, String value) {
put(key, value);
return this;
}
}
@JsonInclude(content=JsonInclude.Include.NON_EMPTY)
static class NoEmptyStringsMap extends LinkedHashMap<String,String> {
public NoEmptyStringsMap add(String key, String value) {
put(key, value);
return this;
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
final private ObjectMapper MAPPER = objectMapper();
public void testUsingObjectWriter() throws IOException
{
ObjectWriter w = MAPPER.writerFor(Object.class);
Map<String,Object> map = new LinkedHashMap<String,Object>();
map.put("a", 1);
String json = w.writeValueAsString(map);
assertEquals(aposToQuotes("{'a':1}"), json);
}
// Test [JACKSON-220]
public void testMapSerializer() throws IOException
{
assertEquals("\"{a=b, c=d}\"", MAPPER.writeValueAsString(new PseudoMap("a", "b", "c", "d")));
}
// Test [JACKSON-314]
public void testMapNullSerialization() throws IOException
{
ObjectMapper m = new ObjectMapper();
Map<String,String> map = new HashMap<String,String>();
map.put("a", null);
// by default, should output null-valued entries:
assertEquals("{\"a\":null}", m.writeValueAsString(map));
// but not if explicitly asked not to (note: config value is dynamic here)
m.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
assertEquals("{}", m.writeValueAsString(map));
}
// [JACKSON-499], problems with map entries, values
public void testMapKeyValueSerialization() throws IOException
{
Map<String,String> map = new HashMap<String,String>();
map.put("a", "b");
assertEquals("[\"a\"]", MAPPER.writeValueAsString(map.keySet()));
assertEquals("[\"b\"]", MAPPER.writeValueAsString(map.values()));
// TreeMap has similar inner class(es):
map = new TreeMap<String,String>();
map.put("c", "d");
assertEquals("[\"c\"]", MAPPER.writeValueAsString(map.keySet()));
assertEquals("[\"d\"]", MAPPER.writeValueAsString(map.values()));
// and for [JACKSON-533], same for concurrent maps
map = new ConcurrentHashMap<String,String>();
map.put("e", "f");
assertEquals("[\"e\"]", MAPPER.writeValueAsString(map.keySet()));
assertEquals("[\"f\"]", MAPPER.writeValueAsString(map.values()));
}
// For [JACKSON-574]
public void testDefaultKeySerializer() throws IOException
{
ObjectMapper m = new ObjectMapper();
m.getSerializerProvider().setDefaultKeySerializer(new DefaultKeySerializer());
Map<String,String> map = new HashMap<String,String>();
map.put("a", "b");
assertEquals("{\"DEFAULT:a\":\"b\"}", m.writeValueAsString(map));
}
// [JACKSON-636]: sort Map entries by key
public void testOrderByKey() throws IOException
{
ObjectMapper m = new ObjectMapper();
assertFalse(m.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS));
LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
map.put("b", 3);
map.put("a", 6);
// by default, no (re)ordering:
assertEquals("{\"b\":3,\"a\":6}", m.writeValueAsString(map));
// but can be changed
assertEquals("{\"a\":6,\"b\":3}", m.writer(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValueAsString(map));
}
// [Databind#335]
public void testOrderByKeyViaProperty() throws IOException
{
MapOrderingBean input = new MapOrderingBean("c", "b", "a");
String json = MAPPER.writeValueAsString(input);
assertEquals(aposToQuotes("{'map':{'a':3,'b':2,'c':1}}"), json);
}
// [Databind#565]
public void testEnumMapEntry() throws IOException
{
StringIntMapEntry input = new StringIntMapEntry("answer", 42);
String json = MAPPER.writeValueAsString(input);
assertEquals(aposToQuotes("{'answer':42}"), json);
StringIntMapEntry[] array = new StringIntMapEntry[] { input };
json = MAPPER.writeValueAsString(array);
assertEquals(aposToQuotes("[{'answer':42}]"), json);
}
// [databind#527]
public void testNonNullValueMap() throws IOException
{
String json = MAPPER.writeValueAsString(new NoNullsStringMap()
.add("a", "foo")
.add("b", null)
.add("c", "bar"));
assertEquals(aposToQuotes("{'a':'foo','c':'bar'}"), json);
}
// [databind#527]
public void testNonEmptyValueMap() throws IOException
{
String json = MAPPER.writeValueAsString(new NoEmptyStringsMap()
.add("a", "foo")
.add("b", "bar")
.add("c", ""));
assertEquals(aposToQuotes("{'a':'foo','b':'bar'}"), json);
}
// [databind#527]
public void testNonNullValueMapViaProp() throws IOException
{
String json = MAPPER.writeValueAsString(new NoNullValuesMapContainer()
.add("a", "foo")
.add("b", null)
.add("c", "bar"));
assertEquals(aposToQuotes("{'stuff':{'a':'foo','c':'bar'}}"), json);
}
public void testClassKey() throws IOException
{
Map<Class<?>,Integer> map = new LinkedHashMap<Class<?>,Integer>();
map.put(String.class, 2);
String json = MAPPER.writeValueAsString(map);
assertEquals(aposToQuotes("{'java.lang.String':2}"), json);
}
} | // You are a professional Java test case writer, please create a test case named `testClassKey` for the issue `JacksonDatabind-682`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-682
//
// ## Issue-Title:
// Deserializing Map<Class<? extends Object>, String>
//
// ## Issue-Description:
// I am having problems deserializing my `Map<Class<? extends Object>, String>`. Simple test case demonstrates it:
//
//
//
// ```
// @Test
// public void testMapWithClassAsKey() throws Exception {
// Map<Class<? extends Object>, String> map = new HashMap<>();
// map.put(ArrayList.class, "ArrayList");
// map.put(HashMap.class, "HashMap");
//
// ObjectMapper mapper = new ObjectMapper();
//
// String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
// System.out.println(json);
// mapper.readValue(json, new TypeReference<Map<Class<? extends Object>, String>>(){});
// }
// ```
//
// This test serializes the map as:
//
//
//
// ```
// {
// "class java.util.ArrayList" : "ArrayList",
// "class java.util.HashMap" : "HashMap"
// }
// ```
//
// `mapper.readValue(json, new TypeReference<Map<Class<? extends Object>, String>>(){});` then throws a `Exception`:
//
//
//
// ```
// com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct Map key of type java.lang.Class from String "class java.util.ArrayList": not a valid representation: Can not construct Map key of type java.lang.Class from String "class java.util.ArrayList": unable to parse key as Class
// at [Source: ...
//
// ```
//
// As i understood from [#630](https://github.com/FasterXML/jackson-databind/issues/630) the KeyDeserializer for Class should be part of Jackson. Am I missing something?
//
//
//
//
public void testClassKey() throws IOException {
| 256 | 9 | 250 | src/test/java/com/fasterxml/jackson/databind/ser/TestMapSerialization.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-682
## Issue-Title:
Deserializing Map<Class<? extends Object>, String>
## Issue-Description:
I am having problems deserializing my `Map<Class<? extends Object>, String>`. Simple test case demonstrates it:
```
@Test
public void testMapWithClassAsKey() throws Exception {
Map<Class<? extends Object>, String> map = new HashMap<>();
map.put(ArrayList.class, "ArrayList");
map.put(HashMap.class, "HashMap");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
System.out.println(json);
mapper.readValue(json, new TypeReference<Map<Class<? extends Object>, String>>(){});
}
```
This test serializes the map as:
```
{
"class java.util.ArrayList" : "ArrayList",
"class java.util.HashMap" : "HashMap"
}
```
`mapper.readValue(json, new TypeReference<Map<Class<? extends Object>, String>>(){});` then throws a `Exception`:
```
com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct Map key of type java.lang.Class from String "class java.util.ArrayList": not a valid representation: Can not construct Map key of type java.lang.Class from String "class java.util.ArrayList": unable to parse key as Class
at [Source: ...
```
As i understood from [#630](https://github.com/FasterXML/jackson-databind/issues/630) the KeyDeserializer for Class should be part of Jackson. Am I missing something?
```
You are a professional Java test case writer, please create a test case named `testClassKey` for the issue `JacksonDatabind-682`, utilizing the provided issue report information and the following function signature.
```java
public void testClassKey() throws IOException {
```
| 250 | [
"com.fasterxml.jackson.databind.ser.std.StdKeySerializer"
] | 4f7aeda1290e99242e67dee093c55ba4489a466883d3be4121a0c6499c6de9bb | public void testClassKey() throws IOException
| // You are a professional Java test case writer, please create a test case named `testClassKey` for the issue `JacksonDatabind-682`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-682
//
// ## Issue-Title:
// Deserializing Map<Class<? extends Object>, String>
//
// ## Issue-Description:
// I am having problems deserializing my `Map<Class<? extends Object>, String>`. Simple test case demonstrates it:
//
//
//
// ```
// @Test
// public void testMapWithClassAsKey() throws Exception {
// Map<Class<? extends Object>, String> map = new HashMap<>();
// map.put(ArrayList.class, "ArrayList");
// map.put(HashMap.class, "HashMap");
//
// ObjectMapper mapper = new ObjectMapper();
//
// String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(map);
// System.out.println(json);
// mapper.readValue(json, new TypeReference<Map<Class<? extends Object>, String>>(){});
// }
// ```
//
// This test serializes the map as:
//
//
//
// ```
// {
// "class java.util.ArrayList" : "ArrayList",
// "class java.util.HashMap" : "HashMap"
// }
// ```
//
// `mapper.readValue(json, new TypeReference<Map<Class<? extends Object>, String>>(){});` then throws a `Exception`:
//
//
//
// ```
// com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct Map key of type java.lang.Class from String "class java.util.ArrayList": not a valid representation: Can not construct Map key of type java.lang.Class from String "class java.util.ArrayList": unable to parse key as Class
// at [Source: ...
//
// ```
//
// As i understood from [#630](https://github.com/FasterXML/jackson-databind/issues/630) the KeyDeserializer for Class should be part of Jackson. Am I missing something?
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.ser;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@SuppressWarnings("serial")
public class TestMapSerialization
extends BaseMapTest
{
/**
* Class needed for testing [JACKSON-220]
*/
@JsonSerialize(using=MapSerializer.class)
static class PseudoMap extends LinkedHashMap<String,String>
{
public PseudoMap(String... values) {
for (int i = 0, len = values.length; i < len; i += 2) {
put(values[i], values[i+1]);
}
}
}
static class MapSerializer extends JsonSerializer<Map<String,String>>
{
@Override
public void serialize(Map<String,String> value,
JsonGenerator jgen,
SerializerProvider provider)
throws IOException
{
// just use standard Map.toString(), output as JSON String
jgen.writeString(value.toString());
}
}
// For [JACKSON-574]
static class DefaultKeySerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException
{
jgen.writeFieldName("DEFAULT:"+value);
}
}
// [#335]
static class MapOrderingBean {
@JsonPropertyOrder(alphabetic=true)
public LinkedHashMap<String,Integer> map;
public MapOrderingBean(String... keys) {
map = new LinkedHashMap<String,Integer>();
int ix = 1;
for (String key : keys) {
map.put(key, ix++);
}
}
}
// [Databind#565]: Support ser/deser of Map.Entry
static class StringIntMapEntry implements Map.Entry<String,Integer> {
public final String k;
public final Integer v;
public StringIntMapEntry(String k, Integer v) {
this.k = k;
this.v = v;
}
@Override
public String getKey() {
return k;
}
@Override
public Integer getValue() {
return v;
}
@Override
public Integer setValue(Integer value) {
throw new UnsupportedOperationException();
}
}
// [databind#527]
static class NoNullValuesMapContainer {
@JsonInclude(content=JsonInclude.Include.NON_NULL)
public Map<String,String> stuff = new LinkedHashMap<String,String>();
public NoNullValuesMapContainer add(String key, String value) {
stuff.put(key, value);
return this;
}
}
// [databind#527]
@JsonInclude(content=JsonInclude.Include.NON_NULL)
static class NoNullsStringMap extends LinkedHashMap<String,String> {
public NoNullsStringMap add(String key, String value) {
put(key, value);
return this;
}
}
@JsonInclude(content=JsonInclude.Include.NON_EMPTY)
static class NoEmptyStringsMap extends LinkedHashMap<String,String> {
public NoEmptyStringsMap add(String key, String value) {
put(key, value);
return this;
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
final private ObjectMapper MAPPER = objectMapper();
public void testUsingObjectWriter() throws IOException
{
ObjectWriter w = MAPPER.writerFor(Object.class);
Map<String,Object> map = new LinkedHashMap<String,Object>();
map.put("a", 1);
String json = w.writeValueAsString(map);
assertEquals(aposToQuotes("{'a':1}"), json);
}
// Test [JACKSON-220]
public void testMapSerializer() throws IOException
{
assertEquals("\"{a=b, c=d}\"", MAPPER.writeValueAsString(new PseudoMap("a", "b", "c", "d")));
}
// Test [JACKSON-314]
public void testMapNullSerialization() throws IOException
{
ObjectMapper m = new ObjectMapper();
Map<String,String> map = new HashMap<String,String>();
map.put("a", null);
// by default, should output null-valued entries:
assertEquals("{\"a\":null}", m.writeValueAsString(map));
// but not if explicitly asked not to (note: config value is dynamic here)
m.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
assertEquals("{}", m.writeValueAsString(map));
}
// [JACKSON-499], problems with map entries, values
public void testMapKeyValueSerialization() throws IOException
{
Map<String,String> map = new HashMap<String,String>();
map.put("a", "b");
assertEquals("[\"a\"]", MAPPER.writeValueAsString(map.keySet()));
assertEquals("[\"b\"]", MAPPER.writeValueAsString(map.values()));
// TreeMap has similar inner class(es):
map = new TreeMap<String,String>();
map.put("c", "d");
assertEquals("[\"c\"]", MAPPER.writeValueAsString(map.keySet()));
assertEquals("[\"d\"]", MAPPER.writeValueAsString(map.values()));
// and for [JACKSON-533], same for concurrent maps
map = new ConcurrentHashMap<String,String>();
map.put("e", "f");
assertEquals("[\"e\"]", MAPPER.writeValueAsString(map.keySet()));
assertEquals("[\"f\"]", MAPPER.writeValueAsString(map.values()));
}
// For [JACKSON-574]
public void testDefaultKeySerializer() throws IOException
{
ObjectMapper m = new ObjectMapper();
m.getSerializerProvider().setDefaultKeySerializer(new DefaultKeySerializer());
Map<String,String> map = new HashMap<String,String>();
map.put("a", "b");
assertEquals("{\"DEFAULT:a\":\"b\"}", m.writeValueAsString(map));
}
// [JACKSON-636]: sort Map entries by key
public void testOrderByKey() throws IOException
{
ObjectMapper m = new ObjectMapper();
assertFalse(m.isEnabled(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS));
LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
map.put("b", 3);
map.put("a", 6);
// by default, no (re)ordering:
assertEquals("{\"b\":3,\"a\":6}", m.writeValueAsString(map));
// but can be changed
assertEquals("{\"a\":6,\"b\":3}", m.writer(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS).writeValueAsString(map));
}
// [Databind#335]
public void testOrderByKeyViaProperty() throws IOException
{
MapOrderingBean input = new MapOrderingBean("c", "b", "a");
String json = MAPPER.writeValueAsString(input);
assertEquals(aposToQuotes("{'map':{'a':3,'b':2,'c':1}}"), json);
}
// [Databind#565]
public void testEnumMapEntry() throws IOException
{
StringIntMapEntry input = new StringIntMapEntry("answer", 42);
String json = MAPPER.writeValueAsString(input);
assertEquals(aposToQuotes("{'answer':42}"), json);
StringIntMapEntry[] array = new StringIntMapEntry[] { input };
json = MAPPER.writeValueAsString(array);
assertEquals(aposToQuotes("[{'answer':42}]"), json);
}
// [databind#527]
public void testNonNullValueMap() throws IOException
{
String json = MAPPER.writeValueAsString(new NoNullsStringMap()
.add("a", "foo")
.add("b", null)
.add("c", "bar"));
assertEquals(aposToQuotes("{'a':'foo','c':'bar'}"), json);
}
// [databind#527]
public void testNonEmptyValueMap() throws IOException
{
String json = MAPPER.writeValueAsString(new NoEmptyStringsMap()
.add("a", "foo")
.add("b", "bar")
.add("c", ""));
assertEquals(aposToQuotes("{'a':'foo','b':'bar'}"), json);
}
// [databind#527]
public void testNonNullValueMapViaProp() throws IOException
{
String json = MAPPER.writeValueAsString(new NoNullValuesMapContainer()
.add("a", "foo")
.add("b", null)
.add("c", "bar"));
assertEquals(aposToQuotes("{'stuff':{'a':'foo','c':'bar'}}"), json);
}
public void testClassKey() throws IOException
{
Map<Class<?>,Integer> map = new LinkedHashMap<Class<?>,Integer>();
map.put(String.class, 2);
String json = MAPPER.writeValueAsString(map);
assertEquals(aposToQuotes("{'java.lang.String':2}"), json);
}
} |
||
public void testCodec101() throws Exception {
byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3);
ByteArrayInputStream bais = new ByteArrayInputStream(codec101);
Base64InputStream in = new Base64InputStream(bais);
byte[] result = new byte[8192];
int c = in.read(result);
assertTrue("Codec101: First read successful [c=" + c + "]", c > 0);
c = in.read(result);
assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0);
} | org.apache.commons.codec.binary.Base64InputStreamTest::testCodec101 | src/test/org/apache/commons/codec/binary/Base64InputStreamTest.java | 64 | src/test/org/apache/commons/codec/binary/Base64InputStreamTest.java | testCodec101 | /*
* 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.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import junit.framework.TestCase;
/**
* @author Apache Software Foundation
* @version $Id $
* @since 1.4
*/
public class Base64InputStreamTest extends TestCase {
private final static byte[] CRLF = {(byte) '\r', (byte) '\n'};
private final static byte[] LF = {(byte) '\n'};
private static final String STRING_FIXTURE = "Hello World";
/**
* Construct a new instance of this test case.
*
* @param name
* Name of the test case
*/
public Base64InputStreamTest(String name) {
super(name);
}
/**
* Test for the CODEC-101 bug: InputStream.read(byte[]) should never return 0
* because Java's builtin InputStreamReader hates that.
*
* @throws Exception for some failure scenarios.
*/
public void testCodec101() throws Exception {
byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3);
ByteArrayInputStream bais = new ByteArrayInputStream(codec101);
Base64InputStream in = new Base64InputStream(bais);
byte[] result = new byte[8192];
int c = in.read(result);
assertTrue("Codec101: First read successful [c=" + c + "]", c > 0);
c = in.read(result);
assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0);
}
/**
* Test the Base64InputStream implementation against the special NPE inducing input
* identified in the CODEC-98 bug.
*
* @throws Exception for some failure scenarios.
*/
public void testCodec98NPE() throws Exception {
byte[] codec98 = StringUtils.getBytesUtf8(Base64TestData.CODEC_98_NPE);
ByteArrayInputStream data = new ByteArrayInputStream(codec98);
Base64InputStream stream = new Base64InputStream(data);
// This line causes an NPE in commons-codec-1.4.jar:
byte[] decodedBytes = Base64TestData.streamToBytes(stream, new byte[1024]);
String decoded = StringUtils.newStringUtf8(decodedBytes);
assertEquals(
"codec-98 NPE Base64InputStream", Base64TestData.CODEC_98_NPE_DECODED, decoded
);
}
/**
* Tests the Base64InputStream implementation against empty input.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64EmptyInputStreamMimeChuckSize() throws Exception {
testBase64EmptyInputStream(Base64.MIME_CHUNK_SIZE);
}
/**
* Tests the Base64InputStream implementation against empty input.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64EmptyInputStreamPemChuckSize() throws Exception {
testBase64EmptyInputStream(Base64.PEM_CHUNK_SIZE);
}
private void testBase64EmptyInputStream(int chuckSize) throws Exception {
byte[] emptyEncoded = new byte[0];
byte[] emptyDecoded = new byte[0];
testByteByByte(emptyEncoded, emptyDecoded, chuckSize, CRLF);
testByChunk(emptyEncoded, emptyDecoded, chuckSize, CRLF);
}
/**
* Tests the Base64InputStream implementation.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64InputStreamByChunk() throws Exception {
// Hello World test.
byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n");
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
testByChunk(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// Single Byte test.
encoded = StringUtils.getBytesUtf8("AA==\r\n");
decoded = new byte[]{(byte) 0};
testByChunk(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// OpenSSL interop test.
encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE);
decoded = Base64TestData.DECODED;
testByChunk(encoded, decoded, Base64.PEM_CHUNK_SIZE, LF);
// Single Line test.
String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", "");
encoded = StringUtils.getBytesUtf8(singleLine);
decoded = Base64TestData.DECODED;
testByChunk(encoded, decoded, 0, LF);
// test random data of sizes 0 thru 150
for (int i = 0; i <= 150; i++) {
byte[][] randomData = Base64TestData.randomData(i, false);
encoded = randomData[1];
decoded = randomData[0];
testByChunk(encoded, decoded, 0, LF);
}
}
/**
* Tests the Base64InputStream implementation.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64InputStreamByteByByte() throws Exception {
// Hello World test.
byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n");
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
testByteByByte(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// Single Byte test.
encoded = StringUtils.getBytesUtf8("AA==\r\n");
decoded = new byte[]{(byte) 0};
testByteByByte(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// OpenSSL interop test.
encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE);
decoded = Base64TestData.DECODED;
testByteByByte(encoded, decoded, Base64.PEM_CHUNK_SIZE, LF);
// Single Line test.
String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", "");
encoded = StringUtils.getBytesUtf8(singleLine);
decoded = Base64TestData.DECODED;
testByteByByte(encoded, decoded, 0, LF);
// test random data of sizes 0 thru 150
for (int i = 0; i <= 150; i++) {
byte[][] randomData = Base64TestData.randomData(i, false);
encoded = randomData[1];
decoded = randomData[0];
testByteByByte(encoded, decoded, 0, LF);
}
}
/**
* Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]-->
* encoded 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded
* <p/>
* By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64InputStream wraps itself in encode and decode mode
* over and over again.
*
* @param encoded
* base64 encoded data
* @param decoded
* the data from above, but decoded
* @param chunkSize
* chunk size (line-length) of the base64 encoded data.
* @param seperator
* Line separator in the base64 encoded data.
* @throws Exception
* Usually signifies a bug in the Base64 commons-codec implementation.
*/
private void testByChunk(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception {
// Start with encode.
InputStream in = new ByteArrayInputStream(decoded);
in = new Base64InputStream(in, true, chunkSize, seperator);
byte[] output = Base64TestData.streamToBytes(in);
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 encode", Arrays.equals(output, encoded));
// Now let's try decode.
in = new ByteArrayInputStream(encoded);
in = new Base64InputStream(in);
output = Base64TestData.streamToBytes(in);
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 decode", Arrays.equals(output, decoded));
// I always wanted to do this! (wrap encoder with decoder etc etc).
in = new ByteArrayInputStream(decoded);
for (int i = 0; i < 10; i++) {
in = new Base64InputStream(in, true, chunkSize, seperator);
in = new Base64InputStream(in, false);
}
output = Base64TestData.streamToBytes(in);
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded));
}
/**
* Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]-->
* encoded 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded
* <p/>
* By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64InputStream wraps itself in encode and decode mode
* over and over again.
*
* @param encoded
* base64 encoded data
* @param decoded
* the data from above, but decoded
* @param chunkSize
* chunk size (line-length) of the base64 encoded data.
* @param seperator
* Line separator in the base64 encoded data.
* @throws Exception
* Usually signifies a bug in the Base64 commons-codec implementation.
*/
private void testByteByByte(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception {
// Start with encode.
InputStream in = new ByteArrayInputStream(decoded);
in = new Base64InputStream(in, true, chunkSize, seperator);
byte[] output = new byte[encoded.length];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) in.read();
}
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 encode", Arrays.equals(output, encoded));
// Now let's try decode.
in = new ByteArrayInputStream(encoded);
in = new Base64InputStream(in);
output = new byte[decoded.length];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) in.read();
}
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 decode", Arrays.equals(output, decoded));
// I always wanted to do this! (wrap encoder with decoder etc etc).
in = new ByteArrayInputStream(decoded);
for (int i = 0; i < 10; i++) {
in = new Base64InputStream(in, true, chunkSize, seperator);
in = new Base64InputStream(in, false);
}
output = new byte[decoded.length];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) in.read();
}
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded));
}
/**
* Tests markSupported.
*
* @throws Exception
*/
public void testMarkSupported() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
// Always returns false for now.
assertFalse("Base64InputStream.markSupported() is false", in.markSupported());
}
/**
* Tests read returning 0
*
* @throws Exception
*/
public void testRead0() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
byte[] buf = new byte[1024];
int bytesRead = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
bytesRead = in.read(buf, 0, 0);
assertEquals("Base64InputStream.read(buf, 0, 0) returns 0", 0, bytesRead);
}
/**
* Tests read with null.
*
* @throws Exception
* for some failure scenarios.
*/
public void testReadNull() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
try {
in.read(null, 0, 0);
fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
}
/**
* Tests read throwing IndexOutOfBoundsException
*
* @throws Exception
*/
public void testReadOutOfBounds() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
byte[] buf = new byte[1024];
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
try {
in.read(buf, -1, 0);
fail("Expected Base64InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
in.read(buf, 0, -1);
fail("Expected Base64InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
in.read(buf, buf.length + 1, 0);
fail("Base64InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
in.read(buf, buf.length - 1, 2);
fail("Base64InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
}
} | // You are a professional Java test case writer, please create a test case named `testCodec101` for the issue `Codec-CODEC-101`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-101
//
// ## Issue-Title:
// Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long
//
// ## Issue-Description:
//
// Using new InputStreamReader(new Base64InputStream(in, true)) sometimes fails with "java.io.IOException: Underlying input stream returned zero bytes".
//
//
// This is been tracked down that Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long.
//
//
//
//
//
public void testCodec101() throws Exception {
| 64 | /**
* Test for the CODEC-101 bug: InputStream.read(byte[]) should never return 0
* because Java's builtin InputStreamReader hates that.
*
* @throws Exception for some failure scenarios.
*/ | 6 | 54 | src/test/org/apache/commons/codec/binary/Base64InputStreamTest.java | src/test | ```markdown
## Issue-ID: Codec-CODEC-101
## Issue-Title:
Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long
## Issue-Description:
Using new InputStreamReader(new Base64InputStream(in, true)) sometimes fails with "java.io.IOException: Underlying input stream returned zero bytes".
This is been tracked down that Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long.
```
You are a professional Java test case writer, please create a test case named `testCodec101` for the issue `Codec-CODEC-101`, utilizing the provided issue report information and the following function signature.
```java
public void testCodec101() throws Exception {
```
| 54 | [
"org.apache.commons.codec.binary.Base64InputStream"
] | 4fc05c0e0e3fa74a5ecb6ba47f6c140ad69ea430ffc4b9729424ce8732ce4e5b | public void testCodec101() throws Exception | // You are a professional Java test case writer, please create a test case named `testCodec101` for the issue `Codec-CODEC-101`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-101
//
// ## Issue-Title:
// Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long
//
// ## Issue-Description:
//
// Using new InputStreamReader(new Base64InputStream(in, true)) sometimes fails with "java.io.IOException: Underlying input stream returned zero bytes".
//
//
// This is been tracked down that Base64InputStream#read(byte[]) incorrectly returns 0 at end of any stream which is multiple of 3 bytes long.
//
//
//
//
//
| 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.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import junit.framework.TestCase;
/**
* @author Apache Software Foundation
* @version $Id $
* @since 1.4
*/
public class Base64InputStreamTest extends TestCase {
private final static byte[] CRLF = {(byte) '\r', (byte) '\n'};
private final static byte[] LF = {(byte) '\n'};
private static final String STRING_FIXTURE = "Hello World";
/**
* Construct a new instance of this test case.
*
* @param name
* Name of the test case
*/
public Base64InputStreamTest(String name) {
super(name);
}
/**
* Test for the CODEC-101 bug: InputStream.read(byte[]) should never return 0
* because Java's builtin InputStreamReader hates that.
*
* @throws Exception for some failure scenarios.
*/
public void testCodec101() throws Exception {
byte[] codec101 = StringUtils.getBytesUtf8(Base64TestData.CODEC_101_MULTIPLE_OF_3);
ByteArrayInputStream bais = new ByteArrayInputStream(codec101);
Base64InputStream in = new Base64InputStream(bais);
byte[] result = new byte[8192];
int c = in.read(result);
assertTrue("Codec101: First read successful [c=" + c + "]", c > 0);
c = in.read(result);
assertTrue("Codec101: Second read should report end-of-stream [c=" + c + "]", c < 0);
}
/**
* Test the Base64InputStream implementation against the special NPE inducing input
* identified in the CODEC-98 bug.
*
* @throws Exception for some failure scenarios.
*/
public void testCodec98NPE() throws Exception {
byte[] codec98 = StringUtils.getBytesUtf8(Base64TestData.CODEC_98_NPE);
ByteArrayInputStream data = new ByteArrayInputStream(codec98);
Base64InputStream stream = new Base64InputStream(data);
// This line causes an NPE in commons-codec-1.4.jar:
byte[] decodedBytes = Base64TestData.streamToBytes(stream, new byte[1024]);
String decoded = StringUtils.newStringUtf8(decodedBytes);
assertEquals(
"codec-98 NPE Base64InputStream", Base64TestData.CODEC_98_NPE_DECODED, decoded
);
}
/**
* Tests the Base64InputStream implementation against empty input.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64EmptyInputStreamMimeChuckSize() throws Exception {
testBase64EmptyInputStream(Base64.MIME_CHUNK_SIZE);
}
/**
* Tests the Base64InputStream implementation against empty input.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64EmptyInputStreamPemChuckSize() throws Exception {
testBase64EmptyInputStream(Base64.PEM_CHUNK_SIZE);
}
private void testBase64EmptyInputStream(int chuckSize) throws Exception {
byte[] emptyEncoded = new byte[0];
byte[] emptyDecoded = new byte[0];
testByteByByte(emptyEncoded, emptyDecoded, chuckSize, CRLF);
testByChunk(emptyEncoded, emptyDecoded, chuckSize, CRLF);
}
/**
* Tests the Base64InputStream implementation.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64InputStreamByChunk() throws Exception {
// Hello World test.
byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n");
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
testByChunk(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// Single Byte test.
encoded = StringUtils.getBytesUtf8("AA==\r\n");
decoded = new byte[]{(byte) 0};
testByChunk(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// OpenSSL interop test.
encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE);
decoded = Base64TestData.DECODED;
testByChunk(encoded, decoded, Base64.PEM_CHUNK_SIZE, LF);
// Single Line test.
String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", "");
encoded = StringUtils.getBytesUtf8(singleLine);
decoded = Base64TestData.DECODED;
testByChunk(encoded, decoded, 0, LF);
// test random data of sizes 0 thru 150
for (int i = 0; i <= 150; i++) {
byte[][] randomData = Base64TestData.randomData(i, false);
encoded = randomData[1];
decoded = randomData[0];
testByChunk(encoded, decoded, 0, LF);
}
}
/**
* Tests the Base64InputStream implementation.
*
* @throws Exception
* for some failure scenarios.
*/
public void testBase64InputStreamByteByByte() throws Exception {
// Hello World test.
byte[] encoded = StringUtils.getBytesUtf8("SGVsbG8gV29ybGQ=\r\n");
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
testByteByByte(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// Single Byte test.
encoded = StringUtils.getBytesUtf8("AA==\r\n");
decoded = new byte[]{(byte) 0};
testByteByByte(encoded, decoded, Base64.MIME_CHUNK_SIZE, CRLF);
// OpenSSL interop test.
encoded = StringUtils.getBytesUtf8(Base64TestData.ENCODED_64_CHARS_PER_LINE);
decoded = Base64TestData.DECODED;
testByteByByte(encoded, decoded, Base64.PEM_CHUNK_SIZE, LF);
// Single Line test.
String singleLine = Base64TestData.ENCODED_64_CHARS_PER_LINE.replaceAll("\n", "");
encoded = StringUtils.getBytesUtf8(singleLine);
decoded = Base64TestData.DECODED;
testByteByByte(encoded, decoded, 0, LF);
// test random data of sizes 0 thru 150
for (int i = 0; i <= 150; i++) {
byte[][] randomData = Base64TestData.randomData(i, false);
encoded = randomData[1];
decoded = randomData[0];
testByteByByte(encoded, decoded, 0, LF);
}
}
/**
* Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]-->
* encoded 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded
* <p/>
* By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64InputStream wraps itself in encode and decode mode
* over and over again.
*
* @param encoded
* base64 encoded data
* @param decoded
* the data from above, but decoded
* @param chunkSize
* chunk size (line-length) of the base64 encoded data.
* @param seperator
* Line separator in the base64 encoded data.
* @throws Exception
* Usually signifies a bug in the Base64 commons-codec implementation.
*/
private void testByChunk(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception {
// Start with encode.
InputStream in = new ByteArrayInputStream(decoded);
in = new Base64InputStream(in, true, chunkSize, seperator);
byte[] output = Base64TestData.streamToBytes(in);
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 encode", Arrays.equals(output, encoded));
// Now let's try decode.
in = new ByteArrayInputStream(encoded);
in = new Base64InputStream(in);
output = Base64TestData.streamToBytes(in);
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 decode", Arrays.equals(output, decoded));
// I always wanted to do this! (wrap encoder with decoder etc etc).
in = new ByteArrayInputStream(decoded);
for (int i = 0; i < 10; i++) {
in = new Base64InputStream(in, true, chunkSize, seperator);
in = new Base64InputStream(in, false);
}
output = Base64TestData.streamToBytes(in);
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded));
}
/**
* Tests method does three tests on the supplied data: 1. encoded ---[DECODE]--> decoded 2. decoded ---[ENCODE]-->
* encoded 3. decoded ---[WRAP-WRAP-WRAP-etc...] --> decoded
* <p/>
* By "[WRAP-WRAP-WRAP-etc...]" we mean situation where the Base64InputStream wraps itself in encode and decode mode
* over and over again.
*
* @param encoded
* base64 encoded data
* @param decoded
* the data from above, but decoded
* @param chunkSize
* chunk size (line-length) of the base64 encoded data.
* @param seperator
* Line separator in the base64 encoded data.
* @throws Exception
* Usually signifies a bug in the Base64 commons-codec implementation.
*/
private void testByteByByte(byte[] encoded, byte[] decoded, int chunkSize, byte[] seperator) throws Exception {
// Start with encode.
InputStream in = new ByteArrayInputStream(decoded);
in = new Base64InputStream(in, true, chunkSize, seperator);
byte[] output = new byte[encoded.length];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) in.read();
}
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 encode", Arrays.equals(output, encoded));
// Now let's try decode.
in = new ByteArrayInputStream(encoded);
in = new Base64InputStream(in);
output = new byte[decoded.length];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) in.read();
}
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 decode", Arrays.equals(output, decoded));
// I always wanted to do this! (wrap encoder with decoder etc etc).
in = new ByteArrayInputStream(decoded);
for (int i = 0; i < 10; i++) {
in = new Base64InputStream(in, true, chunkSize, seperator);
in = new Base64InputStream(in, false);
}
output = new byte[decoded.length];
for (int i = 0; i < output.length; i++) {
output[i] = (byte) in.read();
}
assertEquals("EOF", -1, in.read());
assertEquals("Still EOF", -1, in.read());
assertTrue("Streaming base64 wrap-wrap-wrap!", Arrays.equals(output, decoded));
}
/**
* Tests markSupported.
*
* @throws Exception
*/
public void testMarkSupported() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
// Always returns false for now.
assertFalse("Base64InputStream.markSupported() is false", in.markSupported());
}
/**
* Tests read returning 0
*
* @throws Exception
*/
public void testRead0() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
byte[] buf = new byte[1024];
int bytesRead = 0;
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
bytesRead = in.read(buf, 0, 0);
assertEquals("Base64InputStream.read(buf, 0, 0) returns 0", 0, bytesRead);
}
/**
* Tests read with null.
*
* @throws Exception
* for some failure scenarios.
*/
public void testReadNull() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
try {
in.read(null, 0, 0);
fail("Base64InputStream.read(null, 0, 0) to throw a NullPointerException");
} catch (NullPointerException e) {
// Expected
}
}
/**
* Tests read throwing IndexOutOfBoundsException
*
* @throws Exception
*/
public void testReadOutOfBounds() throws Exception {
byte[] decoded = StringUtils.getBytesUtf8(STRING_FIXTURE);
byte[] buf = new byte[1024];
ByteArrayInputStream bin = new ByteArrayInputStream(decoded);
Base64InputStream in = new Base64InputStream(bin, true, 4, new byte[]{0, 0, 0});
try {
in.read(buf, -1, 0);
fail("Expected Base64InputStream.read(buf, -1, 0) to throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
in.read(buf, 0, -1);
fail("Expected Base64InputStream.read(buf, 0, -1) to throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
in.read(buf, buf.length + 1, 0);
fail("Base64InputStream.read(buf, buf.length + 1, 0) throws IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
try {
in.read(buf, buf.length - 1, 2);
fail("Base64InputStream.read(buf, buf.length - 1, 2) throws IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected
}
}
} |
|
public void testDynamicRootName() throws IOException
{
String xml;
ObjectWriter w = _xmlMapper.writer().withRootName("rudy");
xml = w.writeValueAsString(new StringBean("foo"));
assertEquals("<rudy><text>foo</text></rudy>", xml);
xml = w.writeValueAsString(new StringBean(null));
assertEquals("<rudy><text/></rudy>", xml);
// and even with null will respect configured root name
xml = w.writeValueAsString(null);
assertEquals("<rudy/>", xml);
} | com.fasterxml.jackson.dataformat.xml.misc.RootNameTest::testDynamicRootName | src/test/java/com/fasterxml/jackson/dataformat/xml/misc/RootNameTest.java | 81 | src/test/java/com/fasterxml/jackson/dataformat/xml/misc/RootNameTest.java | testDynamicRootName | package com.fasterxml.jackson.dataformat.xml.misc;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.*;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
public class RootNameTest extends XmlTestBase
{
static class RootBeanBase
{
public String value;
protected RootBeanBase() { this("123"); }
public RootBeanBase(String v) {
value = v;
}
}
@JacksonXmlRootElement(localName="root")
static class RootBean extends RootBeanBase
{
protected RootBean() { super(); }
}
@JacksonXmlRootElement(localName="nsRoot", namespace="http://foo")
static class NsRootBean
{
public String value = "abc";
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
protected XmlMapper _xmlMapper = new XmlMapper();
// Unit test to verify that root name is properly set
public void testRootNameAnnotation() throws IOException
{
String xml = _xmlMapper.writeValueAsString(new StringBean());
// Hmmh. Looks like JDK Stax may adds bogus ns declaration. As such,
// let's just check that name starts ok...
if (!xml.startsWith("<StringBean")) {
fail("Expected root name of 'StringBean'; but XML document is ["+xml+"]");
}
// and then see that basic non-namespace root is ok
xml = _xmlMapper.writeValueAsString(new RootBean());
assertEquals("<root><value>123</value></root>", xml);
// and namespace one too
xml = _xmlMapper.writeValueAsString(new NsRootBean());
if (xml.indexOf("nsRoot") < 0) { // verify localName
fail("Expected root name of 'nsRoot'; but XML document is ["+xml+"]");
}
// and NS declaration
if (xml.indexOf("http://foo") < 0) {
fail("Expected NS declaration for 'http://foo', not found, XML document is ["+xml+"]");
}
}
public void testDynamicRootName() throws IOException
{
String xml;
ObjectWriter w = _xmlMapper.writer().withRootName("rudy");
xml = w.writeValueAsString(new StringBean("foo"));
assertEquals("<rudy><text>foo</text></rudy>", xml);
xml = w.writeValueAsString(new StringBean(null));
assertEquals("<rudy><text/></rudy>", xml);
// and even with null will respect configured root name
xml = w.writeValueAsString(null);
assertEquals("<rudy/>", xml);
}
} | // You are a professional Java test case writer, please create a test case named `testDynamicRootName` for the issue `JacksonXml-213`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonXml-213
//
// ## Issue-Title:
// XmlSerializerProvider does not use withRootName config for null
//
// ## Issue-Description:
// In `jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java`
//
//
// Line 203, I think `_rootNameFromConfig()` should be used if available instead of `ROOT_NAME_FOR_NULL`, so that `withRootName()` config can be used.
//
//
// I don't know whether/how deser would be affected
//
//
//
//
//
// [jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java](https://github.com/FasterXML/jackson-dataformat-xml/blob/ca1c671c419e88a18357d497ec3671c73c37452e/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java#L203)
//
//
//
//
// Line 203
// in
// [ca1c671](/FasterXML/jackson-dataformat-xml/commit/ca1c671c419e88a18357d497ec3671c73c37452e)
//
//
//
//
//
//
//
// | | |
// | --- | --- |
// | | \_initWithRootName((ToXmlGenerator) jgen, ROOT\_NAME\_FOR\_NULL); |
//
//
//
//
//
//
//
public void testDynamicRootName() throws IOException {
| 81 | 4 | 66 | src/test/java/com/fasterxml/jackson/dataformat/xml/misc/RootNameTest.java | src/test/java | ```markdown
## Issue-ID: JacksonXml-213
## Issue-Title:
XmlSerializerProvider does not use withRootName config for null
## Issue-Description:
In `jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java`
Line 203, I think `_rootNameFromConfig()` should be used if available instead of `ROOT_NAME_FOR_NULL`, so that `withRootName()` config can be used.
I don't know whether/how deser would be affected
[jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java](https://github.com/FasterXML/jackson-dataformat-xml/blob/ca1c671c419e88a18357d497ec3671c73c37452e/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java#L203)
Line 203
in
[ca1c671](/FasterXML/jackson-dataformat-xml/commit/ca1c671c419e88a18357d497ec3671c73c37452e)
| | |
| --- | --- |
| | \_initWithRootName((ToXmlGenerator) jgen, ROOT\_NAME\_FOR\_NULL); |
```
You are a professional Java test case writer, please create a test case named `testDynamicRootName` for the issue `JacksonXml-213`, utilizing the provided issue report information and the following function signature.
```java
public void testDynamicRootName() throws IOException {
```
| 66 | [
"com.fasterxml.jackson.dataformat.xml.ser.XmlSerializerProvider"
] | 4febfd4d47bcefe2a559107336bfc284597aae6947a60db23b090d8ae917dbee | public void testDynamicRootName() throws IOException
| // You are a professional Java test case writer, please create a test case named `testDynamicRootName` for the issue `JacksonXml-213`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonXml-213
//
// ## Issue-Title:
// XmlSerializerProvider does not use withRootName config for null
//
// ## Issue-Description:
// In `jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java`
//
//
// Line 203, I think `_rootNameFromConfig()` should be used if available instead of `ROOT_NAME_FOR_NULL`, so that `withRootName()` config can be used.
//
//
// I don't know whether/how deser would be affected
//
//
//
//
//
// [jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java](https://github.com/FasterXML/jackson-dataformat-xml/blob/ca1c671c419e88a18357d497ec3671c73c37452e/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java#L203)
//
//
//
//
// Line 203
// in
// [ca1c671](/FasterXML/jackson-dataformat-xml/commit/ca1c671c419e88a18357d497ec3671c73c37452e)
//
//
//
//
//
//
//
// | | |
// | --- | --- |
// | | \_initWithRootName((ToXmlGenerator) jgen, ROOT\_NAME\_FOR\_NULL); |
//
//
//
//
//
//
//
| JacksonXml | package com.fasterxml.jackson.dataformat.xml.misc;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.*;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
public class RootNameTest extends XmlTestBase
{
static class RootBeanBase
{
public String value;
protected RootBeanBase() { this("123"); }
public RootBeanBase(String v) {
value = v;
}
}
@JacksonXmlRootElement(localName="root")
static class RootBean extends RootBeanBase
{
protected RootBean() { super(); }
}
@JacksonXmlRootElement(localName="nsRoot", namespace="http://foo")
static class NsRootBean
{
public String value = "abc";
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
protected XmlMapper _xmlMapper = new XmlMapper();
// Unit test to verify that root name is properly set
public void testRootNameAnnotation() throws IOException
{
String xml = _xmlMapper.writeValueAsString(new StringBean());
// Hmmh. Looks like JDK Stax may adds bogus ns declaration. As such,
// let's just check that name starts ok...
if (!xml.startsWith("<StringBean")) {
fail("Expected root name of 'StringBean'; but XML document is ["+xml+"]");
}
// and then see that basic non-namespace root is ok
xml = _xmlMapper.writeValueAsString(new RootBean());
assertEquals("<root><value>123</value></root>", xml);
// and namespace one too
xml = _xmlMapper.writeValueAsString(new NsRootBean());
if (xml.indexOf("nsRoot") < 0) { // verify localName
fail("Expected root name of 'nsRoot'; but XML document is ["+xml+"]");
}
// and NS declaration
if (xml.indexOf("http://foo") < 0) {
fail("Expected NS declaration for 'http://foo', not found, XML document is ["+xml+"]");
}
}
public void testDynamicRootName() throws IOException
{
String xml;
ObjectWriter w = _xmlMapper.writer().withRootName("rudy");
xml = w.writeValueAsString(new StringBean("foo"));
assertEquals("<rudy><text>foo</text></rudy>", xml);
xml = w.writeValueAsString(new StringBean(null));
assertEquals("<rudy><text/></rudy>", xml);
// and even with null will respect configured root name
xml = w.writeValueAsString(null);
assertEquals("<rudy/>", xml);
}
} |
||
public void testNonFiniteDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.NaN);
jsonWriter.value(Double.NEGATIVE_INFINITY);
jsonWriter.value(Double.POSITIVE_INFINITY);
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
} | com.google.gson.stream.JsonWriterTest::testNonFiniteDoublesWhenLenient | gson/src/test/java/com/google/gson/stream/JsonWriterTest.java | 226 | gson/src/test/java/com/google/gson/stream/JsonWriterTest.java | testNonFiniteDoublesWhenLenient | /*
* Copyright (C) 2010 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.stream;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
@SuppressWarnings("resource")
public final class JsonWriterTest extends TestCase {
public void testTopLevelValueTypes() throws IOException {
StringWriter string1 = new StringWriter();
JsonWriter writer1 = new JsonWriter(string1);
writer1.value(true);
writer1.close();
assertEquals("true", string1.toString());
StringWriter string2 = new StringWriter();
JsonWriter writer2 = new JsonWriter(string2);
writer2.nullValue();
writer2.close();
assertEquals("null", string2.toString());
StringWriter string3 = new StringWriter();
JsonWriter writer3 = new JsonWriter(string3);
writer3.value(123);
writer3.close();
assertEquals("123", string3.toString());
StringWriter string4 = new StringWriter();
JsonWriter writer4 = new JsonWriter(string4);
writer4.value(123.4);
writer4.close();
assertEquals("123.4", string4.toString());
StringWriter string5 = new StringWriter();
JsonWriter writert = new JsonWriter(string5);
writert.value("a");
writert.close();
assertEquals("\"a\"", string5.toString());
}
public void testInvalidTopLevelTypes() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.name("hello");
try {
jsonWriter.value("world");
fail();
} catch (IllegalStateException expected) {
}
}
public void testTwoNames() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
try {
jsonWriter.name("a");
fail();
} catch (IllegalStateException expected) {
}
}
public void testNameWithoutValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
try {
jsonWriter.endObject();
fail();
} catch (IllegalStateException expected) {
}
}
public void testValueWithoutName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
try {
jsonWriter.value(true);
fail();
} catch (IllegalStateException expected) {
}
}
public void testMultipleTopLevelValues() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray().endArray();
try {
jsonWriter.beginArray();
fail();
} catch (IllegalStateException expected) {
}
}
public void testBadNestingObject() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.beginObject();
try {
jsonWriter.endArray();
fail();
} catch (IllegalStateException expected) {
}
}
public void testBadNestingArray() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.beginArray();
try {
jsonWriter.endObject();
fail();
} catch (IllegalStateException expected) {
}
}
public void testNullName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
try {
jsonWriter.name(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testNullStringValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
jsonWriter.value((String) null);
jsonWriter.endObject();
assertEquals("{\"a\":null}", stringWriter.toString());
}
public void testJsonValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
jsonWriter.jsonValue("{\"b\":true}");
jsonWriter.name("c");
jsonWriter.value(1);
jsonWriter.endObject();
assertEquals("{\"a\":{\"b\":true},\"c\":1}", stringWriter.toString());
}
public void testNonFiniteDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
try {
jsonWriter.value(Double.NaN);
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(Double.NEGATIVE_INFINITY);
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(Double.POSITIVE_INFINITY);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testNonFiniteBoxedDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
try {
jsonWriter.value(new Double(Double.NaN));
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(new Double(Double.NEGATIVE_INFINITY));
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(new Double(Double.POSITIVE_INFINITY));
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testNonFiniteDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.NaN);
jsonWriter.value(Double.NEGATIVE_INFINITY);
jsonWriter.value(Double.POSITIVE_INFINITY);
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
}
public void testNonFiniteBoxedDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.valueOf(Double.NaN));
jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY));
jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
}
public void testDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(-0.0);
jsonWriter.value(1.0);
jsonWriter.value(Double.MAX_VALUE);
jsonWriter.value(Double.MIN_VALUE);
jsonWriter.value(0.0);
jsonWriter.value(-0.5);
jsonWriter.value(2.2250738585072014E-308);
jsonWriter.value(Math.PI);
jsonWriter.value(Math.E);
jsonWriter.endArray();
jsonWriter.close();
assertEquals("[-0.0,"
+ "1.0,"
+ "1.7976931348623157E308,"
+ "4.9E-324,"
+ "0.0,"
+ "-0.5,"
+ "2.2250738585072014E-308,"
+ "3.141592653589793,"
+ "2.718281828459045]", stringWriter.toString());
}
public void testLongs() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(0);
jsonWriter.value(1);
jsonWriter.value(-1);
jsonWriter.value(Long.MIN_VALUE);
jsonWriter.value(Long.MAX_VALUE);
jsonWriter.endArray();
jsonWriter.close();
assertEquals("[0,"
+ "1,"
+ "-1,"
+ "-9223372036854775808,"
+ "9223372036854775807]", stringWriter.toString());
}
public void testNumbers() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(new BigInteger("0"));
jsonWriter.value(new BigInteger("9223372036854775808"));
jsonWriter.value(new BigInteger("-9223372036854775809"));
jsonWriter.value(new BigDecimal("3.141592653589793238462643383"));
jsonWriter.endArray();
jsonWriter.close();
assertEquals("[0,"
+ "9223372036854775808,"
+ "-9223372036854775809,"
+ "3.141592653589793238462643383]", stringWriter.toString());
}
public void testBooleans() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(true);
jsonWriter.value(false);
jsonWriter.endArray();
assertEquals("[true,false]", stringWriter.toString());
}
public void testBoxedBooleans() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value((Boolean) true);
jsonWriter.value((Boolean) false);
jsonWriter.value((Boolean) null);
jsonWriter.endArray();
assertEquals("[true,false,null]", stringWriter.toString());
}
public void testNulls() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.nullValue();
jsonWriter.endArray();
assertEquals("[null]", stringWriter.toString());
}
public void testStrings() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value("a");
jsonWriter.value("a\"");
jsonWriter.value("\"");
jsonWriter.value(":");
jsonWriter.value(",");
jsonWriter.value("\b");
jsonWriter.value("\f");
jsonWriter.value("\n");
jsonWriter.value("\r");
jsonWriter.value("\t");
jsonWriter.value(" ");
jsonWriter.value("\\");
jsonWriter.value("{");
jsonWriter.value("}");
jsonWriter.value("[");
jsonWriter.value("]");
jsonWriter.value("\0");
jsonWriter.value("\u0019");
jsonWriter.endArray();
assertEquals("[\"a\","
+ "\"a\\\"\","
+ "\"\\\"\","
+ "\":\","
+ "\",\","
+ "\"\\b\","
+ "\"\\f\","
+ "\"\\n\","
+ "\"\\r\","
+ "\"\\t\","
+ "\" \","
+ "\"\\\\\","
+ "\"{\","
+ "\"}\","
+ "\"[\","
+ "\"]\","
+ "\"\\u0000\","
+ "\"\\u0019\"]", stringWriter.toString());
}
public void testUnicodeLineBreaksEscaped() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value("\u2028 \u2029");
jsonWriter.endArray();
assertEquals("[\"\\u2028 \\u2029\"]", stringWriter.toString());
}
public void testEmptyArray() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.endArray();
assertEquals("[]", stringWriter.toString());
}
public void testEmptyObject() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.endObject();
assertEquals("{}", stringWriter.toString());
}
public void testObjectsInArrays() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.beginObject();
jsonWriter.name("a").value(5);
jsonWriter.name("b").value(false);
jsonWriter.endObject();
jsonWriter.beginObject();
jsonWriter.name("c").value(6);
jsonWriter.name("d").value(true);
jsonWriter.endObject();
jsonWriter.endArray();
assertEquals("[{\"a\":5,\"b\":false},"
+ "{\"c\":6,\"d\":true}]", stringWriter.toString());
}
public void testArraysInObjects() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
jsonWriter.beginArray();
jsonWriter.value(5);
jsonWriter.value(false);
jsonWriter.endArray();
jsonWriter.name("b");
jsonWriter.beginArray();
jsonWriter.value(6);
jsonWriter.value(true);
jsonWriter.endArray();
jsonWriter.endObject();
assertEquals("{\"a\":[5,false],"
+ "\"b\":[6,true]}", stringWriter.toString());
}
public void testDeepNestingArrays() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
for (int i = 0; i < 20; i++) {
jsonWriter.beginArray();
}
for (int i = 0; i < 20; i++) {
jsonWriter.endArray();
}
assertEquals("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]", stringWriter.toString());
}
public void testDeepNestingObjects() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
for (int i = 0; i < 20; i++) {
jsonWriter.name("a");
jsonWriter.beginObject();
}
for (int i = 0; i < 20; i++) {
jsonWriter.endObject();
}
jsonWriter.endObject();
assertEquals("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":"
+ "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{"
+ "}}}}}}}}}}}}}}}}}}}}}", stringWriter.toString());
}
public void testRepeatedName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a").value(true);
jsonWriter.name("a").value(false);
jsonWriter.endObject();
// JsonWriter doesn't attempt to detect duplicate names
assertEquals("{\"a\":true,\"a\":false}", stringWriter.toString());
}
public void testPrettyPrintObject() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setIndent(" ");
jsonWriter.beginObject();
jsonWriter.name("a").value(true);
jsonWriter.name("b").value(false);
jsonWriter.name("c").value(5.0);
jsonWriter.name("e").nullValue();
jsonWriter.name("f").beginArray();
jsonWriter.value(6.0);
jsonWriter.value(7.0);
jsonWriter.endArray();
jsonWriter.name("g").beginObject();
jsonWriter.name("h").value(8.0);
jsonWriter.name("i").value(9.0);
jsonWriter.endObject();
jsonWriter.endObject();
String expected = "{\n"
+ " \"a\": true,\n"
+ " \"b\": false,\n"
+ " \"c\": 5.0,\n"
+ " \"e\": null,\n"
+ " \"f\": [\n"
+ " 6.0,\n"
+ " 7.0\n"
+ " ],\n"
+ " \"g\": {\n"
+ " \"h\": 8.0,\n"
+ " \"i\": 9.0\n"
+ " }\n"
+ "}";
assertEquals(expected, stringWriter.toString());
}
public void testPrettyPrintArray() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setIndent(" ");
jsonWriter.beginArray();
jsonWriter.value(true);
jsonWriter.value(false);
jsonWriter.value(5.0);
jsonWriter.nullValue();
jsonWriter.beginObject();
jsonWriter.name("a").value(6.0);
jsonWriter.name("b").value(7.0);
jsonWriter.endObject();
jsonWriter.beginArray();
jsonWriter.value(8.0);
jsonWriter.value(9.0);
jsonWriter.endArray();
jsonWriter.endArray();
String expected = "[\n"
+ " true,\n"
+ " false,\n"
+ " 5.0,\n"
+ " null,\n"
+ " {\n"
+ " \"a\": 6.0,\n"
+ " \"b\": 7.0\n"
+ " },\n"
+ " [\n"
+ " 8.0,\n"
+ " 9.0\n"
+ " ]\n"
+ "]";
assertEquals(expected, stringWriter.toString());
}
public void testLenientWriterPermitsMultipleTopLevelValues() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.setLenient(true);
writer.beginArray();
writer.endArray();
writer.beginArray();
writer.endArray();
writer.close();
assertEquals("[][]", stringWriter.toString());
}
public void testStrictWriterDoesNotPermitMultipleTopLevelValues() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
try {
writer.beginArray();
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnStructure() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.beginArray();
fail();
} catch (IllegalStateException expected) {
}
try {
writer.endArray();
fail();
} catch (IllegalStateException expected) {
}
try {
writer.beginObject();
fail();
} catch (IllegalStateException expected) {
}
try {
writer.endObject();
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.name("a");
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.value("a");
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnFlush() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.flush();
fail();
} catch (IllegalStateException expected) {
}
}
public void testWriterCloseIsIdempotent() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
writer.close();
}
} | // You are a professional Java test case writer, please create a test case named `testNonFiniteDoublesWhenLenient` for the issue `Gson-1090`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Gson-1090
//
// ## Issue-Title:
// JsonWriter#value(java.lang.Number) can be lenient, but JsonWriter#value(double) can't,
//
// ## Issue-Description:
// In lenient mode, JsonWriter#value(java.lang.Number) can write pseudo-numeric values like `NaN`, `Infinity`, `-Infinity`:
//
//
//
// ```
// if (!lenient
// && (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
// throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
// }
// ```
//
// But JsonWriter#value(double) behaves in different way:
//
//
//
// ```
// if (Double.isNaN(value) || Double.isInfinite(value)) {
// throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
// }
// ```
//
// So, while working with streaming, it's impossible to write semi-numeric value without boxing a double (e. g. `out.value((Number) Double.valueOf(Double.NaN))`).
//
//
// I think, this should be possible, because boxing gives worse performance.
//
//
//
//
public void testNonFiniteDoublesWhenLenient() throws IOException {
| 226 | 15 | 216 | gson/src/test/java/com/google/gson/stream/JsonWriterTest.java | gson/src/test/java | ```markdown
## Issue-ID: Gson-1090
## Issue-Title:
JsonWriter#value(java.lang.Number) can be lenient, but JsonWriter#value(double) can't,
## Issue-Description:
In lenient mode, JsonWriter#value(java.lang.Number) can write pseudo-numeric values like `NaN`, `Infinity`, `-Infinity`:
```
if (!lenient
&& (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
```
But JsonWriter#value(double) behaves in different way:
```
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
```
So, while working with streaming, it's impossible to write semi-numeric value without boxing a double (e. g. `out.value((Number) Double.valueOf(Double.NaN))`).
I think, this should be possible, because boxing gives worse performance.
```
You are a professional Java test case writer, please create a test case named `testNonFiniteDoublesWhenLenient` for the issue `Gson-1090`, utilizing the provided issue report information and the following function signature.
```java
public void testNonFiniteDoublesWhenLenient() throws IOException {
```
| 216 | [
"com.google.gson.stream.JsonWriter"
] | 502698a024c46984b80927b2bb310bff5f35a7cd0328dec3cc606ccb42db1b60 | public void testNonFiniteDoublesWhenLenient() throws IOException | // You are a professional Java test case writer, please create a test case named `testNonFiniteDoublesWhenLenient` for the issue `Gson-1090`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Gson-1090
//
// ## Issue-Title:
// JsonWriter#value(java.lang.Number) can be lenient, but JsonWriter#value(double) can't,
//
// ## Issue-Description:
// In lenient mode, JsonWriter#value(java.lang.Number) can write pseudo-numeric values like `NaN`, `Infinity`, `-Infinity`:
//
//
//
// ```
// if (!lenient
// && (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
// throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
// }
// ```
//
// But JsonWriter#value(double) behaves in different way:
//
//
//
// ```
// if (Double.isNaN(value) || Double.isInfinite(value)) {
// throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
// }
// ```
//
// So, while working with streaming, it's impossible to write semi-numeric value without boxing a double (e. g. `out.value((Number) Double.valueOf(Double.NaN))`).
//
//
// I think, this should be possible, because boxing gives worse performance.
//
//
//
//
| Gson | /*
* Copyright (C) 2010 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.stream;
import junit.framework.TestCase;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
@SuppressWarnings("resource")
public final class JsonWriterTest extends TestCase {
public void testTopLevelValueTypes() throws IOException {
StringWriter string1 = new StringWriter();
JsonWriter writer1 = new JsonWriter(string1);
writer1.value(true);
writer1.close();
assertEquals("true", string1.toString());
StringWriter string2 = new StringWriter();
JsonWriter writer2 = new JsonWriter(string2);
writer2.nullValue();
writer2.close();
assertEquals("null", string2.toString());
StringWriter string3 = new StringWriter();
JsonWriter writer3 = new JsonWriter(string3);
writer3.value(123);
writer3.close();
assertEquals("123", string3.toString());
StringWriter string4 = new StringWriter();
JsonWriter writer4 = new JsonWriter(string4);
writer4.value(123.4);
writer4.close();
assertEquals("123.4", string4.toString());
StringWriter string5 = new StringWriter();
JsonWriter writert = new JsonWriter(string5);
writert.value("a");
writert.close();
assertEquals("\"a\"", string5.toString());
}
public void testInvalidTopLevelTypes() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.name("hello");
try {
jsonWriter.value("world");
fail();
} catch (IllegalStateException expected) {
}
}
public void testTwoNames() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
try {
jsonWriter.name("a");
fail();
} catch (IllegalStateException expected) {
}
}
public void testNameWithoutValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
try {
jsonWriter.endObject();
fail();
} catch (IllegalStateException expected) {
}
}
public void testValueWithoutName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
try {
jsonWriter.value(true);
fail();
} catch (IllegalStateException expected) {
}
}
public void testMultipleTopLevelValues() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray().endArray();
try {
jsonWriter.beginArray();
fail();
} catch (IllegalStateException expected) {
}
}
public void testBadNestingObject() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.beginObject();
try {
jsonWriter.endArray();
fail();
} catch (IllegalStateException expected) {
}
}
public void testBadNestingArray() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.beginArray();
try {
jsonWriter.endObject();
fail();
} catch (IllegalStateException expected) {
}
}
public void testNullName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
try {
jsonWriter.name(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testNullStringValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
jsonWriter.value((String) null);
jsonWriter.endObject();
assertEquals("{\"a\":null}", stringWriter.toString());
}
public void testJsonValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
jsonWriter.jsonValue("{\"b\":true}");
jsonWriter.name("c");
jsonWriter.value(1);
jsonWriter.endObject();
assertEquals("{\"a\":{\"b\":true},\"c\":1}", stringWriter.toString());
}
public void testNonFiniteDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
try {
jsonWriter.value(Double.NaN);
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(Double.NEGATIVE_INFINITY);
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(Double.POSITIVE_INFINITY);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testNonFiniteBoxedDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
try {
jsonWriter.value(new Double(Double.NaN));
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(new Double(Double.NEGATIVE_INFINITY));
fail();
} catch (IllegalArgumentException expected) {
}
try {
jsonWriter.value(new Double(Double.POSITIVE_INFINITY));
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testNonFiniteDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.NaN);
jsonWriter.value(Double.NEGATIVE_INFINITY);
jsonWriter.value(Double.POSITIVE_INFINITY);
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
}
public void testNonFiniteBoxedDoublesWhenLenient() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setLenient(true);
jsonWriter.beginArray();
jsonWriter.value(Double.valueOf(Double.NaN));
jsonWriter.value(Double.valueOf(Double.NEGATIVE_INFINITY));
jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY));
jsonWriter.endArray();
assertEquals("[NaN,-Infinity,Infinity]", stringWriter.toString());
}
public void testDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(-0.0);
jsonWriter.value(1.0);
jsonWriter.value(Double.MAX_VALUE);
jsonWriter.value(Double.MIN_VALUE);
jsonWriter.value(0.0);
jsonWriter.value(-0.5);
jsonWriter.value(2.2250738585072014E-308);
jsonWriter.value(Math.PI);
jsonWriter.value(Math.E);
jsonWriter.endArray();
jsonWriter.close();
assertEquals("[-0.0,"
+ "1.0,"
+ "1.7976931348623157E308,"
+ "4.9E-324,"
+ "0.0,"
+ "-0.5,"
+ "2.2250738585072014E-308,"
+ "3.141592653589793,"
+ "2.718281828459045]", stringWriter.toString());
}
public void testLongs() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(0);
jsonWriter.value(1);
jsonWriter.value(-1);
jsonWriter.value(Long.MIN_VALUE);
jsonWriter.value(Long.MAX_VALUE);
jsonWriter.endArray();
jsonWriter.close();
assertEquals("[0,"
+ "1,"
+ "-1,"
+ "-9223372036854775808,"
+ "9223372036854775807]", stringWriter.toString());
}
public void testNumbers() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(new BigInteger("0"));
jsonWriter.value(new BigInteger("9223372036854775808"));
jsonWriter.value(new BigInteger("-9223372036854775809"));
jsonWriter.value(new BigDecimal("3.141592653589793238462643383"));
jsonWriter.endArray();
jsonWriter.close();
assertEquals("[0,"
+ "9223372036854775808,"
+ "-9223372036854775809,"
+ "3.141592653589793238462643383]", stringWriter.toString());
}
public void testBooleans() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value(true);
jsonWriter.value(false);
jsonWriter.endArray();
assertEquals("[true,false]", stringWriter.toString());
}
public void testBoxedBooleans() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value((Boolean) true);
jsonWriter.value((Boolean) false);
jsonWriter.value((Boolean) null);
jsonWriter.endArray();
assertEquals("[true,false,null]", stringWriter.toString());
}
public void testNulls() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.nullValue();
jsonWriter.endArray();
assertEquals("[null]", stringWriter.toString());
}
public void testStrings() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value("a");
jsonWriter.value("a\"");
jsonWriter.value("\"");
jsonWriter.value(":");
jsonWriter.value(",");
jsonWriter.value("\b");
jsonWriter.value("\f");
jsonWriter.value("\n");
jsonWriter.value("\r");
jsonWriter.value("\t");
jsonWriter.value(" ");
jsonWriter.value("\\");
jsonWriter.value("{");
jsonWriter.value("}");
jsonWriter.value("[");
jsonWriter.value("]");
jsonWriter.value("\0");
jsonWriter.value("\u0019");
jsonWriter.endArray();
assertEquals("[\"a\","
+ "\"a\\\"\","
+ "\"\\\"\","
+ "\":\","
+ "\",\","
+ "\"\\b\","
+ "\"\\f\","
+ "\"\\n\","
+ "\"\\r\","
+ "\"\\t\","
+ "\" \","
+ "\"\\\\\","
+ "\"{\","
+ "\"}\","
+ "\"[\","
+ "\"]\","
+ "\"\\u0000\","
+ "\"\\u0019\"]", stringWriter.toString());
}
public void testUnicodeLineBreaksEscaped() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.value("\u2028 \u2029");
jsonWriter.endArray();
assertEquals("[\"\\u2028 \\u2029\"]", stringWriter.toString());
}
public void testEmptyArray() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.endArray();
assertEquals("[]", stringWriter.toString());
}
public void testEmptyObject() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.endObject();
assertEquals("{}", stringWriter.toString());
}
public void testObjectsInArrays() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginArray();
jsonWriter.beginObject();
jsonWriter.name("a").value(5);
jsonWriter.name("b").value(false);
jsonWriter.endObject();
jsonWriter.beginObject();
jsonWriter.name("c").value(6);
jsonWriter.name("d").value(true);
jsonWriter.endObject();
jsonWriter.endArray();
assertEquals("[{\"a\":5,\"b\":false},"
+ "{\"c\":6,\"d\":true}]", stringWriter.toString());
}
public void testArraysInObjects() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
jsonWriter.beginArray();
jsonWriter.value(5);
jsonWriter.value(false);
jsonWriter.endArray();
jsonWriter.name("b");
jsonWriter.beginArray();
jsonWriter.value(6);
jsonWriter.value(true);
jsonWriter.endArray();
jsonWriter.endObject();
assertEquals("{\"a\":[5,false],"
+ "\"b\":[6,true]}", stringWriter.toString());
}
public void testDeepNestingArrays() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
for (int i = 0; i < 20; i++) {
jsonWriter.beginArray();
}
for (int i = 0; i < 20; i++) {
jsonWriter.endArray();
}
assertEquals("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]", stringWriter.toString());
}
public void testDeepNestingObjects() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
for (int i = 0; i < 20; i++) {
jsonWriter.name("a");
jsonWriter.beginObject();
}
for (int i = 0; i < 20; i++) {
jsonWriter.endObject();
}
jsonWriter.endObject();
assertEquals("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":"
+ "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{"
+ "}}}}}}}}}}}}}}}}}}}}}", stringWriter.toString());
}
public void testRepeatedName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a").value(true);
jsonWriter.name("a").value(false);
jsonWriter.endObject();
// JsonWriter doesn't attempt to detect duplicate names
assertEquals("{\"a\":true,\"a\":false}", stringWriter.toString());
}
public void testPrettyPrintObject() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setIndent(" ");
jsonWriter.beginObject();
jsonWriter.name("a").value(true);
jsonWriter.name("b").value(false);
jsonWriter.name("c").value(5.0);
jsonWriter.name("e").nullValue();
jsonWriter.name("f").beginArray();
jsonWriter.value(6.0);
jsonWriter.value(7.0);
jsonWriter.endArray();
jsonWriter.name("g").beginObject();
jsonWriter.name("h").value(8.0);
jsonWriter.name("i").value(9.0);
jsonWriter.endObject();
jsonWriter.endObject();
String expected = "{\n"
+ " \"a\": true,\n"
+ " \"b\": false,\n"
+ " \"c\": 5.0,\n"
+ " \"e\": null,\n"
+ " \"f\": [\n"
+ " 6.0,\n"
+ " 7.0\n"
+ " ],\n"
+ " \"g\": {\n"
+ " \"h\": 8.0,\n"
+ " \"i\": 9.0\n"
+ " }\n"
+ "}";
assertEquals(expected, stringWriter.toString());
}
public void testPrettyPrintArray() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.setIndent(" ");
jsonWriter.beginArray();
jsonWriter.value(true);
jsonWriter.value(false);
jsonWriter.value(5.0);
jsonWriter.nullValue();
jsonWriter.beginObject();
jsonWriter.name("a").value(6.0);
jsonWriter.name("b").value(7.0);
jsonWriter.endObject();
jsonWriter.beginArray();
jsonWriter.value(8.0);
jsonWriter.value(9.0);
jsonWriter.endArray();
jsonWriter.endArray();
String expected = "[\n"
+ " true,\n"
+ " false,\n"
+ " 5.0,\n"
+ " null,\n"
+ " {\n"
+ " \"a\": 6.0,\n"
+ " \"b\": 7.0\n"
+ " },\n"
+ " [\n"
+ " 8.0,\n"
+ " 9.0\n"
+ " ]\n"
+ "]";
assertEquals(expected, stringWriter.toString());
}
public void testLenientWriterPermitsMultipleTopLevelValues() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.setLenient(true);
writer.beginArray();
writer.endArray();
writer.beginArray();
writer.endArray();
writer.close();
assertEquals("[][]", stringWriter.toString());
}
public void testStrictWriterDoesNotPermitMultipleTopLevelValues() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
try {
writer.beginArray();
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnStructure() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.beginArray();
fail();
} catch (IllegalStateException expected) {
}
try {
writer.endArray();
fail();
} catch (IllegalStateException expected) {
}
try {
writer.beginObject();
fail();
} catch (IllegalStateException expected) {
}
try {
writer.endObject();
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnName() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.name("a");
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnValue() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.value("a");
fail();
} catch (IllegalStateException expected) {
}
}
public void testClosedWriterThrowsOnFlush() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
try {
writer.flush();
fail();
} catch (IllegalStateException expected) {
}
}
public void testWriterCloseIsIdempotent() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
writer.beginArray();
writer.endArray();
writer.close();
writer.close();
}
} |
||
@Test
public void testHeaderMissingWithNull() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().withNullString("").withIgnoreEmptyHeaders(true).parse(in).iterator();
} | org.apache.commons.csv.CSVParserTest::testHeaderMissingWithNull | src/test/java/org/apache/commons/csv/CSVParserTest.java | 670 | src/test/java/org/apache/commons/csv/CSVParserTest.java | testHeaderMissingWithNull | /*
* 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.apache.commons.csv.Constants.CRLF;
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.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.apache.commons.io.input.BOMInputStream;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* CSVParserTest
*
* The test are organized in three different sections:
* The 'setter/getter' section, the lexer section and finally the parser
* section. In case a test fails, you should follow a top-down approach for
* fixing a potential bug (its likely that the parser itself fails if the lexer
* has problems...).
*
* @version $Id$
*/
public class CSVParserTest {
private static final String CSV_INPUT = "a,b,c,d\n"
+ " a , b , 1 2 \n"
+ "\"foo baar\", b,\n"
// + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n";
+ " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping
private static final String CSV_INPUT_1 = "a,b,c,d";
private static final String CSV_INPUT_2 = "a,b,1 2";
private static final String[][] RESULT = {
{"a", "b", "c", "d"},
{"a", "b", "1 2"},
{"foo baar", "b", ""},
{"foo\n,,\n\",,\n\"", "d", "e"}
};
@Test
public void testBackslashEscaping() throws IOException {
// To avoid confusion over the need for escaping chars in java code,
// We will test with a forward slash as the escape char, and a single
// quote as the encapsulator.
final String code =
"one,two,three\n" // 0
+ "'',''\n" // 1) empty encapsulators
+ "/',/'\n" // 2) single encapsulators
+ "'/'','/''\n" // 3) single encapsulators encapsulated via escape
+ "'''',''''\n" // 4) single encapsulators encapsulated via doubling
+ "/,,/,\n" // 5) separator escaped
+ "//,//\n" // 6) escape escaped
+ "'//','//'\n" // 7) escape escaped in encapsulation
+ " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces
+ "9, /\n \n" // escaped newline
+ "";
final String[][] res = {
{"one", "two", "three"}, // 0
{"", ""}, // 1
{"'", "'"}, // 2
{"'", "'"}, // 3
{"'", "'"}, // 4
{",", ","}, // 5
{"/", "/"}, // 6
{"/", "/"}, // 7
{" 8 ", " \"quoted \"\" /\" / string\" "},
{"9", " \n "},
};
final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'')
.withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true);
final CSVParser parser = CSVParser.parse(code, format);
final List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Records do not match expected result", res, records);
parser.close();
}
@Test
public void testBackslashEscaping2() throws IOException {
// To avoid confusion over the need for escaping chars in java code,
// We will test with a forward slash as the escape char, and a single
// quote as the encapsulator.
final String code = ""
+ " , , \n" // 1)
+ " \t , , \n" // 2)
+ " // , /, , /,\n" // 3)
+ "";
final String[][] res = {
{" ", " ", " "}, // 1
{" \t ", " ", " "}, // 2
{" / ", " , ", " ,"}, // 3
};
final CSVFormat format = CSVFormat.newFormat(',')
.withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true);
final CSVParser parser = CSVParser.parse(code, format);
final List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("", res, records);
parser.close();
}
@Test
@Ignore
public void testBackslashEscapingOld() throws IOException {
final String code =
"one,two,three\n"
+ "on\\\"e,two\n"
+ "on\"e,two\n"
+ "one,\"tw\\\"o\"\n"
+ "one,\"t\\,wo\"\n"
+ "one,two,\"th,ree\"\n"
+ "\"a\\\\\"\n"
+ "a\\,b\n"
+ "\"a\\\\,b\"";
final String[][] res = {
{"one", "two", "three"},
{"on\\\"e", "two"},
{"on\"e", "two"},
{"one", "tw\"o"},
{"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",")
{"one", "two", "th,ree"},
{"a\\\\"}, // backslash in quotes only escapes a delimiter (",")
{"a\\", "b"}, // a backslash must be returnd
{"a\\\\,b"} // backslash in quotes only escapes a delimiter (",")
};
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
@Test
@Ignore("CSV-107")
public void testBOM() throws IOException {
final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv");
final CSVParser parser = CSVParser.parse(url, Charset.forName("UTF-8"), CSVFormat.EXCEL.withHeader());
try {
for (final CSVRecord record : parser) {
final String string = record.get("Date");
Assert.assertNotNull(string);
//System.out.println("date: " + record.get("Date"));
}
} finally {
parser.close();
}
}
@Test
public void testBOMInputStream() {}
// Defects4J: flaky method
// @Test
// public void testBOMInputStream() throws IOException {
// final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv");
// final Reader reader = new InputStreamReader(new BOMInputStream(url.openStream()), "UTF-8");
// final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
// try {
// for (final CSVRecord record : parser) {
// final String string = record.get("Date");
// Assert.assertNotNull(string);
// //System.out.println("date: " + record.get("Date"));
// }
// } finally {
// parser.close();
// reader.close();
// }
// }
@Test
public void testCarriageReturnEndings() throws IOException {
final String code = "foo\rbaar,\rhello,world\r,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
@Test
public void testCarriageReturnLineFeedEndings() throws IOException {
final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
@Test(expected = NoSuchElementException.class)
public void testClose() throws Exception {
final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z");
final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in);
final Iterator<CSVRecord> records = parser.iterator();
assertTrue(records.hasNext());
parser.close();
assertFalse(records.hasNext());
records.next();
}
@Test
public void testCSV57() throws Exception {
final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT);
final List<CSVRecord> list = parser.getRecords();
assertNotNull(list);
assertEquals(0, list.size());
parser.close();
}
@Test
public void testDefaultFormat() throws IOException {
final String code = ""
+ "a,b#\n" // 1)
+ "\"\n\",\" \",#\n" // 2)
+ "#,\"\"\n" // 3)
+ "# Final comment\n"// 4)
;
final String[][] res = {
{"a", "b#"},
{"\n", " ", "#"},
{"#", ""},
{"# Final comment"}
};
CSVFormat format = CSVFormat.DEFAULT;
assertFalse(format.isCommentingEnabled());
CSVParser parser = CSVParser.parse(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Failed to parse without comments", res, records);
final String[][] res_comments = {
{"a", "b#"},
{"\n", " ", "#"},
};
format = CSVFormat.DEFAULT.withCommentStart('#');
parser.close();
parser = CSVParser.parse(code, format);
records = parser.getRecords();
Utils.compare("Failed to parse with comments", res_comments, records);
parser.close();
}
@Test
public void testEmptyFile() throws Exception {
final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT);
assertNull(parser.nextRecord());
parser.close();
}
@Test
public void testEmptyLineBehaviourCSV() throws Exception {
final String[] codes = {
"hello,\r\n\r\n\r\n",
"hello,\n\n\n",
"hello,\"\"\r\n\r\n\r\n",
"hello,\"\"\n\n\n"
};
final String[][] res = {
{"hello", ""} // CSV format ignores empty lines
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testEmptyLineBehaviourExcel() throws Exception {
final String[] codes = {
"hello,\r\n\r\n\r\n",
"hello,\n\n\n",
"hello,\"\"\r\n\r\n\r\n",
"hello,\"\"\n\n\n"
};
final String[][] res = {
{"hello", ""},
{""}, // Excel format does not ignore empty lines
{""}
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testEndOfFileBehaviorCSV() throws Exception {
final String[] codes = {
"hello,\r\n\r\nworld,\r\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\r\n",
"hello,\r\n\r\nworld,\"\"",
"hello,\r\n\r\nworld,\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\n",
"hello,\r\n\r\nworld,\"\""
};
final String[][] res = {
{"hello", ""}, // CSV format ignores empty lines
{"world", ""}
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testEndOfFileBehaviourExcel() throws Exception {
final String[] codes = {
"hello,\r\n\r\nworld,\r\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\r\n",
"hello,\r\n\r\nworld,\"\"",
"hello,\r\n\r\nworld,\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\n",
"hello,\r\n\r\nworld,\"\""
};
final String[][] res = {
{"hello", ""},
{""}, // Excel format does not ignore empty lines
{"world", ""}
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testExcelFormat1() throws IOException {
final String code =
"value1,value2,value3,value4\r\na,b,c,d\r\n x,,,"
+ "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n";
final String[][] res = {
{"value1", "value2", "value3", "value4"},
{"a", "b", "c", "d"},
{" x", "", "", ""},
{""},
{"\"hello\"", " \"world\"", "abc\ndef", ""}
};
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
@Test
public void testExcelFormat2() throws Exception {
final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n";
final String[][] res = {
{"foo", "baar"},
{""},
{"hello", ""},
{""},
{"world", ""}
};
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
@Test
public void testForEach() throws Exception {
final List<CSVRecord> records = new ArrayList<CSVRecord>();
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) {
records.add(record);
}
assertEquals(3, records.size());
assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values());
assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values());
assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values());
}
@Test
public void testGetHeaderMap() throws Exception {
final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C"));
final Map<String, Integer> headerMap = parser.getHeaderMap();
final Iterator<String> columnNames = headerMap.keySet().iterator();
// Headers are iterated in column order.
Assert.assertEquals("A", columnNames.next());
Assert.assertEquals("B", columnNames.next());
Assert.assertEquals("C", columnNames.next());
final Iterator<CSVRecord> records = parser.iterator();
// Parse to make sure getHeaderMap did not have a side-effect.
for (int i = 0; i < 3; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("A"));
assertEquals(record.get(1), record.get("B"));
assertEquals(record.get(2), record.get("C"));
}
assertFalse(records.hasNext());
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testDuplicateHeaders() throws Exception {
CSVParser.parse("a,b,a\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader(new String[]{}));
}
@Test
public void testGetLine() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));
for (final String[] re : RESULT) {
assertArrayEquals(re, parser.nextRecord().values());
}
assertNull(parser.nextRecord());
parser.close();
}
@Test
public void testGetLineNumberWithCR() throws Exception {
this.validateLineNumbers(String.valueOf(CR));
}
@Test
public void testGetLineNumberWithCRLF() throws Exception {
this.validateLineNumbers(CRLF);
}
@Test
public void testGetLineNumberWithLF() throws Exception {
this.validateLineNumbers(String.valueOf(LF));
}
@Test
public void testGetOneLine() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT);
final CSVRecord record = parser.getRecords().get(0);
assertArrayEquals(RESULT[0], record.values());
parser.close();
}
@Test
public void testGetOneLineCustomCollection() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT);
final CSVRecord record = parser.getRecords(new LinkedList<CSVRecord>()).getFirst();
assertArrayEquals(RESULT[0], record.values());
parser.close();
}
/**
* Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110].
*
* @throws IOException
*/
@Test
public void testGetOneLineOneParser() throws IOException {
final PipedWriter writer = new PipedWriter();
final PipedReader reader = new PipedReader(writer);
final CSVFormat format = CSVFormat.DEFAULT;
final CSVParser parser = new CSVParser(reader, format);
try {
writer.append(CSV_INPUT_1);
writer.append(format.getRecordSeparator());
final CSVRecord record1 = parser.nextRecord();
assertArrayEquals(RESULT[0], record1.values());
writer.append(CSV_INPUT_2);
writer.append(format.getRecordSeparator());
final CSVRecord record2 = parser.nextRecord();
assertArrayEquals(RESULT[1], record2.values());
} finally {
parser.close();
}
}
@Test
public void testGetRecordNumberWithCR() throws Exception {
this.validateRecordNumbers(String.valueOf(CR));
}
@Test
public void testGetRecordNumberWithCRLF() throws Exception {
this.validateRecordNumbers(CRLF);
}
@Test
public void testGetRecordNumberWithLF() throws Exception {
this.validateRecordNumbers(String.valueOf(LF));
}
@Test
public void testGetRecords() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));
final List<CSVRecord> records = parser.getRecords();
assertEquals(RESULT.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < RESULT.length; i++) {
assertArrayEquals(RESULT[i], records.get(i).values());
}
parser.close();
}
@Test
public void testGetRecordWithMultiLineValues() throws Exception {
final CSVParser parser = CSVParser.parse("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"",
CSVFormat.DEFAULT.withRecordSeparator(CRLF));
CSVRecord record;
assertEquals(0, parser.getRecordNumber());
assertEquals(0, parser.getCurrentLineNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(3, parser.getCurrentLineNumber());
assertEquals(1, record.getRecordNumber());
assertEquals(1, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(6, parser.getCurrentLineNumber());
assertEquals(2, record.getRecordNumber());
assertEquals(2, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(8, parser.getCurrentLineNumber());
assertEquals(3, record.getRecordNumber());
assertEquals(3, parser.getRecordNumber());
assertNull(record = parser.nextRecord());
assertEquals(8, parser.getCurrentLineNumber());
assertEquals(3, parser.getRecordNumber());
parser.close();
}
@Test
public void testHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(1), record.get("b"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test
public void testHeaderMissing() throws Exception {
final Reader in = new StringReader("a,,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test(expected=IllegalArgumentException.class)
public void testHeadersMissingException() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().parse(in).iterator();
}
@Test
public void testHeadersMissing() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().withIgnoreEmptyHeaders(true).parse(in).iterator();
}
@Test
public void testHeaderMissingWithNull() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().withNullString("").withIgnoreEmptyHeaders(true).parse(in).iterator();
}
@Test
public void testHeaderComment() throws Exception {
final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(1), record.get("b"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test
public void testIgnoreEmptyLines() throws IOException {
final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n";
//String code = "world\r\n\n";
//String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(3, records.size());
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidFormat() throws Exception {
final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR);
new CSVParser(null, invalidFormat).close();
}
@Test
public void testIterator() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> iterator = CSVFormat.DEFAULT.parse(in).iterator();
assertTrue(iterator.hasNext());
try {
iterator.remove();
fail("expected UnsupportedOperationException");
} catch (final UnsupportedOperationException expected) {
// expected
}
assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values());
assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values());
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("NoSuchElementException expected");
} catch (final NoSuchElementException e) {
// expected
}
}
@Test
public void testLineFeedEndings() throws IOException {
final String code = "foo\nbaar,\nhello,world\n,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
@Test
public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true)
.parse(in).iterator();
CSVRecord record;
// 1st record
record = records.next();
assertTrue(record.isMapped("A"));
assertTrue(record.isMapped("B"));
assertTrue(record.isMapped("C"));
assertTrue(record.isSet("A"));
assertTrue(record.isSet("B"));
assertFalse(record.isSet("C"));
assertEquals("1", record.get("A"));
assertEquals("2", record.get("B"));
assertFalse(record.isConsistent());
// 2nd record
record = records.next();
assertTrue(record.isMapped("A"));
assertTrue(record.isMapped("B"));
assertTrue(record.isMapped("C"));
assertTrue(record.isSet("A"));
assertTrue(record.isSet("B"));
assertTrue(record.isSet("C"));
assertEquals("x", record.get("A"));
assertEquals("y", record.get("B"));
assertEquals("z", record.get("C"));
assertTrue(record.isConsistent());
assertFalse(records.hasNext());
}
@Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called?
public void testMultipleIterators() throws Exception {
final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT);
final Iterator<CSVRecord> itr1 = parser.iterator();
final Iterator<CSVRecord> itr2 = parser.iterator();
final CSVRecord first = itr1.next();
assertEquals("a", first.get(0));
assertEquals("b", first.get(1));
assertEquals("c", first.get(2));
final CSVRecord second = itr2.next();
assertEquals("d", second.get(0));
assertEquals("e", second.get(1));
assertEquals("f", second.get(2));
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCSVParserNullReaderFormat() throws Exception {
new CSVParser(null, CSVFormat.DEFAULT).close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCSVParserReaderNullFormat() throws Exception {
new CSVParser(new StringReader(""), null).close();
}
@Test
public void testNoHeaderMap() throws Exception {
final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT);
Assert.assertNull(parser.getHeaderMap());
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testParseFileNullFormat() throws Exception {
CSVParser.parse(new File(""), Charset.defaultCharset(), null);
}
@Test(expected = IllegalArgumentException.class)
public void testParseNullFileFormat() throws Exception {
CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT);
}
@Test(expected = IllegalArgumentException.class)
public void testParseNullStringFormat() throws Exception {
CSVParser.parse((String) null, CSVFormat.DEFAULT);
}
@Test(expected = IllegalArgumentException.class)
public void testParseNullUrlCharsetFormat() throws Exception {
CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT);
}
@Test(expected = IllegalArgumentException.class)
public void testParserUrlNullCharsetFormat() throws Exception {
final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), null, CSVFormat.DEFAULT);
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testParseStringNullFormat() throws Exception {
CSVParser.parse("csv data", null);
}
@Test(expected = IllegalArgumentException.class)
public void testParseUrlCharsetNullFormat() throws Exception {
final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), Charset.defaultCharset(), null);
parser.close();
}
@Test
public void testProvidedHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator();
for (int i = 0; i < 3; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertTrue(record.isMapped("A"));
assertTrue(record.isMapped("B"));
assertTrue(record.isMapped("C"));
assertFalse(record.isMapped("NOT MAPPED"));
assertEquals(record.get(0), record.get("A"));
assertEquals(record.get(1), record.get("B"));
assertEquals(record.get(2), record.get("C"));
}
assertFalse(records.hasNext());
}
@Test
public void testProvidedHeaderAuto() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertTrue(record.isMapped("a"));
assertTrue(record.isMapped("b"));
assertTrue(record.isMapped("c"));
assertFalse(record.isMapped("NOT MAPPED"));
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(1), record.get("b"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test
public void testRoundtrip() throws Exception {
final StringWriter out = new StringWriter();
final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT);
final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n";
for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) {
printer.printRecord(record);
}
assertEquals(input, out.toString());
printer.close();
}
@Test
public void testSkipAutoHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
final CSVRecord record = records.next();
assertEquals("1", record.get("a"));
assertEquals("2", record.get("b"));
assertEquals("3", record.get("c"));
}
@Test
public void testSkipSetHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true)
.parse(in).iterator();
final CSVRecord record = records.next();
assertEquals("1", record.get("a"));
assertEquals("2", record.get("b"));
assertEquals("3", record.get("c"));
}
private void validateLineNumbers(final String lineSeparator) throws IOException {
final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator));
assertEquals(0, parser.getCurrentLineNumber());
assertNotNull(parser.nextRecord());
assertEquals(1, parser.getCurrentLineNumber());
assertNotNull(parser.nextRecord());
assertEquals(2, parser.getCurrentLineNumber());
assertNotNull(parser.nextRecord());
// Still 2 because the last line is does not have EOL chars
assertEquals(2, parser.getCurrentLineNumber());
assertNull(parser.nextRecord());
// Still 2 because the last line is does not have EOL chars
assertEquals(2, parser.getCurrentLineNumber());
parser.close();
}
private void validateRecordNumbers(final String lineSeparator) throws IOException {
final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator));
CSVRecord record;
assertEquals(0, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(1, record.getRecordNumber());
assertEquals(1, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(2, record.getRecordNumber());
assertEquals(2, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(3, record.getRecordNumber());
assertEquals(3, parser.getRecordNumber());
assertNull(record = parser.nextRecord());
assertEquals(3, parser.getRecordNumber());
parser.close();
}
} | // You are a professional Java test case writer, please create a test case named `testHeaderMissingWithNull` for the issue `Csv-CSV-122`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Csv-CSV-122
//
// ## Issue-Title:
// NullPointerException when empty header string and and null string of ""
//
// ## Issue-Description:
//
// When setting the format to have a nullString of "" and having an empty header value, a nullPointerException is thrown.
//
//
//
//
//
@Test
public void testHeaderMissingWithNull() throws Exception {
| 670 | 11 | 666 | src/test/java/org/apache/commons/csv/CSVParserTest.java | src/test/java | ```markdown
## Issue-ID: Csv-CSV-122
## Issue-Title:
NullPointerException when empty header string and and null string of ""
## Issue-Description:
When setting the format to have a nullString of "" and having an empty header value, a nullPointerException is thrown.
```
You are a professional Java test case writer, please create a test case named `testHeaderMissingWithNull` for the issue `Csv-CSV-122`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testHeaderMissingWithNull() throws Exception {
```
| 666 | [
"org.apache.commons.csv.CSVParser"
] | 50b2f4870c16eae445fb17813cd1f21d4665380af553b4803c0257ad4b98aebb | @Test
public void testHeaderMissingWithNull() throws Exception | // You are a professional Java test case writer, please create a test case named `testHeaderMissingWithNull` for the issue `Csv-CSV-122`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Csv-CSV-122
//
// ## Issue-Title:
// NullPointerException when empty header string and and null string of ""
//
// ## Issue-Description:
//
// When setting the format to have a nullString of "" and having an empty header value, a nullPointerException is thrown.
//
//
//
//
//
| 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.apache.commons.csv.Constants.CRLF;
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.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.apache.commons.io.input.BOMInputStream;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* CSVParserTest
*
* The test are organized in three different sections:
* The 'setter/getter' section, the lexer section and finally the parser
* section. In case a test fails, you should follow a top-down approach for
* fixing a potential bug (its likely that the parser itself fails if the lexer
* has problems...).
*
* @version $Id$
*/
public class CSVParserTest {
private static final String CSV_INPUT = "a,b,c,d\n"
+ " a , b , 1 2 \n"
+ "\"foo baar\", b,\n"
// + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n";
+ " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping
private static final String CSV_INPUT_1 = "a,b,c,d";
private static final String CSV_INPUT_2 = "a,b,1 2";
private static final String[][] RESULT = {
{"a", "b", "c", "d"},
{"a", "b", "1 2"},
{"foo baar", "b", ""},
{"foo\n,,\n\",,\n\"", "d", "e"}
};
@Test
public void testBackslashEscaping() throws IOException {
// To avoid confusion over the need for escaping chars in java code,
// We will test with a forward slash as the escape char, and a single
// quote as the encapsulator.
final String code =
"one,two,three\n" // 0
+ "'',''\n" // 1) empty encapsulators
+ "/',/'\n" // 2) single encapsulators
+ "'/'','/''\n" // 3) single encapsulators encapsulated via escape
+ "'''',''''\n" // 4) single encapsulators encapsulated via doubling
+ "/,,/,\n" // 5) separator escaped
+ "//,//\n" // 6) escape escaped
+ "'//','//'\n" // 7) escape escaped in encapsulation
+ " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces
+ "9, /\n \n" // escaped newline
+ "";
final String[][] res = {
{"one", "two", "three"}, // 0
{"", ""}, // 1
{"'", "'"}, // 2
{"'", "'"}, // 3
{"'", "'"}, // 4
{",", ","}, // 5
{"/", "/"}, // 6
{"/", "/"}, // 7
{" 8 ", " \"quoted \"\" /\" / string\" "},
{"9", " \n "},
};
final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'')
.withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true);
final CSVParser parser = CSVParser.parse(code, format);
final List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Records do not match expected result", res, records);
parser.close();
}
@Test
public void testBackslashEscaping2() throws IOException {
// To avoid confusion over the need for escaping chars in java code,
// We will test with a forward slash as the escape char, and a single
// quote as the encapsulator.
final String code = ""
+ " , , \n" // 1)
+ " \t , , \n" // 2)
+ " // , /, , /,\n" // 3)
+ "";
final String[][] res = {
{" ", " ", " "}, // 1
{" \t ", " ", " "}, // 2
{" / ", " , ", " ,"}, // 3
};
final CSVFormat format = CSVFormat.newFormat(',')
.withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true);
final CSVParser parser = CSVParser.parse(code, format);
final List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("", res, records);
parser.close();
}
@Test
@Ignore
public void testBackslashEscapingOld() throws IOException {
final String code =
"one,two,three\n"
+ "on\\\"e,two\n"
+ "on\"e,two\n"
+ "one,\"tw\\\"o\"\n"
+ "one,\"t\\,wo\"\n"
+ "one,two,\"th,ree\"\n"
+ "\"a\\\\\"\n"
+ "a\\,b\n"
+ "\"a\\\\,b\"";
final String[][] res = {
{"one", "two", "three"},
{"on\\\"e", "two"},
{"on\"e", "two"},
{"one", "tw\"o"},
{"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",")
{"one", "two", "th,ree"},
{"a\\\\"}, // backslash in quotes only escapes a delimiter (",")
{"a\\", "b"}, // a backslash must be returnd
{"a\\\\,b"} // backslash in quotes only escapes a delimiter (",")
};
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
@Test
@Ignore("CSV-107")
public void testBOM() throws IOException {
final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv");
final CSVParser parser = CSVParser.parse(url, Charset.forName("UTF-8"), CSVFormat.EXCEL.withHeader());
try {
for (final CSVRecord record : parser) {
final String string = record.get("Date");
Assert.assertNotNull(string);
//System.out.println("date: " + record.get("Date"));
}
} finally {
parser.close();
}
}
@Test
public void testBOMInputStream() {}
// Defects4J: flaky method
// @Test
// public void testBOMInputStream() throws IOException {
// final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv");
// final Reader reader = new InputStreamReader(new BOMInputStream(url.openStream()), "UTF-8");
// final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
// try {
// for (final CSVRecord record : parser) {
// final String string = record.get("Date");
// Assert.assertNotNull(string);
// //System.out.println("date: " + record.get("Date"));
// }
// } finally {
// parser.close();
// reader.close();
// }
// }
@Test
public void testCarriageReturnEndings() throws IOException {
final String code = "foo\rbaar,\rhello,world\r,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
@Test
public void testCarriageReturnLineFeedEndings() throws IOException {
final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
@Test(expected = NoSuchElementException.class)
public void testClose() throws Exception {
final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z");
final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in);
final Iterator<CSVRecord> records = parser.iterator();
assertTrue(records.hasNext());
parser.close();
assertFalse(records.hasNext());
records.next();
}
@Test
public void testCSV57() throws Exception {
final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT);
final List<CSVRecord> list = parser.getRecords();
assertNotNull(list);
assertEquals(0, list.size());
parser.close();
}
@Test
public void testDefaultFormat() throws IOException {
final String code = ""
+ "a,b#\n" // 1)
+ "\"\n\",\" \",#\n" // 2)
+ "#,\"\"\n" // 3)
+ "# Final comment\n"// 4)
;
final String[][] res = {
{"a", "b#"},
{"\n", " ", "#"},
{"#", ""},
{"# Final comment"}
};
CSVFormat format = CSVFormat.DEFAULT;
assertFalse(format.isCommentingEnabled());
CSVParser parser = CSVParser.parse(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Failed to parse without comments", res, records);
final String[][] res_comments = {
{"a", "b#"},
{"\n", " ", "#"},
};
format = CSVFormat.DEFAULT.withCommentStart('#');
parser.close();
parser = CSVParser.parse(code, format);
records = parser.getRecords();
Utils.compare("Failed to parse with comments", res_comments, records);
parser.close();
}
@Test
public void testEmptyFile() throws Exception {
final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT);
assertNull(parser.nextRecord());
parser.close();
}
@Test
public void testEmptyLineBehaviourCSV() throws Exception {
final String[] codes = {
"hello,\r\n\r\n\r\n",
"hello,\n\n\n",
"hello,\"\"\r\n\r\n\r\n",
"hello,\"\"\n\n\n"
};
final String[][] res = {
{"hello", ""} // CSV format ignores empty lines
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testEmptyLineBehaviourExcel() throws Exception {
final String[] codes = {
"hello,\r\n\r\n\r\n",
"hello,\n\n\n",
"hello,\"\"\r\n\r\n\r\n",
"hello,\"\"\n\n\n"
};
final String[][] res = {
{"hello", ""},
{""}, // Excel format does not ignore empty lines
{""}
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testEndOfFileBehaviorCSV() throws Exception {
final String[] codes = {
"hello,\r\n\r\nworld,\r\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\r\n",
"hello,\r\n\r\nworld,\"\"",
"hello,\r\n\r\nworld,\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\n",
"hello,\r\n\r\nworld,\"\""
};
final String[][] res = {
{"hello", ""}, // CSV format ignores empty lines
{"world", ""}
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testEndOfFileBehaviourExcel() throws Exception {
final String[] codes = {
"hello,\r\n\r\nworld,\r\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\r\n",
"hello,\r\n\r\nworld,\"\"",
"hello,\r\n\r\nworld,\n",
"hello,\r\n\r\nworld,",
"hello,\r\n\r\nworld,\"\"\n",
"hello,\r\n\r\nworld,\"\""
};
final String[][] res = {
{"hello", ""},
{""}, // Excel format does not ignore empty lines
{"world", ""}
};
for (final String code : codes) {
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
}
@Test
public void testExcelFormat1() throws IOException {
final String code =
"value1,value2,value3,value4\r\na,b,c,d\r\n x,,,"
+ "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n";
final String[][] res = {
{"value1", "value2", "value3", "value4"},
{"a", "b", "c", "d"},
{" x", "", "", ""},
{""},
{"\"hello\"", " \"world\"", "abc\ndef", ""}
};
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
@Test
public void testExcelFormat2() throws Exception {
final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n";
final String[][] res = {
{"foo", "baar"},
{""},
{"hello", ""},
{""},
{"world", ""}
};
final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL);
final List<CSVRecord> records = parser.getRecords();
assertEquals(res.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertArrayEquals(res[i], records.get(i).values());
}
parser.close();
}
@Test
public void testForEach() throws Exception {
final List<CSVRecord> records = new ArrayList<CSVRecord>();
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) {
records.add(record);
}
assertEquals(3, records.size());
assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values());
assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values());
assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values());
}
@Test
public void testGetHeaderMap() throws Exception {
final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C"));
final Map<String, Integer> headerMap = parser.getHeaderMap();
final Iterator<String> columnNames = headerMap.keySet().iterator();
// Headers are iterated in column order.
Assert.assertEquals("A", columnNames.next());
Assert.assertEquals("B", columnNames.next());
Assert.assertEquals("C", columnNames.next());
final Iterator<CSVRecord> records = parser.iterator();
// Parse to make sure getHeaderMap did not have a side-effect.
for (int i = 0; i < 3; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("A"));
assertEquals(record.get(1), record.get("B"));
assertEquals(record.get(2), record.get("C"));
}
assertFalse(records.hasNext());
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testDuplicateHeaders() throws Exception {
CSVParser.parse("a,b,a\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader(new String[]{}));
}
@Test
public void testGetLine() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));
for (final String[] re : RESULT) {
assertArrayEquals(re, parser.nextRecord().values());
}
assertNull(parser.nextRecord());
parser.close();
}
@Test
public void testGetLineNumberWithCR() throws Exception {
this.validateLineNumbers(String.valueOf(CR));
}
@Test
public void testGetLineNumberWithCRLF() throws Exception {
this.validateLineNumbers(CRLF);
}
@Test
public void testGetLineNumberWithLF() throws Exception {
this.validateLineNumbers(String.valueOf(LF));
}
@Test
public void testGetOneLine() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT);
final CSVRecord record = parser.getRecords().get(0);
assertArrayEquals(RESULT[0], record.values());
parser.close();
}
@Test
public void testGetOneLineCustomCollection() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT);
final CSVRecord record = parser.getRecords(new LinkedList<CSVRecord>()).getFirst();
assertArrayEquals(RESULT[0], record.values());
parser.close();
}
/**
* Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110].
*
* @throws IOException
*/
@Test
public void testGetOneLineOneParser() throws IOException {
final PipedWriter writer = new PipedWriter();
final PipedReader reader = new PipedReader(writer);
final CSVFormat format = CSVFormat.DEFAULT;
final CSVParser parser = new CSVParser(reader, format);
try {
writer.append(CSV_INPUT_1);
writer.append(format.getRecordSeparator());
final CSVRecord record1 = parser.nextRecord();
assertArrayEquals(RESULT[0], record1.values());
writer.append(CSV_INPUT_2);
writer.append(format.getRecordSeparator());
final CSVRecord record2 = parser.nextRecord();
assertArrayEquals(RESULT[1], record2.values());
} finally {
parser.close();
}
}
@Test
public void testGetRecordNumberWithCR() throws Exception {
this.validateRecordNumbers(String.valueOf(CR));
}
@Test
public void testGetRecordNumberWithCRLF() throws Exception {
this.validateRecordNumbers(CRLF);
}
@Test
public void testGetRecordNumberWithLF() throws Exception {
this.validateRecordNumbers(String.valueOf(LF));
}
@Test
public void testGetRecords() throws IOException {
final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));
final List<CSVRecord> records = parser.getRecords();
assertEquals(RESULT.length, records.size());
assertTrue(records.size() > 0);
for (int i = 0; i < RESULT.length; i++) {
assertArrayEquals(RESULT[i], records.get(i).values());
}
parser.close();
}
@Test
public void testGetRecordWithMultiLineValues() throws Exception {
final CSVParser parser = CSVParser.parse("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"",
CSVFormat.DEFAULT.withRecordSeparator(CRLF));
CSVRecord record;
assertEquals(0, parser.getRecordNumber());
assertEquals(0, parser.getCurrentLineNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(3, parser.getCurrentLineNumber());
assertEquals(1, record.getRecordNumber());
assertEquals(1, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(6, parser.getCurrentLineNumber());
assertEquals(2, record.getRecordNumber());
assertEquals(2, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(8, parser.getCurrentLineNumber());
assertEquals(3, record.getRecordNumber());
assertEquals(3, parser.getRecordNumber());
assertNull(record = parser.nextRecord());
assertEquals(8, parser.getCurrentLineNumber());
assertEquals(3, parser.getRecordNumber());
parser.close();
}
@Test
public void testHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(1), record.get("b"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test
public void testHeaderMissing() throws Exception {
final Reader in = new StringReader("a,,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test(expected=IllegalArgumentException.class)
public void testHeadersMissingException() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().parse(in).iterator();
}
@Test
public void testHeadersMissing() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().withIgnoreEmptyHeaders(true).parse(in).iterator();
}
@Test
public void testHeaderMissingWithNull() throws Exception {
final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz");
CSVFormat.DEFAULT.withHeader().withNullString("").withIgnoreEmptyHeaders(true).parse(in).iterator();
}
@Test
public void testHeaderComment() throws Exception {
final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(1), record.get("b"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test
public void testIgnoreEmptyLines() throws IOException {
final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n";
//String code = "world\r\n\n";
//String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(3, records.size());
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testInvalidFormat() throws Exception {
final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR);
new CSVParser(null, invalidFormat).close();
}
@Test
public void testIterator() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> iterator = CSVFormat.DEFAULT.parse(in).iterator();
assertTrue(iterator.hasNext());
try {
iterator.remove();
fail("expected UnsupportedOperationException");
} catch (final UnsupportedOperationException expected) {
// expected
}
assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values());
assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values());
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("NoSuchElementException expected");
} catch (final NoSuchElementException e) {
// expected
}
}
@Test
public void testLineFeedEndings() throws IOException {
final String code = "foo\nbaar,\nhello,world\n,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
@Test
public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true)
.parse(in).iterator();
CSVRecord record;
// 1st record
record = records.next();
assertTrue(record.isMapped("A"));
assertTrue(record.isMapped("B"));
assertTrue(record.isMapped("C"));
assertTrue(record.isSet("A"));
assertTrue(record.isSet("B"));
assertFalse(record.isSet("C"));
assertEquals("1", record.get("A"));
assertEquals("2", record.get("B"));
assertFalse(record.isConsistent());
// 2nd record
record = records.next();
assertTrue(record.isMapped("A"));
assertTrue(record.isMapped("B"));
assertTrue(record.isMapped("C"));
assertTrue(record.isSet("A"));
assertTrue(record.isSet("B"));
assertTrue(record.isSet("C"));
assertEquals("x", record.get("A"));
assertEquals("y", record.get("B"));
assertEquals("z", record.get("C"));
assertTrue(record.isConsistent());
assertFalse(records.hasNext());
}
@Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called?
public void testMultipleIterators() throws Exception {
final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT);
final Iterator<CSVRecord> itr1 = parser.iterator();
final Iterator<CSVRecord> itr2 = parser.iterator();
final CSVRecord first = itr1.next();
assertEquals("a", first.get(0));
assertEquals("b", first.get(1));
assertEquals("c", first.get(2));
final CSVRecord second = itr2.next();
assertEquals("d", second.get(0));
assertEquals("e", second.get(1));
assertEquals("f", second.get(2));
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCSVParserNullReaderFormat() throws Exception {
new CSVParser(null, CSVFormat.DEFAULT).close();
}
@Test(expected = IllegalArgumentException.class)
public void testNewCSVParserReaderNullFormat() throws Exception {
new CSVParser(new StringReader(""), null).close();
}
@Test
public void testNoHeaderMap() throws Exception {
final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT);
Assert.assertNull(parser.getHeaderMap());
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testParseFileNullFormat() throws Exception {
CSVParser.parse(new File(""), Charset.defaultCharset(), null);
}
@Test(expected = IllegalArgumentException.class)
public void testParseNullFileFormat() throws Exception {
CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT);
}
@Test(expected = IllegalArgumentException.class)
public void testParseNullStringFormat() throws Exception {
CSVParser.parse((String) null, CSVFormat.DEFAULT);
}
@Test(expected = IllegalArgumentException.class)
public void testParseNullUrlCharsetFormat() throws Exception {
CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT);
}
@Test(expected = IllegalArgumentException.class)
public void testParserUrlNullCharsetFormat() throws Exception {
final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), null, CSVFormat.DEFAULT);
parser.close();
}
@Test(expected = IllegalArgumentException.class)
public void testParseStringNullFormat() throws Exception {
CSVParser.parse("csv data", null);
}
@Test(expected = IllegalArgumentException.class)
public void testParseUrlCharsetNullFormat() throws Exception {
final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), Charset.defaultCharset(), null);
parser.close();
}
@Test
public void testProvidedHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator();
for (int i = 0; i < 3; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertTrue(record.isMapped("A"));
assertTrue(record.isMapped("B"));
assertTrue(record.isMapped("C"));
assertFalse(record.isMapped("NOT MAPPED"));
assertEquals(record.get(0), record.get("A"));
assertEquals(record.get(1), record.get("B"));
assertEquals(record.get(2), record.get("C"));
}
assertFalse(records.hasNext());
}
@Test
public void testProvidedHeaderAuto() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
for (int i = 0; i < 2; i++) {
assertTrue(records.hasNext());
final CSVRecord record = records.next();
assertTrue(record.isMapped("a"));
assertTrue(record.isMapped("b"));
assertTrue(record.isMapped("c"));
assertFalse(record.isMapped("NOT MAPPED"));
assertEquals(record.get(0), record.get("a"));
assertEquals(record.get(1), record.get("b"));
assertEquals(record.get(2), record.get("c"));
}
assertFalse(records.hasNext());
}
@Test
public void testRoundtrip() throws Exception {
final StringWriter out = new StringWriter();
final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT);
final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n";
for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) {
printer.printRecord(record);
}
assertEquals(input, out.toString());
printer.close();
}
@Test
public void testSkipAutoHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator();
final CSVRecord record = records.next();
assertEquals("1", record.get("a"));
assertEquals("2", record.get("b"));
assertEquals("3", record.get("c"));
}
@Test
public void testSkipSetHeader() throws Exception {
final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true)
.parse(in).iterator();
final CSVRecord record = records.next();
assertEquals("1", record.get("a"));
assertEquals("2", record.get("b"));
assertEquals("3", record.get("c"));
}
private void validateLineNumbers(final String lineSeparator) throws IOException {
final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator));
assertEquals(0, parser.getCurrentLineNumber());
assertNotNull(parser.nextRecord());
assertEquals(1, parser.getCurrentLineNumber());
assertNotNull(parser.nextRecord());
assertEquals(2, parser.getCurrentLineNumber());
assertNotNull(parser.nextRecord());
// Still 2 because the last line is does not have EOL chars
assertEquals(2, parser.getCurrentLineNumber());
assertNull(parser.nextRecord());
// Still 2 because the last line is does not have EOL chars
assertEquals(2, parser.getCurrentLineNumber());
parser.close();
}
private void validateRecordNumbers(final String lineSeparator) throws IOException {
final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator));
CSVRecord record;
assertEquals(0, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(1, record.getRecordNumber());
assertEquals(1, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(2, record.getRecordNumber());
assertEquals(2, parser.getRecordNumber());
assertNotNull(record = parser.nextRecord());
assertEquals(3, record.getRecordNumber());
assertEquals(3, parser.getRecordNumber());
assertNull(record = parser.nextRecord());
assertEquals(3, parser.getRecordNumber());
parser.close();
}
} |
||
public void test() throws Exception
{
Options options = buildCommandLineOptions();
CommandLineParser parser = new PosixParser();
String[] args = new String[] {"-t", "-something" };
CommandLine commandLine;
commandLine = parser.parse( options, args );
assertEquals("-something", commandLine.getOptionValue( 't'));
} | org.apache.commons.cli.bug.BugCLI51Test::test | src/test/org/apache/commons/cli/bug/BugCLI51Test.java | 41 | src/test/org/apache/commons/cli/bug/BugCLI51Test.java | test | /*
* 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 junit.framework.TestCase;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Option;
/**
* @author brianegge
*/
public class BugCLI51Test
extends TestCase
{
public void test() throws Exception
{
Options options = buildCommandLineOptions();
CommandLineParser parser = new PosixParser();
String[] args = new String[] {"-t", "-something" };
CommandLine commandLine;
commandLine = parser.parse( options, args );
assertEquals("-something", commandLine.getOptionValue( 't'));
}
private Options buildCommandLineOptions()
{
Option opt = OptionBuilder.withArgName( "t").hasArg().create('t');
Options options = new Options();
options.addOption( opt);
return options;
}
} | // You are a professional Java test case writer, please create a test case named `test` for the issue `Cli-CLI-51`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-51
//
// ## Issue-Title:
// [cli] Parameter value "-something" misinterpreted as a parameter
//
// ## Issue-Description:
//
// If a parameter value is passed that contains a hyphen as the (delimited) first
//
// character, CLI parses this a parameter. For example using the call
//
// java myclass -t "-something"
//
// Results in the parser creating the invalid parameter -o (noting that it is
//
// skipping the 's')
//
//
// My code is using the Posix parser as follows
//
// Options options = buildCommandLineOptions();
//
// CommandLineParser parser = new PosixParser();
//
// CommandLine commandLine = null;
//
// try {
//
//
// commandLine = parser.parse(options, args);
//
// }
//
// catch (ParseException e) {
//
//
// System.out.println("Invalid parameters. " + e.getMessage() + NEW\_LINE);
//
// System.exit(EXIT\_CODE\_ERROR);
//
// }
//
//
// This has been tested against the nightly build dated 20050503.
//
//
//
//
//
public void test() throws Exception {
| 41 | 2 | 33 | src/test/org/apache/commons/cli/bug/BugCLI51Test.java | src/test | ```markdown
## Issue-ID: Cli-CLI-51
## Issue-Title:
[cli] Parameter value "-something" misinterpreted as a parameter
## Issue-Description:
If a parameter value is passed that contains a hyphen as the (delimited) first
character, CLI parses this a parameter. For example using the call
java myclass -t "-something"
Results in the parser creating the invalid parameter -o (noting that it is
skipping the 's')
My code is using the Posix parser as follows
Options options = buildCommandLineOptions();
CommandLineParser parser = new PosixParser();
CommandLine commandLine = null;
try {
commandLine = parser.parse(options, args);
}
catch (ParseException e) {
System.out.println("Invalid parameters. " + e.getMessage() + NEW\_LINE);
System.exit(EXIT\_CODE\_ERROR);
}
This has been tested against the nightly build dated 20050503.
```
You are a professional Java test case writer, please create a test case named `test` for the issue `Cli-CLI-51`, utilizing the provided issue report information and the following function signature.
```java
public void test() throws Exception {
```
| 33 | [
"org.apache.commons.cli.PosixParser"
] | 510442be9a9617bf9110d20d33b1bbff24ec4b53e7d434c364304c9b24e08462 | public void test() throws Exception
| // You are a professional Java test case writer, please create a test case named `test` for the issue `Cli-CLI-51`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-51
//
// ## Issue-Title:
// [cli] Parameter value "-something" misinterpreted as a parameter
//
// ## Issue-Description:
//
// If a parameter value is passed that contains a hyphen as the (delimited) first
//
// character, CLI parses this a parameter. For example using the call
//
// java myclass -t "-something"
//
// Results in the parser creating the invalid parameter -o (noting that it is
//
// skipping the 's')
//
//
// My code is using the Posix parser as follows
//
// Options options = buildCommandLineOptions();
//
// CommandLineParser parser = new PosixParser();
//
// CommandLine commandLine = null;
//
// try {
//
//
// commandLine = parser.parse(options, args);
//
// }
//
// catch (ParseException e) {
//
//
// System.out.println("Invalid parameters. " + e.getMessage() + NEW\_LINE);
//
// System.exit(EXIT\_CODE\_ERROR);
//
// }
//
//
// This has been tested against the nightly build dated 20050503.
//
//
//
//
//
| 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 junit.framework.TestCase;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Option;
/**
* @author brianegge
*/
public class BugCLI51Test
extends TestCase
{
public void test() throws Exception
{
Options options = buildCommandLineOptions();
CommandLineParser parser = new PosixParser();
String[] args = new String[] {"-t", "-something" };
CommandLine commandLine;
commandLine = parser.parse( options, args );
assertEquals("-something", commandLine.getOptionValue( 't'));
}
private Options buildCommandLineOptions()
{
Option opt = OptionBuilder.withArgName( "t").hasArg().create('t');
Options options = new Options();
options.addOption( opt);
return options;
}
} |
||
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
File dir = mkdir("COMPRESS-279");
TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar");
FileOutputStream out = null;
try {
TarArchiveEntry entry = is.getNextTarEntry();
int count = 0;
while (entry != null) {
out = new FileOutputStream(new File(dir, String.valueOf(count)));
IOUtils.copy(is, out);
out.close();
out = null;
count++;
entry = is.getNextTarEntry();
}
} finally {
is.close();
if (out != null) {
out.close();
}
}
} | org.apache.commons.compress.archivers.tar.TarArchiveInputStreamTest::shouldThrowAnExceptionOnTruncatedEntries | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | 233 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | shouldThrowAnExceptionOnTruncatedEntries | /*
* 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.apache.commons.compress.AbstractTestCase.getFile;
import static org.apache.commons.compress.AbstractTestCase.mkdir;
import static org.apache.commons.compress.AbstractTestCase.rmdir;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.utils.CharsetNames;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
public class TarArchiveInputStreamTest {
@Test
public void readSimplePaxHeader() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
@Test
public void readPaxHeaderWithEmbeddedNewline() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("line1\nline2\nand3", headers.get("comment"));
tais.close();
}
@Test
public void readNonAsciiPaxHeader() throws Exception {
String ae = "\u00e4";
String line = "11 path="+ ae + "\n";
assertEquals(11, line.getBytes(CharsetNames.UTF_8).length);
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals(ae, headers.get("path"));
tais.close();
}
@Test
public void workaroundForBrokenTimeHeader() throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar")));
TarArchiveEntry tae = in.getNextTarEntry();
tae = in.getNextTarEntry();
assertEquals("sample/link-to-txt-file.lnk", tae.getName());
assertEquals(new Date(0), tae.getLastModifiedDate());
assertTrue(tae.isSymbolicLink());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void datePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("preepoch-star.tar");
}
@Test
public void datePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("preepoch-posix.tar");
}
private void datePriorToEpoch(String archive) throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile(archive)));
TarArchiveEntry tae = in.getNextTarEntry();
assertEquals("foo", tae.getName());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1969, 11, 31, 23, 59, 59);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(cal.getTime(), tae.getLastModifiedDate());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
}
@Test
public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()
throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoding = CharsetNames.UTF_16;
String name = "1234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890\u00e4";
TarArchiveOutputStream tos =
new TarArchiveOutputStream(bos, encoding);
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
TarArchiveEntry t = new TarArchiveEntry(name);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis, encoding);
t = tis.getNextTarEntry();
assertEquals(name, t.getName());
tis.close();
}
@Test
public void shouldConsumeArchiveCompletely() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/archive_with_trailer.tar");
TarArchiveInputStream tar = new TarArchiveInputStream(is);
while (tar.getNextTarEntry() != null) {
// just consume the archive
}
byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'
};
byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
tar.close();
}
@Test
public void readsArchiveCompletely_COMPRESS245() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/COMPRESS-245.tar.gz");
try {
InputStream gin = new GZIPInputStream(is);
TarArchiveInputStream tar = new TarArchiveInputStream(gin);
int count = 0;
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
count++;
entry = tar.getNextTarEntry();
}
assertEquals(31, count);
} catch (IOException e) {
fail("COMPRESS-245: " + e.getMessage());
} finally {
is.close();
}
}
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
File dir = mkdir("COMPRESS-279");
TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar");
FileOutputStream out = null;
try {
TarArchiveEntry entry = is.getNextTarEntry();
int count = 0;
while (entry != null) {
out = new FileOutputStream(new File(dir, String.valueOf(count)));
IOUtils.copy(is, out);
out.close();
out = null;
count++;
entry = is.getNextTarEntry();
}
} finally {
is.close();
if (out != null) {
out.close();
}
}
}
private TarArchiveInputStream getTestStream(String name) {
return new TarArchiveInputStream(
TarArchiveInputStreamTest.class.getResourceAsStream(name));
}
} | // You are a professional Java test case writer, please create a test case named `shouldThrowAnExceptionOnTruncatedEntries` for the issue `Compress-COMPRESS-279`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-279
//
// ## Issue-Title:
// TarArchiveInputStream silently finished when unexpected EOF occured
//
// ## Issue-Description:
//
// I just found the following test case didn't raise an IOException as it used to be for a **tar trimmed on purpose**
//
//
// @Test
//
// public void testCorruptedBzip2() throws IOException {
//
// String archivePath = PathUtil.join(testdataDir, "test.tar.bz2");
//
// TarArchiveInputStream input = null;
//
// input = new TarArchiveInputStream(new BZip2CompressorInputStream(
//
// GoogleFile.SYSTEM.newInputStream(archivePath), true));
//
// ArchiveEntry nextMatchedEntry = input.getNextEntry();
//
// while (nextMatchedEntry != null)
//
//
// {
// logger.infofmt("Extracting %s", nextMatchedEntry.getName());
// String outputPath = PathUtil.join("/tmp/", nextMatchedEntry.getName());
// OutputStream out = new FileOutputStream(outputPath);
// ByteStreams.copy(input, out);
// out.close();
// nextMatchedEntry = input.getNextEntry();
// }
// }
//
//
//
//
//
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
| 233 | 28 | 211 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-279
## Issue-Title:
TarArchiveInputStream silently finished when unexpected EOF occured
## Issue-Description:
I just found the following test case didn't raise an IOException as it used to be for a **tar trimmed on purpose**
@Test
public void testCorruptedBzip2() throws IOException {
String archivePath = PathUtil.join(testdataDir, "test.tar.bz2");
TarArchiveInputStream input = null;
input = new TarArchiveInputStream(new BZip2CompressorInputStream(
GoogleFile.SYSTEM.newInputStream(archivePath), true));
ArchiveEntry nextMatchedEntry = input.getNextEntry();
while (nextMatchedEntry != null)
{
logger.infofmt("Extracting %s", nextMatchedEntry.getName());
String outputPath = PathUtil.join("/tmp/", nextMatchedEntry.getName());
OutputStream out = new FileOutputStream(outputPath);
ByteStreams.copy(input, out);
out.close();
nextMatchedEntry = input.getNextEntry();
}
}
```
You are a professional Java test case writer, please create a test case named `shouldThrowAnExceptionOnTruncatedEntries` for the issue `Compress-COMPRESS-279`, utilizing the provided issue report information and the following function signature.
```java
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
```
| 211 | [
"org.apache.commons.compress.archivers.tar.TarArchiveInputStream"
] | 516c270a46ec9c17758e370b8a69fc64b2c46af7c2ca5353fc7c580613b6484f | @Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception | // You are a professional Java test case writer, please create a test case named `shouldThrowAnExceptionOnTruncatedEntries` for the issue `Compress-COMPRESS-279`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-279
//
// ## Issue-Title:
// TarArchiveInputStream silently finished when unexpected EOF occured
//
// ## Issue-Description:
//
// I just found the following test case didn't raise an IOException as it used to be for a **tar trimmed on purpose**
//
//
// @Test
//
// public void testCorruptedBzip2() throws IOException {
//
// String archivePath = PathUtil.join(testdataDir, "test.tar.bz2");
//
// TarArchiveInputStream input = null;
//
// input = new TarArchiveInputStream(new BZip2CompressorInputStream(
//
// GoogleFile.SYSTEM.newInputStream(archivePath), true));
//
// ArchiveEntry nextMatchedEntry = input.getNextEntry();
//
// while (nextMatchedEntry != null)
//
//
// {
// logger.infofmt("Extracting %s", nextMatchedEntry.getName());
// String outputPath = PathUtil.join("/tmp/", nextMatchedEntry.getName());
// OutputStream out = new FileOutputStream(outputPath);
// ByteStreams.copy(input, out);
// out.close();
// nextMatchedEntry = input.getNextEntry();
// }
// }
//
//
//
//
//
| 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.apache.commons.compress.AbstractTestCase.getFile;
import static org.apache.commons.compress.AbstractTestCase.mkdir;
import static org.apache.commons.compress.AbstractTestCase.rmdir;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.utils.CharsetNames;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
public class TarArchiveInputStreamTest {
@Test
public void readSimplePaxHeader() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
@Test
public void readPaxHeaderWithEmbeddedNewline() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("line1\nline2\nand3", headers.get("comment"));
tais.close();
}
@Test
public void readNonAsciiPaxHeader() throws Exception {
String ae = "\u00e4";
String line = "11 path="+ ae + "\n";
assertEquals(11, line.getBytes(CharsetNames.UTF_8).length);
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals(ae, headers.get("path"));
tais.close();
}
@Test
public void workaroundForBrokenTimeHeader() throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile("simple-aix-native-tar.tar")));
TarArchiveEntry tae = in.getNextTarEntry();
tae = in.getNextTarEntry();
assertEquals("sample/link-to-txt-file.lnk", tae.getName());
assertEquals(new Date(0), tae.getLastModifiedDate());
assertTrue(tae.isSymbolicLink());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void datePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("preepoch-star.tar");
}
@Test
public void datePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("preepoch-posix.tar");
}
private void datePriorToEpoch(String archive) throws Exception {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(getFile(archive)));
TarArchiveEntry tae = in.getNextTarEntry();
assertEquals("foo", tae.getName());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1969, 11, 31, 23, 59, 59);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(cal.getTime(), tae.getLastModifiedDate());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
}
@Test
public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()
throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String encoding = CharsetNames.UTF_16;
String name = "1234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890\u00e4";
TarArchiveOutputStream tos =
new TarArchiveOutputStream(bos, encoding);
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
TarArchiveEntry t = new TarArchiveEntry(name);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
byte[] data = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(data);
TarArchiveInputStream tis =
new TarArchiveInputStream(bis, encoding);
t = tis.getNextTarEntry();
assertEquals(name, t.getName());
tis.close();
}
@Test
public void shouldConsumeArchiveCompletely() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/archive_with_trailer.tar");
TarArchiveInputStream tar = new TarArchiveInputStream(is);
while (tar.getNextTarEntry() != null) {
// just consume the archive
}
byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'
};
byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
tar.close();
}
@Test
public void readsArchiveCompletely_COMPRESS245() throws Exception {
InputStream is = TarArchiveInputStreamTest.class
.getResourceAsStream("/COMPRESS-245.tar.gz");
try {
InputStream gin = new GZIPInputStream(is);
TarArchiveInputStream tar = new TarArchiveInputStream(gin);
int count = 0;
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
count++;
entry = tar.getNextTarEntry();
}
assertEquals(31, count);
} catch (IOException e) {
fail("COMPRESS-245: " + e.getMessage());
} finally {
is.close();
}
}
@Test(expected = IOException.class)
public void shouldThrowAnExceptionOnTruncatedEntries() throws Exception {
File dir = mkdir("COMPRESS-279");
TarArchiveInputStream is = getTestStream("/COMPRESS-279.tar");
FileOutputStream out = null;
try {
TarArchiveEntry entry = is.getNextTarEntry();
int count = 0;
while (entry != null) {
out = new FileOutputStream(new File(dir, String.valueOf(count)));
IOUtils.copy(is, out);
out.close();
out = null;
count++;
entry = is.getNextTarEntry();
}
} finally {
is.close();
if (out != null) {
out.close();
}
}
}
private TarArchiveInputStream getTestStream(String name) {
return new TarArchiveInputStream(
TarArchiveInputStreamTest.class.getResourceAsStream(name));
}
} |
||
public void testLang299() {
StrBuilder sb = new StrBuilder(1);
sb.appendFixedWidthPadRight("foo", 1, '-');
assertEquals("f", sb.toString());
} | org.apache.commons.lang.text.StrBuilderAppendInsertTest::testLang299 | src/test/org/apache/commons/lang/text/StrBuilderAppendInsertTest.java | 603 | src/test/org/apache/commons/lang/text/StrBuilderAppendInsertTest.java | testLang299 | /*
* 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.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import org.apache.commons.lang.SystemUtils;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Unit tests for {@link org.apache.commons.lang.text.StrBuilder}.
*
* @version $Id$
*/
public class StrBuilderAppendInsertTest extends TestCase {
/** Test subclass of Object, with a toString method. */
private static Object FOO = new Object() {
public String toString() {
return "foo";
}
};
/**
* Main method.
*
* @param args command line arguments, ignored
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* 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(StrBuilderAppendInsertTest.class);
suite.setName("StrBuilder Tests");
return suite;
}
/**
* Create a new test case with the specified name.
*
* @param name the name
*/
public StrBuilderAppendInsertTest(String name) {
super(name);
}
//-----------------------------------------------------------------------
public void testAppendNewLine() {
StrBuilder sb = new StrBuilder("---");
sb.appendNewLine().append("+++");
assertEquals("---" + SystemUtils.LINE_SEPARATOR + "+++", sb.toString());
sb = new StrBuilder("---");
sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine();
assertEquals("---#" + SystemUtils.LINE_SEPARATOR, sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithNullText() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL");
assertEquals("", sb.toString());
sb.appendNull();
assertEquals("NULL", sb.toString());
sb.append((Object) null);
assertEquals("NULLNULL", sb.toString());
sb.append(FOO);
assertEquals("NULLNULLfoo", sb.toString());
sb.append((String) null);
assertEquals("NULLNULLfooNULL", sb.toString());
sb.append("");
assertEquals("NULLNULLfooNULL", sb.toString());
sb.append("bar");
assertEquals("NULLNULLfooNULLbar", sb.toString());
sb.append((StringBuffer) null);
assertEquals("NULLNULLfooNULLbarNULL", sb.toString());
sb.append(new StringBuffer("baz"));
assertEquals("NULLNULLfooNULLbarNULLbaz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_Object() {
StrBuilder sb = new StrBuilder();
sb.appendNull();
assertEquals("", sb.toString());
sb.append((Object) null);
assertEquals("", sb.toString());
sb.append(FOO);
assertEquals("foo", sb.toString());
sb.append((StringBuffer) null);
assertEquals("foo", sb.toString());
sb.append(new StringBuffer("baz"));
assertEquals("foobaz", sb.toString());
sb.append(new StrBuilder("yes"));
assertEquals("foobazyes", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_String() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((String) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append("foo");
assertEquals("foo", sb.toString());
sb.append("");
assertEquals("foo", sb.toString());
sb.append("bar");
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_String_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((String) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append("foo", 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append("bar", -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append("bar", 3, 0);
assertEquals("foo", sb.toString());
sb.append("abcbardef", 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StringBuffer() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StringBuffer) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StringBuffer("foo"));
assertEquals("foo", sb.toString());
sb.append(new StringBuffer(""));
assertEquals("foo", sb.toString());
sb.append(new StringBuffer("bar"));
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StringBuffer_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StringBuffer) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StringBuffer("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StringBuffer("bar"), -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append(new StringBuffer("bar"), 3, 0);
assertEquals("foo", sb.toString());
sb.append(new StringBuffer("abcbardef"), 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StrBuilder() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StrBuilder) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StrBuilder("foo"));
assertEquals("foo", sb.toString());
sb.append(new StrBuilder(""));
assertEquals("foo", sb.toString());
sb.append(new StrBuilder("bar"));
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StrBuilder_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StrBuilder) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StrBuilder("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StrBuilder("bar"), -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append(new StrBuilder("bar"), 3, 0);
assertEquals("foo", sb.toString());
sb.append(new StrBuilder("abcbardef"), 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_CharArray() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((char[]) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new char[0]);
assertEquals("", sb.toString());
sb.append(new char[]{'f', 'o', 'o'});
assertEquals("foo", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_CharArray_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((char[]) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new char[]{'f', 'o', 'o'}, 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new char[]{'b', 'a', 'r'}, -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append(new char[]{'b', 'a', 'r'}, 3, 0);
assertEquals("foo", sb.toString());
sb.append(new char[]{'a', 'b', 'c', 'b', 'a', 'r', 'd', 'e', 'f'}, 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_Primitive() {
StrBuilder sb = new StrBuilder();
sb.append(true);
assertEquals("true", sb.toString());
sb.append(false);
assertEquals("truefalse", sb.toString());
sb.append('!');
assertEquals("truefalse!", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_PrimitiveNumber() {
StrBuilder sb = new StrBuilder();
sb.append(0);
assertEquals("0", sb.toString());
sb.append(1L);
assertEquals("01", sb.toString());
sb.append(2.3f);
assertEquals("012.3", sb.toString());
sb.append(4.5d);
assertEquals("012.34.5", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendPadding() {
StrBuilder sb = new StrBuilder();
sb.append("foo");
assertEquals("foo", sb.toString());
sb.appendPadding(-1, '-');
assertEquals("foo", sb.toString());
sb.appendPadding(0, '-');
assertEquals("foo", sb.toString());
sb.appendPadding(1, '-');
assertEquals("foo-", sb.toString());
sb.appendPadding(16, '-');
assertEquals(20, sb.length());
// 12345678901234567890
assertEquals("foo-----------------", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadLeft() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadLeft("foo", -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 1, '-');
assertEquals("o", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 2, '-');
assertEquals("oo", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 3, '-');
assertEquals("foo", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 4, '-');
assertEquals("-foo", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("-------foo", sb.toString());
sb.clear();
sb.setNullText("null");
sb.appendFixedWidthPadLeft(null, 5, '-');
assertEquals("-null", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadLeft_int() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadLeft(123, -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 1, '-');
assertEquals("3", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 2, '-');
assertEquals("23", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 3, '-');
assertEquals("123", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 4, '-');
assertEquals("-123", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("-------123", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadRight() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadRight("foo", -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 1, '-');
assertEquals("f", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 2, '-');
assertEquals("fo", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 3, '-');
assertEquals("foo", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 4, '-');
assertEquals("foo-", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("foo-------", sb.toString());
sb.clear();
sb.setNullText("null");
sb.appendFixedWidthPadRight(null, 5, '-');
assertEquals("null-", sb.toString());
}
// See: http://issues.apache.org/jira/browse/LANG-299
public void testLang299() {
StrBuilder sb = new StrBuilder(1);
sb.appendFixedWidthPadRight("foo", 1, '-');
assertEquals("f", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadRight_int() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadRight(123, -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 1, '-');
assertEquals("1", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 2, '-');
assertEquals("12", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 3, '-');
assertEquals("123", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 4, '-');
assertEquals("123-", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("123-------", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparators_Array() {
StrBuilder sb = new StrBuilder();
sb.appendWithSeparators((Object[]) null, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[0], ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, ",");
assertEquals("foo,bar,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, null);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
assertEquals("foo,,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparators_Collection() {
StrBuilder sb = new StrBuilder();
sb.appendWithSeparators((Collection) null, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Collections.EMPTY_LIST, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), ",");
assertEquals("foo,bar,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), null);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ",");
assertEquals("foo,,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparators_Iterator() {
StrBuilder sb = new StrBuilder();
sb.appendWithSeparators((Iterator) null, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Collections.EMPTY_LIST.iterator(), ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), ",");
assertEquals("foo,bar,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), null);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}).iterator(), ",");
assertEquals("foo,,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparatorsWithNullText() {
StrBuilder sb = new StrBuilder();
sb.setNullText("null");
sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
assertEquals("foo,null,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ",");
assertEquals("foo,null,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testInsert() {
StrBuilder sb = new StrBuilder();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, FOO);
fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, FOO);
fail("insert(7, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (Object) null);
assertEquals("barbaz", sb.toString());
sb.insert(0, FOO);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, "foo");
fail("insert(-1, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, "foo");
fail("insert(7, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (String) null);
assertEquals("barbaz", sb.toString());
sb.insert(0, "foo");
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, new char[]{'f', 'o', 'o'});
fail("insert(-1, char[]) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, new char[]{'f', 'o', 'o'});
fail("insert(7, char[]) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (char[]) null);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[0]);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[]{'f', 'o', 'o'});
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
fail("insert(-1, char[], 3, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
fail("insert(7, char[], 3, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (char[]) null, 0, 0);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[0], 0, 0);
assertEquals("barbaz", sb.toString());
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3);
fail("insert(0, char[], -1, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3);
fail("insert(0, char[], 10, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1);
fail("insert(0, char[], 0, -1) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10);
fail("insert(0, char[], 0, 10) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 0);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, true);
fail("insert(-1, boolean) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, true);
fail("insert(7, boolean) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, true);
assertEquals("truebarbaz", sb.toString());
sb.insert(0, false);
assertEquals("falsetruebarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, '!');
fail("insert(-1, char) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, '!');
fail("insert(7, char) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, '!');
assertEquals("!barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 0);
fail("insert(-1, int) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 0);
fail("insert(7, int) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, '0');
assertEquals("0barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 1L);
fail("insert(-1, long) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 1L);
fail("insert(7, long) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, 1L);
assertEquals("1barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 2.3F);
fail("insert(-1, float) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 2.3F);
fail("insert(7, float) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, 2.3F);
assertEquals("2.3barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 4.5D);
fail("insert(-1, double) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 4.5D);
fail("insert(7, double) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, 4.5D);
assertEquals("4.5barbaz", sb.toString());
}
//-----------------------------------------------------------------------
public void testInsertWithNullText() {
StrBuilder sb = new StrBuilder();
sb.setNullText("null");
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, FOO);
fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, FOO);
fail("insert(7, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (Object) null);
assertEquals("nullbarbaz", sb.toString());
sb.insert(0, FOO);
assertEquals("foonullbarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, "foo");
fail("insert(-1, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, "foo");
fail("insert(7, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (String) null);
assertEquals("nullbarbaz", sb.toString());
sb.insert(0, "foo");
assertEquals("foonullbarbaz", sb.toString());
sb.insert(0, (char[]) null);
assertEquals("nullfoonullbarbaz", sb.toString());
sb.insert(0, (char[]) null, 0, 0);
assertEquals("nullnullfoonullbarbaz", sb.toString());
}
} | // You are a professional Java test case writer, please create a test case named `testLang299` for the issue `Lang-LANG-299`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-299
//
// ## Issue-Title:
// Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException
//
// ## Issue-Description:
//
// There's a bug in method appendFixedWidthPadRight of class StrBuilder:
//
//
// public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
//
// if (width > 0) {
//
// ensureCapacity(size + width);
//
// String str = (obj == null ? getNullText() : obj.toString());
//
// int strLen = str.length();
//
// if (strLen >= width)
//
//
// {
// ==> str.getChars(0, strLen, buffer, size); <==== BUG: it should be str.getChars(0, width, buffer, size);
// }
// else {
//
// int padLen = width - strLen;
//
// str.getChars(0, strLen, buffer, size);
//
// for (int i = 0; i < padLen; i++)
//
//
// {
// buffer[size + strLen + i] = padChar;
// }
// }
//
// size += width;
//
// }
//
// return this;
//
// }
//
//
// This is causing an ArrayIndexOutOfBoundsException, so this method is unusable when strLen > width.
//
//
// It's counterpart method appendFixedWidthPadLeft seems to be ok.
//
//
//
//
//
public void testLang299() {
| 603 | // See: http://issues.apache.org/jira/browse/LANG-299 | 59 | 599 | src/test/org/apache/commons/lang/text/StrBuilderAppendInsertTest.java | src/test | ```markdown
## Issue-ID: Lang-LANG-299
## Issue-Title:
Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException
## Issue-Description:
There's a bug in method appendFixedWidthPadRight of class StrBuilder:
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
int strLen = str.length();
if (strLen >= width)
{
==> str.getChars(0, strLen, buffer, size); <==== BUG: it should be str.getChars(0, width, buffer, size);
}
else {
int padLen = width - strLen;
str.getChars(0, strLen, buffer, size);
for (int i = 0; i < padLen; i++)
{
buffer[size + strLen + i] = padChar;
}
}
size += width;
}
return this;
}
This is causing an ArrayIndexOutOfBoundsException, so this method is unusable when strLen > width.
It's counterpart method appendFixedWidthPadLeft seems to be ok.
```
You are a professional Java test case writer, please create a test case named `testLang299` for the issue `Lang-LANG-299`, utilizing the provided issue report information and the following function signature.
```java
public void testLang299() {
```
| 599 | [
"org.apache.commons.lang.text.StrBuilder"
] | 53430836691699fecf20854c46afee75a82c1a5f5b0c089ac8697fea66eba94b | public void testLang299() | // You are a professional Java test case writer, please create a test case named `testLang299` for the issue `Lang-LANG-299`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-299
//
// ## Issue-Title:
// Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException
//
// ## Issue-Description:
//
// There's a bug in method appendFixedWidthPadRight of class StrBuilder:
//
//
// public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
//
// if (width > 0) {
//
// ensureCapacity(size + width);
//
// String str = (obj == null ? getNullText() : obj.toString());
//
// int strLen = str.length();
//
// if (strLen >= width)
//
//
// {
// ==> str.getChars(0, strLen, buffer, size); <==== BUG: it should be str.getChars(0, width, buffer, size);
// }
// else {
//
// int padLen = width - strLen;
//
// str.getChars(0, strLen, buffer, size);
//
// for (int i = 0; i < padLen; i++)
//
//
// {
// buffer[size + strLen + i] = padChar;
// }
// }
//
// size += width;
//
// }
//
// return this;
//
// }
//
//
// This is causing an ArrayIndexOutOfBoundsException, so this method is unusable when strLen > width.
//
//
// It's counterpart method appendFixedWidthPadLeft seems to be ok.
//
//
//
//
//
| 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.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import org.apache.commons.lang.SystemUtils;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Unit tests for {@link org.apache.commons.lang.text.StrBuilder}.
*
* @version $Id$
*/
public class StrBuilderAppendInsertTest extends TestCase {
/** Test subclass of Object, with a toString method. */
private static Object FOO = new Object() {
public String toString() {
return "foo";
}
};
/**
* Main method.
*
* @param args command line arguments, ignored
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* 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(StrBuilderAppendInsertTest.class);
suite.setName("StrBuilder Tests");
return suite;
}
/**
* Create a new test case with the specified name.
*
* @param name the name
*/
public StrBuilderAppendInsertTest(String name) {
super(name);
}
//-----------------------------------------------------------------------
public void testAppendNewLine() {
StrBuilder sb = new StrBuilder("---");
sb.appendNewLine().append("+++");
assertEquals("---" + SystemUtils.LINE_SEPARATOR + "+++", sb.toString());
sb = new StrBuilder("---");
sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine();
assertEquals("---#" + SystemUtils.LINE_SEPARATOR, sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithNullText() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL");
assertEquals("", sb.toString());
sb.appendNull();
assertEquals("NULL", sb.toString());
sb.append((Object) null);
assertEquals("NULLNULL", sb.toString());
sb.append(FOO);
assertEquals("NULLNULLfoo", sb.toString());
sb.append((String) null);
assertEquals("NULLNULLfooNULL", sb.toString());
sb.append("");
assertEquals("NULLNULLfooNULL", sb.toString());
sb.append("bar");
assertEquals("NULLNULLfooNULLbar", sb.toString());
sb.append((StringBuffer) null);
assertEquals("NULLNULLfooNULLbarNULL", sb.toString());
sb.append(new StringBuffer("baz"));
assertEquals("NULLNULLfooNULLbarNULLbaz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_Object() {
StrBuilder sb = new StrBuilder();
sb.appendNull();
assertEquals("", sb.toString());
sb.append((Object) null);
assertEquals("", sb.toString());
sb.append(FOO);
assertEquals("foo", sb.toString());
sb.append((StringBuffer) null);
assertEquals("foo", sb.toString());
sb.append(new StringBuffer("baz"));
assertEquals("foobaz", sb.toString());
sb.append(new StrBuilder("yes"));
assertEquals("foobazyes", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_String() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((String) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append("foo");
assertEquals("foo", sb.toString());
sb.append("");
assertEquals("foo", sb.toString());
sb.append("bar");
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_String_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((String) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append("foo", 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append("bar", -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append("bar", 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append("bar", 3, 0);
assertEquals("foo", sb.toString());
sb.append("abcbardef", 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StringBuffer() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StringBuffer) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StringBuffer("foo"));
assertEquals("foo", sb.toString());
sb.append(new StringBuffer(""));
assertEquals("foo", sb.toString());
sb.append(new StringBuffer("bar"));
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StringBuffer_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StringBuffer) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StringBuffer("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StringBuffer("bar"), -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StringBuffer("bar"), 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append(new StringBuffer("bar"), 3, 0);
assertEquals("foo", sb.toString());
sb.append(new StringBuffer("abcbardef"), 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StrBuilder() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StrBuilder) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StrBuilder("foo"));
assertEquals("foo", sb.toString());
sb.append(new StrBuilder(""));
assertEquals("foo", sb.toString());
sb.append(new StrBuilder("bar"));
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_StrBuilder_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((StrBuilder) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new StrBuilder("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StrBuilder("bar"), -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new StrBuilder("bar"), 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append(new StrBuilder("bar"), 3, 0);
assertEquals("foo", sb.toString());
sb.append(new StrBuilder("abcbardef"), 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_CharArray() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((char[]) null);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new char[0]);
assertEquals("", sb.toString());
sb.append(new char[]{'f', 'o', 'o'});
assertEquals("foo", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_CharArray_int_int() {
StrBuilder sb = new StrBuilder();
sb.setNullText("NULL").append((char[]) null, 0, 1);
assertEquals("NULL", sb.toString());
sb = new StrBuilder();
sb.append(new char[]{'f', 'o', 'o'}, 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new char[]{'b', 'a', 'r'}, -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.append(new char[]{'b', 'a', 'r'}, 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.append(new char[]{'b', 'a', 'r'}, 3, 0);
assertEquals("foo", sb.toString());
sb.append(new char[]{'a', 'b', 'c', 'b', 'a', 'r', 'd', 'e', 'f'}, 3, 3);
assertEquals("foobar", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_Primitive() {
StrBuilder sb = new StrBuilder();
sb.append(true);
assertEquals("true", sb.toString());
sb.append(false);
assertEquals("truefalse", sb.toString());
sb.append('!');
assertEquals("truefalse!", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppend_PrimitiveNumber() {
StrBuilder sb = new StrBuilder();
sb.append(0);
assertEquals("0", sb.toString());
sb.append(1L);
assertEquals("01", sb.toString());
sb.append(2.3f);
assertEquals("012.3", sb.toString());
sb.append(4.5d);
assertEquals("012.34.5", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendPadding() {
StrBuilder sb = new StrBuilder();
sb.append("foo");
assertEquals("foo", sb.toString());
sb.appendPadding(-1, '-');
assertEquals("foo", sb.toString());
sb.appendPadding(0, '-');
assertEquals("foo", sb.toString());
sb.appendPadding(1, '-');
assertEquals("foo-", sb.toString());
sb.appendPadding(16, '-');
assertEquals(20, sb.length());
// 12345678901234567890
assertEquals("foo-----------------", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadLeft() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadLeft("foo", -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 1, '-');
assertEquals("o", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 2, '-');
assertEquals("oo", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 3, '-');
assertEquals("foo", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 4, '-');
assertEquals("-foo", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft("foo", 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("-------foo", sb.toString());
sb.clear();
sb.setNullText("null");
sb.appendFixedWidthPadLeft(null, 5, '-');
assertEquals("-null", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadLeft_int() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadLeft(123, -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 1, '-');
assertEquals("3", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 2, '-');
assertEquals("23", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 3, '-');
assertEquals("123", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 4, '-');
assertEquals("-123", sb.toString());
sb.clear();
sb.appendFixedWidthPadLeft(123, 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("-------123", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadRight() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadRight("foo", -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 1, '-');
assertEquals("f", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 2, '-');
assertEquals("fo", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 3, '-');
assertEquals("foo", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 4, '-');
assertEquals("foo-", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight("foo", 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("foo-------", sb.toString());
sb.clear();
sb.setNullText("null");
sb.appendFixedWidthPadRight(null, 5, '-');
assertEquals("null-", sb.toString());
}
// See: http://issues.apache.org/jira/browse/LANG-299
public void testLang299() {
StrBuilder sb = new StrBuilder(1);
sb.appendFixedWidthPadRight("foo", 1, '-');
assertEquals("f", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendFixedWidthPadRight_int() {
StrBuilder sb = new StrBuilder();
sb.appendFixedWidthPadRight(123, -1, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 0, '-');
assertEquals("", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 1, '-');
assertEquals("1", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 2, '-');
assertEquals("12", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 3, '-');
assertEquals("123", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 4, '-');
assertEquals("123-", sb.toString());
sb.clear();
sb.appendFixedWidthPadRight(123, 10, '-');
assertEquals(10, sb.length());
// 1234567890
assertEquals("123-------", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparators_Array() {
StrBuilder sb = new StrBuilder();
sb.appendWithSeparators((Object[]) null, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[0], ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, ",");
assertEquals("foo,bar,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, null);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
assertEquals("foo,,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparators_Collection() {
StrBuilder sb = new StrBuilder();
sb.appendWithSeparators((Collection) null, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Collections.EMPTY_LIST, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), ",");
assertEquals("foo,bar,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), null);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ",");
assertEquals("foo,,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparators_Iterator() {
StrBuilder sb = new StrBuilder();
sb.appendWithSeparators((Iterator) null, ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Collections.EMPTY_LIST.iterator(), ",");
assertEquals("", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), ",");
assertEquals("foo,bar,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), null);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}).iterator(), ",");
assertEquals("foo,,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testAppendWithSeparatorsWithNullText() {
StrBuilder sb = new StrBuilder();
sb.setNullText("null");
sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
assertEquals("foo,null,baz", sb.toString());
sb.clear();
sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ",");
assertEquals("foo,null,baz", sb.toString());
}
//-----------------------------------------------------------------------
public void testInsert() {
StrBuilder sb = new StrBuilder();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, FOO);
fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, FOO);
fail("insert(7, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (Object) null);
assertEquals("barbaz", sb.toString());
sb.insert(0, FOO);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, "foo");
fail("insert(-1, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, "foo");
fail("insert(7, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (String) null);
assertEquals("barbaz", sb.toString());
sb.insert(0, "foo");
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, new char[]{'f', 'o', 'o'});
fail("insert(-1, char[]) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, new char[]{'f', 'o', 'o'});
fail("insert(7, char[]) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (char[]) null);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[0]);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[]{'f', 'o', 'o'});
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
fail("insert(-1, char[], 3, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
fail("insert(7, char[], 3, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (char[]) null, 0, 0);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[0], 0, 0);
assertEquals("barbaz", sb.toString());
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3);
fail("insert(0, char[], -1, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3);
fail("insert(0, char[], 10, 3) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1);
fail("insert(0, char[], 0, -1) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10);
fail("insert(0, char[], 0, 10) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 0);
assertEquals("barbaz", sb.toString());
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
assertEquals("foobarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, true);
fail("insert(-1, boolean) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, true);
fail("insert(7, boolean) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, true);
assertEquals("truebarbaz", sb.toString());
sb.insert(0, false);
assertEquals("falsetruebarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, '!');
fail("insert(-1, char) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, '!');
fail("insert(7, char) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, '!');
assertEquals("!barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 0);
fail("insert(-1, int) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 0);
fail("insert(7, int) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, '0');
assertEquals("0barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 1L);
fail("insert(-1, long) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 1L);
fail("insert(7, long) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, 1L);
assertEquals("1barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 2.3F);
fail("insert(-1, float) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 2.3F);
fail("insert(7, float) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, 2.3F);
assertEquals("2.3barbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 4.5D);
fail("insert(-1, double) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, 4.5D);
fail("insert(7, double) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, 4.5D);
assertEquals("4.5barbaz", sb.toString());
}
//-----------------------------------------------------------------------
public void testInsertWithNullText() {
StrBuilder sb = new StrBuilder();
sb.setNullText("null");
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, FOO);
fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, FOO);
fail("insert(7, Object) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (Object) null);
assertEquals("nullbarbaz", sb.toString());
sb.insert(0, FOO);
assertEquals("foonullbarbaz", sb.toString());
sb.clear();
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, "foo");
fail("insert(-1, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
try {
sb.insert(7, "foo");
fail("insert(7, String) expected StringIndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// expected
}
sb.insert(0, (String) null);
assertEquals("nullbarbaz", sb.toString());
sb.insert(0, "foo");
assertEquals("foonullbarbaz", sb.toString());
sb.insert(0, (char[]) null);
assertEquals("nullfoonullbarbaz", sb.toString());
sb.insert(0, (char[]) null, 0, 0);
assertEquals("nullnullfoonullbarbaz", sb.toString());
}
} |
|
@Test
public void littleEndianWithOverflow() throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
87, // 01010111
45, // 00101101
66, // 01000010
15, // 00001111
90, // 01011010
29, // 00011101
88, // 01011000
61, // 00111101
33, // 00100001
74 // 01001010
});
BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE_ENDIAN);
assertEquals(23, // 10111
bin.readBits(5));
assertEquals(714595605644185962l, // 0001-00111101-01011000-00011101-01011010-00001111-01000010-00101101-010
bin.readBits(63));
assertEquals(1186, // 01001010-0010
bin.readBits(12));
assertEquals(-1 , bin.readBits(1));
} | org.apache.commons.compress.utils.BitInputStreamTest::littleEndianWithOverflow | src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java | 145 | src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java | littleEndianWithOverflow | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.compress.utils;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import org.junit.Test;
public class BitInputStreamTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowReadingOfANegativeAmountOfBits() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
bis.readBits(-1);
bis.close();
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowReadingOfMoreThan63BitsAtATime() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
bis.readBits(64);
bis.close();
}
@Test
public void testReading24BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x000140f8, bis.readBits(24));
bis.close();
}
@Test
public void testReading24BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
assertEquals(0x00f84001, bis.readBits(24));
bis.close();
}
@Test
public void testReading17BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x000140f8, bis.readBits(17));
bis.close();
}
@Test
public void testReading17BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
// 1-11110000-10000000
assertEquals(0x0001f080, bis.readBits(17));
bis.close();
}
@Test
public void testReading30BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x2f0140f8, bis.readBits(30));
bis.close();
}
@Test
public void testReading30BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
// 111110-00010000-00000000-01001011
assertEquals(0x3e10004b, bis.readBits(30));
bis.close();
}
@Test
public void testReading31BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x2f0140f8, bis.readBits(31));
bis.close();
}
@Test
public void testReading31BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
// 1111100-00100000-00000000-10010111
assertEquals(0x7c200097, bis.readBits(31));
bis.close();
}
@Test
public void testClearBitCache() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x08, bis.readBits(4));
bis.clearBitCache();
assertEquals(0, bis.readBits(1));
bis.close();
}
@Test
public void testEOF() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x2f0140f8, bis.readBits(30));
assertEquals(-1, bis.readBits(3));
bis.close();
}
/**
* @see "https://issues.apache.org/jira/browse/COMPRESS-363"
*/
@Test
public void littleEndianWithOverflow() throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
87, // 01010111
45, // 00101101
66, // 01000010
15, // 00001111
90, // 01011010
29, // 00011101
88, // 01011000
61, // 00111101
33, // 00100001
74 // 01001010
});
BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE_ENDIAN);
assertEquals(23, // 10111
bin.readBits(5));
assertEquals(714595605644185962l, // 0001-00111101-01011000-00011101-01011010-00001111-01000010-00101101-010
bin.readBits(63));
assertEquals(1186, // 01001010-0010
bin.readBits(12));
assertEquals(-1 , bin.readBits(1));
}
@Test
public void bigEndianWithOverflow() throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
87, // 01010111
45, // 00101101
66, // 01000010
15, // 00001111
90, // 01011010
29, // 00011101
88, // 01011000
61, // 00111101
33, // 00100001
74 // 01001010
});
BitInputStream bin = new BitInputStream(in, ByteOrder.BIG_ENDIAN);
assertEquals(10, // 01010
bin.readBits(5));
assertEquals(8274274654740644818l, //111-00101101-01000010-00001111-01011010-00011101-01011000-00111101-0010
bin.readBits(63));
assertEquals(330, // 0001-01001010
bin.readBits(12));
assertEquals(-1 , bin.readBits(1));
}
private ByteArrayInputStream getStream() {
return new ByteArrayInputStream(new byte[] {
(byte) 0xF8, // 11111000
0x40, // 01000000
0x01, // 00000001
0x2F }); // 00101111
}
} | // You are a professional Java test case writer, please create a test case named `littleEndianWithOverflow` for the issue `Compress-COMPRESS-363`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-363
//
// ## Issue-Title:
// Overflow in BitInputStream
//
// ## Issue-Description:
//
// in Class BitInputStream.java(\src\main\java\org\apache\commons\compress\utils),
//
// funcion:
//
//
// public long readBits(final int count) throws IOException {
//
// if (count < 0 || count > MAXIMUM\_CACHE\_SIZE)
//
//
// {
// throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM\_CACHE\_SIZE);
// }
// while (bitsCachedSize < count) {
//
// final long nextByte = in.read();
//
// if (nextByte < 0)
//
//
// {
// return nextByte;
// }
// if (byteOrder == ByteOrder.LITTLE\_ENDIAN)
//
//
// {
// bitsCached |= (nextByte << bitsCachedSize);
// }
// else
//
//
// {
// bitsCached <<= 8;
// bitsCached |= nextByte;
// }
// bitsCachedSize += 8;
//
// }
//
//
// final long bitsOut;
//
// if (byteOrder == ByteOrder.LITTLE\_ENDIAN)
//
//
// {
// bitsOut = (bitsCached & MASKS[count]);
// bitsCached >>>= count;
// }
// else
//
//
// {
// bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
// }
// bitsCachedSize -= count;
//
// return bitsOut;
//
// }
//
//
// I think here "bitsCached |= (nextByte << bitsCachedSize);" will overflow in some cases. for example, below is a test case:
//
//
// public static void test() {
//
//
// ByteArrayInputStream in = new ByteArrayInputStream(new byte[]
//
//
// {87, 45, 66, 15,
// 90, 29, 88, 61, 33, 74}
// );
//
// BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE\_ENDIAN);
//
// try
//
//
// {
// long ret = bin.readBits(5);
// ret = bin.readBits(63);
// ret = bin.readBits(12);
// }
// catch (Exception e)
//
//
// {
// e.printStackTrace();
// }
// }
//
//
// overflow occur in "bin.readBits(63);" , so ,result in wrong result from "bin.readBits(12);"
//
//
//
//
//
@Test
public void littleEndianWithOverflow() throws Exception {
| 145 | /**
* @see "https://issues.apache.org/jira/browse/COMPRESS-363"
*/ | 40 | 123 | src/test/java/org/apache/commons/compress/utils/BitInputStreamTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-363
## Issue-Title:
Overflow in BitInputStream
## Issue-Description:
in Class BitInputStream.java(\src\main\java\org\apache\commons\compress\utils),
funcion:
public long readBits(final int count) throws IOException {
if (count < 0 || count > MAXIMUM\_CACHE\_SIZE)
{
throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM\_CACHE\_SIZE);
}
while (bitsCachedSize < count) {
final long nextByte = in.read();
if (nextByte < 0)
{
return nextByte;
}
if (byteOrder == ByteOrder.LITTLE\_ENDIAN)
{
bitsCached |= (nextByte << bitsCachedSize);
}
else
{
bitsCached <<= 8;
bitsCached |= nextByte;
}
bitsCachedSize += 8;
}
final long bitsOut;
if (byteOrder == ByteOrder.LITTLE\_ENDIAN)
{
bitsOut = (bitsCached & MASKS[count]);
bitsCached >>>= count;
}
else
{
bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
}
bitsCachedSize -= count;
return bitsOut;
}
I think here "bitsCached |= (nextByte << bitsCachedSize);" will overflow in some cases. for example, below is a test case:
public static void test() {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[]
{87, 45, 66, 15,
90, 29, 88, 61, 33, 74}
);
BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE\_ENDIAN);
try
{
long ret = bin.readBits(5);
ret = bin.readBits(63);
ret = bin.readBits(12);
}
catch (Exception e)
{
e.printStackTrace();
}
}
overflow occur in "bin.readBits(63);" , so ,result in wrong result from "bin.readBits(12);"
```
You are a professional Java test case writer, please create a test case named `littleEndianWithOverflow` for the issue `Compress-COMPRESS-363`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void littleEndianWithOverflow() throws Exception {
```
| 123 | [
"org.apache.commons.compress.utils.BitInputStream"
] | 544fd993b5e67f8ab2fafb85e4cd638b97aa5bf78636824472999d6382284a3a | @Test
public void littleEndianWithOverflow() throws Exception | // You are a professional Java test case writer, please create a test case named `littleEndianWithOverflow` for the issue `Compress-COMPRESS-363`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-363
//
// ## Issue-Title:
// Overflow in BitInputStream
//
// ## Issue-Description:
//
// in Class BitInputStream.java(\src\main\java\org\apache\commons\compress\utils),
//
// funcion:
//
//
// public long readBits(final int count) throws IOException {
//
// if (count < 0 || count > MAXIMUM\_CACHE\_SIZE)
//
//
// {
// throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM\_CACHE\_SIZE);
// }
// while (bitsCachedSize < count) {
//
// final long nextByte = in.read();
//
// if (nextByte < 0)
//
//
// {
// return nextByte;
// }
// if (byteOrder == ByteOrder.LITTLE\_ENDIAN)
//
//
// {
// bitsCached |= (nextByte << bitsCachedSize);
// }
// else
//
//
// {
// bitsCached <<= 8;
// bitsCached |= nextByte;
// }
// bitsCachedSize += 8;
//
// }
//
//
// final long bitsOut;
//
// if (byteOrder == ByteOrder.LITTLE\_ENDIAN)
//
//
// {
// bitsOut = (bitsCached & MASKS[count]);
// bitsCached >>>= count;
// }
// else
//
//
// {
// bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
// }
// bitsCachedSize -= count;
//
// return bitsOut;
//
// }
//
//
// I think here "bitsCached |= (nextByte << bitsCachedSize);" will overflow in some cases. for example, below is a test case:
//
//
// public static void test() {
//
//
// ByteArrayInputStream in = new ByteArrayInputStream(new byte[]
//
//
// {87, 45, 66, 15,
// 90, 29, 88, 61, 33, 74}
// );
//
// BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE\_ENDIAN);
//
// try
//
//
// {
// long ret = bin.readBits(5);
// ret = bin.readBits(63);
// ret = bin.readBits(12);
// }
// catch (Exception e)
//
//
// {
// e.printStackTrace();
// }
// }
//
//
// overflow occur in "bin.readBits(63);" , so ,result in wrong result from "bin.readBits(12);"
//
//
//
//
//
| Compress | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.compress.utils;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import org.junit.Test;
public class BitInputStreamTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowReadingOfANegativeAmountOfBits() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
bis.readBits(-1);
bis.close();
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowReadingOfMoreThan63BitsAtATime() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
bis.readBits(64);
bis.close();
}
@Test
public void testReading24BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x000140f8, bis.readBits(24));
bis.close();
}
@Test
public void testReading24BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
assertEquals(0x00f84001, bis.readBits(24));
bis.close();
}
@Test
public void testReading17BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x000140f8, bis.readBits(17));
bis.close();
}
@Test
public void testReading17BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
// 1-11110000-10000000
assertEquals(0x0001f080, bis.readBits(17));
bis.close();
}
@Test
public void testReading30BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x2f0140f8, bis.readBits(30));
bis.close();
}
@Test
public void testReading30BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
// 111110-00010000-00000000-01001011
assertEquals(0x3e10004b, bis.readBits(30));
bis.close();
}
@Test
public void testReading31BitsInLittleEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x2f0140f8, bis.readBits(31));
bis.close();
}
@Test
public void testReading31BitsInBigEndian() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.BIG_ENDIAN);
// 1111100-00100000-00000000-10010111
assertEquals(0x7c200097, bis.readBits(31));
bis.close();
}
@Test
public void testClearBitCache() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x08, bis.readBits(4));
bis.clearBitCache();
assertEquals(0, bis.readBits(1));
bis.close();
}
@Test
public void testEOF() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x2f0140f8, bis.readBits(30));
assertEquals(-1, bis.readBits(3));
bis.close();
}
/**
* @see "https://issues.apache.org/jira/browse/COMPRESS-363"
*/
@Test
public void littleEndianWithOverflow() throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
87, // 01010111
45, // 00101101
66, // 01000010
15, // 00001111
90, // 01011010
29, // 00011101
88, // 01011000
61, // 00111101
33, // 00100001
74 // 01001010
});
BitInputStream bin = new BitInputStream(in, ByteOrder.LITTLE_ENDIAN);
assertEquals(23, // 10111
bin.readBits(5));
assertEquals(714595605644185962l, // 0001-00111101-01011000-00011101-01011010-00001111-01000010-00101101-010
bin.readBits(63));
assertEquals(1186, // 01001010-0010
bin.readBits(12));
assertEquals(-1 , bin.readBits(1));
}
@Test
public void bigEndianWithOverflow() throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {
87, // 01010111
45, // 00101101
66, // 01000010
15, // 00001111
90, // 01011010
29, // 00011101
88, // 01011000
61, // 00111101
33, // 00100001
74 // 01001010
});
BitInputStream bin = new BitInputStream(in, ByteOrder.BIG_ENDIAN);
assertEquals(10, // 01010
bin.readBits(5));
assertEquals(8274274654740644818l, //111-00101101-01000010-00001111-01011010-00011101-01011000-00111101-0010
bin.readBits(63));
assertEquals(330, // 0001-01001010
bin.readBits(12));
assertEquals(-1 , bin.readBits(1));
}
private ByteArrayInputStream getStream() {
return new ByteArrayInputStream(new byte[] {
(byte) 0xF8, // 11111000
0x40, // 01000000
0x01, // 00000001
0x2F }); // 00101111
}
} |
|
public void testIssue1255() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
Foo mo = new Foo();
mo.bar1 = new Bar();
mo.bar2 = mo.bar1;
String json = mapper.writeValueAsString(mo);
Foo result = mapper.readValue(json, Foo.class);
assertNotNull(result);
} | com.fasterxml.jackson.databind.objectid.AlwaysAsReferenceFirstTest::testIssue1255 | src/test/java/com/fasterxml/jackson/databind/objectid/AlwaysAsReferenceFirstTest.java | 33 | src/test/java/com/fasterxml/jackson/databind/objectid/AlwaysAsReferenceFirstTest.java | testIssue1255 | package com.fasterxml.jackson.databind.objectid;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class AlwaysAsReferenceFirstTest extends BaseMapTest
{
@JsonPropertyOrder({ "bar1", "bar2" })
static class Foo {
@JsonIdentityReference(alwaysAsId = true)
public Bar bar1;
@JsonIdentityReference
public Bar bar2;
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
static class Bar {
public int value = 3;
}
public void testIssue1255() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
Foo mo = new Foo();
mo.bar1 = new Bar();
mo.bar2 = mo.bar1;
String json = mapper.writeValueAsString(mo);
Foo result = mapper.readValue(json, Foo.class);
assertNotNull(result);
}
} | // You are a professional Java test case writer, please create a test case named `testIssue1255` for the issue `JacksonDatabind-1255`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1255
//
// ## Issue-Title:
// JsonIdentityInfo incorrectly serializing forward references
//
// ## Issue-Description:
// I wrote this small test program to demonstrate the issue:
//
//
//
// ```
// import com.fasterxml.jackson.annotation.JsonIdentityInfo;
// import com.fasterxml.jackson.annotation.JsonIdentityReference;
// import com.fasterxml.jackson.annotation.ObjectIdGenerators;
// import com.fasterxml.jackson.databind.ObjectMapper;
//
// public class ObjectIdTest {
//
// public static class Foo {
//
// @JsonIdentityReference(alwaysAsId = true)
// public Bar bar1;
//
// @JsonIdentityReference()
// public Bar bar2;
// }
//
// @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
// public static class Bar {
//
// }
//
// public static void main(String[] args) throws Exception {
// ObjectMapper mapper = new ObjectMapper();
//
// // create structure to serialize
// Foo mo = new Foo();
// mo.bar1 = new Bar();
// mo.bar2 = mo.bar1;
//
// // serialize it
// System.out.println(mapper.writeValueAsString(mo));
// }
//
// }
// ```
//
// When executing this test program in the latest version (2.7.4), the output will be `{"bar1":1,"bar2":{"@id":2}}` - the second field will be written with a new id even though both fields reference the same object. Because of this, writing forward references is essentially impossible.
//
//
// The issue seems to be the fact that BeanSerializerBase will always call WritableObjectId.generateId if the referenced object has not been written in plain format yet (<https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/BeanSerializerBase.java#L600>). This will also happen if an id has been generated before.
//
// It might also be smarter to only generate a new id in WritableObjectId.generateId if that hasn't happened before; as that method doesn't have a javadoc I can't tell how it is supposed to work.
//
//
//
//
public void testIssue1255() throws Exception {
| 33 | 49 | 22 | src/test/java/com/fasterxml/jackson/databind/objectid/AlwaysAsReferenceFirstTest.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1255
## Issue-Title:
JsonIdentityInfo incorrectly serializing forward references
## Issue-Description:
I wrote this small test program to demonstrate the issue:
```
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectIdTest {
public static class Foo {
@JsonIdentityReference(alwaysAsId = true)
public Bar bar1;
@JsonIdentityReference()
public Bar bar2;
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
public static class Bar {
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// create structure to serialize
Foo mo = new Foo();
mo.bar1 = new Bar();
mo.bar2 = mo.bar1;
// serialize it
System.out.println(mapper.writeValueAsString(mo));
}
}
```
When executing this test program in the latest version (2.7.4), the output will be `{"bar1":1,"bar2":{"@id":2}}` - the second field will be written with a new id even though both fields reference the same object. Because of this, writing forward references is essentially impossible.
The issue seems to be the fact that BeanSerializerBase will always call WritableObjectId.generateId if the referenced object has not been written in plain format yet (<https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/BeanSerializerBase.java#L600>). This will also happen if an id has been generated before.
It might also be smarter to only generate a new id in WritableObjectId.generateId if that hasn't happened before; as that method doesn't have a javadoc I can't tell how it is supposed to work.
```
You are a professional Java test case writer, please create a test case named `testIssue1255` for the issue `JacksonDatabind-1255`, utilizing the provided issue report information and the following function signature.
```java
public void testIssue1255() throws Exception {
```
| 22 | [
"com.fasterxml.jackson.databind.ser.impl.WritableObjectId"
] | 5563d77ac2a1332f7942e590097a397f48539727b187ef18404b94b27b3fc6c0 | public void testIssue1255() throws Exception
| // You are a professional Java test case writer, please create a test case named `testIssue1255` for the issue `JacksonDatabind-1255`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1255
//
// ## Issue-Title:
// JsonIdentityInfo incorrectly serializing forward references
//
// ## Issue-Description:
// I wrote this small test program to demonstrate the issue:
//
//
//
// ```
// import com.fasterxml.jackson.annotation.JsonIdentityInfo;
// import com.fasterxml.jackson.annotation.JsonIdentityReference;
// import com.fasterxml.jackson.annotation.ObjectIdGenerators;
// import com.fasterxml.jackson.databind.ObjectMapper;
//
// public class ObjectIdTest {
//
// public static class Foo {
//
// @JsonIdentityReference(alwaysAsId = true)
// public Bar bar1;
//
// @JsonIdentityReference()
// public Bar bar2;
// }
//
// @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
// public static class Bar {
//
// }
//
// public static void main(String[] args) throws Exception {
// ObjectMapper mapper = new ObjectMapper();
//
// // create structure to serialize
// Foo mo = new Foo();
// mo.bar1 = new Bar();
// mo.bar2 = mo.bar1;
//
// // serialize it
// System.out.println(mapper.writeValueAsString(mo));
// }
//
// }
// ```
//
// When executing this test program in the latest version (2.7.4), the output will be `{"bar1":1,"bar2":{"@id":2}}` - the second field will be written with a new id even though both fields reference the same object. Because of this, writing forward references is essentially impossible.
//
//
// The issue seems to be the fact that BeanSerializerBase will always call WritableObjectId.generateId if the referenced object has not been written in plain format yet (<https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com/fasterxml/jackson/databind/ser/std/BeanSerializerBase.java#L600>). This will also happen if an id has been generated before.
//
// It might also be smarter to only generate a new id in WritableObjectId.generateId if that hasn't happened before; as that method doesn't have a javadoc I can't tell how it is supposed to work.
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.objectid;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class AlwaysAsReferenceFirstTest extends BaseMapTest
{
@JsonPropertyOrder({ "bar1", "bar2" })
static class Foo {
@JsonIdentityReference(alwaysAsId = true)
public Bar bar1;
@JsonIdentityReference
public Bar bar2;
}
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
static class Bar {
public int value = 3;
}
public void testIssue1255() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
Foo mo = new Foo();
mo.bar1 = new Bar();
mo.bar2 = mo.bar1;
String json = mapper.writeValueAsString(mo);
Foo result = mapper.readValue(json, Foo.class);
assertNotNull(result);
}
} |
||
public void testValidDefine() {
assertTrue(testValidDefineValue("1"));
assertTrue(testValidDefineValue("-3"));
assertTrue(testValidDefineValue("true"));
assertTrue(testValidDefineValue("false"));
assertTrue(testValidDefineValue("'foo'"));
assertFalse(testValidDefineValue("x"));
assertFalse(testValidDefineValue("null"));
assertFalse(testValidDefineValue("undefined"));
assertFalse(testValidDefineValue("NaN"));
assertTrue(testValidDefineValue("!true"));
assertTrue(testValidDefineValue("-true"));
assertTrue(testValidDefineValue("1 & 8"));
assertTrue(testValidDefineValue("1 + 8"));
assertTrue(testValidDefineValue("'a' + 'b'"));
assertFalse(testValidDefineValue("1 & foo"));
} | com.google.javascript.jscomp.NodeUtilTest::testValidDefine | test/com/google/javascript/jscomp/NodeUtilTest.java | 1,089 | test/com/google/javascript/jscomp/NodeUtilTest.java | testValidDefine | /*
* 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;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.TernaryValue;
import junit.framework.TestCase;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class NodeUtilTest extends TestCase {
private static Node parse(String js) {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode(js);
assertEquals(0, compiler.getErrorCount());
return n;
}
static Node getNode(String js) {
Node root = parse("var a=(" + js + ");");
Node expr = root.getFirstChild();
Node var = expr.getFirstChild();
return var.getFirstChild();
}
public void testIsLiteralOrConstValue() {
assertLiteralAndImmutable(getNode("10"));
assertLiteralAndImmutable(getNode("-10"));
assertLiteralButNotImmutable(getNode("[10, 20]"));
assertLiteralButNotImmutable(getNode("{'a': 20}"));
assertLiteralButNotImmutable(getNode("[10, , 1.0, [undefined], 'a']"));
assertLiteralButNotImmutable(getNode("/abc/"));
assertLiteralAndImmutable(getNode("\"string\""));
assertLiteralAndImmutable(getNode("'aaa'"));
assertLiteralAndImmutable(getNode("null"));
assertLiteralAndImmutable(getNode("undefined"));
assertLiteralAndImmutable(getNode("void 0"));
assertNotLiteral(getNode("abc"));
assertNotLiteral(getNode("[10, foo(), 20]"));
assertNotLiteral(getNode("foo()"));
assertNotLiteral(getNode("c + d"));
assertNotLiteral(getNode("{'a': foo()}"));
assertNotLiteral(getNode("void foo()"));
}
public void assertLiteralAndImmutable(Node n) {
assertTrue(NodeUtil.isLiteralValue(n, true));
assertTrue(NodeUtil.isLiteralValue(n, false));
assertTrue(NodeUtil.isImmutableValue(n));
}
public void assertLiteralButNotImmutable(Node n) {
assertTrue(NodeUtil.isLiteralValue(n, true));
assertTrue(NodeUtil.isLiteralValue(n, false));
assertFalse(NodeUtil.isImmutableValue(n));
}
public void assertNotLiteral(Node n) {
assertFalse(NodeUtil.isLiteralValue(n, true));
assertFalse(NodeUtil.isLiteralValue(n, false));
assertFalse(NodeUtil.isImmutableValue(n));
}
public void testGetBooleanValue() {
assertBooleanTrue("true");
assertBooleanTrue("10");
assertBooleanTrue("'0'");
assertBooleanTrue("/a/");
assertBooleanTrue("{}");
assertBooleanTrue("[]");
assertBooleanFalse("false");
assertBooleanFalse("null");
assertBooleanFalse("0");
assertBooleanFalse("''");
assertBooleanFalse("undefined");
assertBooleanFalse("void 0");
assertBooleanFalse("void foo()");
assertBooleanUnknown("b");
assertBooleanUnknown("-'0.0'");
}
private void assertBooleanTrue(String val) {
assertEquals(TernaryValue.TRUE, NodeUtil.getBooleanValue(getNode(val)));
}
private void assertBooleanFalse(String val) {
assertEquals(TernaryValue.FALSE, NodeUtil.getBooleanValue(getNode(val)));
}
private void assertBooleanUnknown(String val) {
assertEquals(TernaryValue.UNKNOWN, NodeUtil.getBooleanValue(getNode(val)));
}
public void testGetExpressionBooleanValue() {
assertExpressionBooleanTrue("a=true");
assertExpressionBooleanFalse("a=false");
assertExpressionBooleanTrue("a=(false,true)");
assertExpressionBooleanFalse("a=(true,false)");
assertExpressionBooleanTrue("a=(false || true)");
assertExpressionBooleanFalse("a=(true && false)");
assertExpressionBooleanTrue("a=!(true && false)");
assertExpressionBooleanTrue("a,true");
assertExpressionBooleanFalse("a,false");
assertExpressionBooleanTrue("true||false");
assertExpressionBooleanFalse("false||false");
assertExpressionBooleanTrue("true&&true");
assertExpressionBooleanFalse("true&&false");
assertExpressionBooleanFalse("!true");
assertExpressionBooleanTrue("!false");
assertExpressionBooleanTrue("!''");
// Assignment ops other than ASSIGN are unknown.
assertExpressionBooleanUnknown("a *= 2");
// Complex expressions that contain anything other then "=", ",", or "!" are
// unknown.
assertExpressionBooleanUnknown("2 + 2");
assertExpressionBooleanTrue("a=1");
assertExpressionBooleanTrue("a=/a/");
assertExpressionBooleanTrue("a={}");
assertExpressionBooleanTrue("true");
assertExpressionBooleanTrue("10");
assertExpressionBooleanTrue("'0'");
assertExpressionBooleanTrue("/a/");
assertExpressionBooleanTrue("{}");
assertExpressionBooleanTrue("[]");
assertExpressionBooleanFalse("false");
assertExpressionBooleanFalse("null");
assertExpressionBooleanFalse("0");
assertExpressionBooleanFalse("''");
assertExpressionBooleanFalse("undefined");
assertExpressionBooleanFalse("void 0");
assertExpressionBooleanFalse("void foo()");
assertExpressionBooleanTrue("a?true:true");
assertExpressionBooleanFalse("a?false:false");
assertExpressionBooleanUnknown("a?true:false");
assertExpressionBooleanUnknown("a?true:foo()");
assertExpressionBooleanUnknown("b");
assertExpressionBooleanUnknown("-'0.0'");
}
private void assertExpressionBooleanTrue(String val) {
assertEquals(TernaryValue.TRUE,
NodeUtil.getExpressionBooleanValue(getNode(val)));
}
private void assertExpressionBooleanFalse(String val) {
assertEquals(TernaryValue.FALSE,
NodeUtil.getExpressionBooleanValue(getNode(val)));
}
private void assertExpressionBooleanUnknown(String val) {
assertEquals(TernaryValue.UNKNOWN,
NodeUtil.getExpressionBooleanValue(getNode(val)));
}
public void testGetStringValue() {
assertEquals("true", NodeUtil.getStringValue(getNode("true")));
assertEquals("10", NodeUtil.getStringValue(getNode("10")));
assertEquals("1", NodeUtil.getStringValue(getNode("1.0")));
assertEquals("0", NodeUtil.getStringValue(getNode("'0'")));
assertEquals(null, NodeUtil.getStringValue(getNode("/a/")));
assertEquals(null, NodeUtil.getStringValue(getNode("{}")));
assertEquals(null, NodeUtil.getStringValue(getNode("[]")));
assertEquals("false", NodeUtil.getStringValue(getNode("false")));
assertEquals("null", NodeUtil.getStringValue(getNode("null")));
assertEquals("0", NodeUtil.getStringValue(getNode("0")));
assertEquals("", NodeUtil.getStringValue(getNode("''")));
assertEquals("undefined", NodeUtil.getStringValue(getNode("undefined")));
assertEquals("undefined", NodeUtil.getStringValue(getNode("void 0")));
assertEquals("undefined", NodeUtil.getStringValue(getNode("void foo()")));
}
public void testGetFunctionName1() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("function name(){}");
testGetFunctionName(parent.getFirstChild(), "name");
}
public void testGetFunctionName2() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("var name = function(){}")
.getFirstChild().getFirstChild();
testGetFunctionName(parent.getFirstChild(), "name");
}
public void testGetFunctionName3() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("qualified.name = function(){}")
.getFirstChild().getFirstChild();
testGetFunctionName(parent.getLastChild(), "qualified.name");
}
public void testGetFunctionName4() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("var name2 = function name1(){}")
.getFirstChild().getFirstChild();
testGetFunctionName(parent.getFirstChild(), "name2");
}
public void testGetFunctionName5() throws Exception {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode("qualified.name2 = function name1(){}");
Node parent = n.getFirstChild().getFirstChild();
testGetFunctionName(parent.getLastChild(), "qualified.name2");
}
private void testGetFunctionName(Node function, String name) {
assertEquals(Token.FUNCTION, function.getType());
assertEquals(name, NodeUtil.getFunctionName(function));
}
public void testContainsFunctionDeclaration() {
assertTrue(NodeUtil.containsFunction(
getNode("function foo(){}")));
assertTrue(NodeUtil.containsFunction(
getNode("(b?function(){}:null)")));
assertFalse(NodeUtil.containsFunction(
getNode("(b?foo():null)")));
assertFalse(NodeUtil.containsFunction(
getNode("foo()")));
}
private void assertSideEffect(boolean se, String js) {
Node n = parse(js);
assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild()));
}
private void assertSideEffect(boolean se, String js, boolean GlobalRegExp) {
Node n = parse(js);
Compiler compiler = new Compiler();
compiler.setHasRegExpGlobalReferences(GlobalRegExp);
assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild(), compiler));
}
public void testMayHaveSideEffects() {
assertSideEffect(true, "i++");
assertSideEffect(true, "[b, [a, i++]]");
assertSideEffect(true, "i=3");
assertSideEffect(true, "[0, i=3]");
assertSideEffect(true, "b()");
assertSideEffect(true, "[1, b()]");
assertSideEffect(true, "b.b=4");
assertSideEffect(true, "b.b--");
assertSideEffect(true, "i--");
assertSideEffect(true, "a[0][i=4]");
assertSideEffect(true, "a += 3");
assertSideEffect(true, "a, b, z += 4");
assertSideEffect(true, "a ? c : d++");
assertSideEffect(true, "a + c++");
assertSideEffect(true, "a + c - d()");
assertSideEffect(true, "a + c - d()");
assertSideEffect(true, "function foo() {}");
assertSideEffect(true, "while(true);");
assertSideEffect(true, "if(true){a()}");
assertSideEffect(false, "if(true){a}");
assertSideEffect(false, "(function() { })");
assertSideEffect(false, "(function() { i++ })");
assertSideEffect(false, "[function a(){}]");
assertSideEffect(false, "a");
assertSideEffect(false, "[b, c [d, [e]]]");
assertSideEffect(false, "({a: x, b: y, c: z})");
assertSideEffect(false, "/abc/gi");
assertSideEffect(false, "'a'");
assertSideEffect(false, "0");
assertSideEffect(false, "a + c");
assertSideEffect(false, "'c' + a[0]");
assertSideEffect(false, "a[0][1]");
assertSideEffect(false, "'a' + c");
assertSideEffect(false, "'a' + a.name");
assertSideEffect(false, "1, 2, 3");
assertSideEffect(false, "a, b, 3");
assertSideEffect(false, "(function(a, b) { })");
assertSideEffect(false, "a ? c : d");
assertSideEffect(false, "'1' + navigator.userAgent");
assertSideEffect(false, "new RegExp('foobar', 'i')");
assertSideEffect(true, "new RegExp(SomethingWacky(), 'i')");
assertSideEffect(false, "new Array()");
assertSideEffect(false, "new Array");
assertSideEffect(false, "new Array(4)");
assertSideEffect(false, "new Array('a', 'b', 'c')");
assertSideEffect(true, "new SomeClassINeverHeardOf()");
assertSideEffect(true, "new SomeClassINeverHeardOf()");
assertSideEffect(false, "({}).foo = 4");
assertSideEffect(false, "([]).foo = 4");
assertSideEffect(false, "(function() {}).foo = 4");
assertSideEffect(true, "this.foo = 4");
assertSideEffect(true, "a.foo = 4");
assertSideEffect(true, "(function() { return n; })().foo = 4");
assertSideEffect(true, "([]).foo = bar()");
assertSideEffect(false, "undefined");
assertSideEffect(false, "void 0");
assertSideEffect(true, "void foo()");
assertSideEffect(false, "-Infinity");
assertSideEffect(false, "Infinity");
assertSideEffect(false, "NaN");
assertSideEffect(false, "({}||[]).foo = 2;");
assertSideEffect(false, "(true ? {} : []).foo = 2;");
assertSideEffect(false, "({},[]).foo = 2;");
}
public void testRegExpSideEffect() {
// A RegExp Object by itself doesn't have any side-effects
assertSideEffect(false, "/abc/gi", true);
assertSideEffect(false, "/abc/gi", false);
// RegExp instance methods have global side-effects, so whether they are
// considered side-effect free depends on whether the global properties
// are referenced.
assertSideEffect(true, "(/abc/gi).test('')", true);
assertSideEffect(false, "(/abc/gi).test('')", false);
assertSideEffect(true, "(/abc/gi).test(a)", true);
assertSideEffect(false, "(/abc/gi).test(b)", false);
assertSideEffect(true, "(/abc/gi).exec('')", true);
assertSideEffect(false, "(/abc/gi).exec('')", false);
// Some RegExp object method that may have side-effects.
assertSideEffect(true, "(/abc/gi).foo('')", true);
assertSideEffect(true, "(/abc/gi).foo('')", false);
// Try the string RegExp ops.
assertSideEffect(true, "''.match('a')", true);
assertSideEffect(false, "''.match('a')", false);
assertSideEffect(true, "''.match(/(a)/)", true);
assertSideEffect(false, "''.match(/(a)/)", false);
assertSideEffect(true, "''.replace('a')", true);
assertSideEffect(false, "''.replace('a')", false);
assertSideEffect(true, "''.search('a')", true);
assertSideEffect(false, "''.search('a')", false);
assertSideEffect(true, "''.split('a')", true);
assertSideEffect(false, "''.split('a')", false);
// Some non-RegExp string op that may have side-effects.
assertSideEffect(true, "''.foo('a')", true);
assertSideEffect(true, "''.foo('a')", false);
// 'a' might be a RegExp object with the 'g' flag, in which case
// the state might change by running any of the string ops.
// Specifically, using these methods resets the "lastIndex" if used
// in combination with a RegExp instance "exec" method.
assertSideEffect(true, "''.match(a)", true);
assertSideEffect(true, "''.match(a)", false);
}
private void assertMutableState(boolean se, String js) {
Node n = parse(js);
assertEquals(se, NodeUtil.mayEffectMutableState(n.getFirstChild()));
}
public void testMayEffectMutableState() {
assertMutableState(true, "i++");
assertMutableState(true, "[b, [a, i++]]");
assertMutableState(true, "i=3");
assertMutableState(true, "[0, i=3]");
assertMutableState(true, "b()");
assertMutableState(true, "void b()");
assertMutableState(true, "[1, b()]");
assertMutableState(true, "b.b=4");
assertMutableState(true, "b.b--");
assertMutableState(true, "i--");
assertMutableState(true, "a[0][i=4]");
assertMutableState(true, "a += 3");
assertMutableState(true, "a, b, z += 4");
assertMutableState(true, "a ? c : d++");
assertMutableState(true, "a + c++");
assertMutableState(true, "a + c - d()");
assertMutableState(true, "a + c - d()");
assertMutableState(true, "function foo() {}");
assertMutableState(true, "while(true);");
assertMutableState(true, "if(true){a()}");
assertMutableState(false, "if(true){a}");
assertMutableState(true, "(function() { })");
assertMutableState(true, "(function() { i++ })");
assertMutableState(true, "[function a(){}]");
assertMutableState(false, "a");
assertMutableState(true, "[b, c [d, [e]]]");
assertMutableState(true, "({a: x, b: y, c: z})");
// Note: RegEx objects are not immutable, for instance, the exec
// method maintains state for "global" searches.
assertMutableState(true, "/abc/gi");
assertMutableState(false, "'a'");
assertMutableState(false, "0");
assertMutableState(false, "a + c");
assertMutableState(false, "'c' + a[0]");
assertMutableState(false, "a[0][1]");
assertMutableState(false, "'a' + c");
assertMutableState(false, "'a' + a.name");
assertMutableState(false, "1, 2, 3");
assertMutableState(false, "a, b, 3");
assertMutableState(true, "(function(a, b) { })");
assertMutableState(false, "a ? c : d");
assertMutableState(false, "'1' + navigator.userAgent");
assertMutableState(true, "new RegExp('foobar', 'i')");
assertMutableState(true, "new RegExp(SomethingWacky(), 'i')");
assertMutableState(true, "new Array()");
assertMutableState(true, "new Array");
assertMutableState(true, "new Array(4)");
assertMutableState(true, "new Array('a', 'b', 'c')");
assertMutableState(true, "new SomeClassINeverHeardOf()");
}
public void testIsFunctionExpression() {
assertContainsAnonFunc(true, "(function(){})");
assertContainsAnonFunc(true, "[function a(){}]");
assertContainsAnonFunc(false, "{x: function a(){}}");
assertContainsAnonFunc(true, "(function a(){})()");
assertContainsAnonFunc(true, "x = function a(){};");
assertContainsAnonFunc(true, "var x = function a(){};");
assertContainsAnonFunc(true, "if (function a(){});");
assertContainsAnonFunc(true, "while (function a(){});");
assertContainsAnonFunc(true, "do; while (function a(){});");
assertContainsAnonFunc(true, "for (function a(){};;);");
assertContainsAnonFunc(true, "for (;function a(){};);");
assertContainsAnonFunc(true, "for (;;function a(){});");
assertContainsAnonFunc(true, "for (p in function a(){});");
assertContainsAnonFunc(true, "with (function a(){}) {}");
assertContainsAnonFunc(false, "function a(){}");
assertContainsAnonFunc(false, "if (x) function a(){};");
assertContainsAnonFunc(false, "if (x) { function a(){} }");
assertContainsAnonFunc(false, "if (x); else function a(){};");
assertContainsAnonFunc(false, "while (x) function a(){};");
assertContainsAnonFunc(false, "do function a(){} while (0);");
assertContainsAnonFunc(false, "for (;;) function a(){}");
assertContainsAnonFunc(false, "for (p in o) function a(){};");
assertContainsAnonFunc(false, "with (x) function a(){}");
}
public void testNewFunctionNode() {
Node expected = parse("function foo(p1, p2, p3) { throw 2; }");
Node body = new Node(Token.BLOCK, new Node(Token.THROW, Node.newNumber(2)));
List<Node> params = Lists.newArrayList(Node.newString(Token.NAME, "p1"),
Node.newString(Token.NAME, "p2"),
Node.newString(Token.NAME, "p3"));
Node function = NodeUtil.newFunctionNode(
"foo", params, body, -1, -1);
Node actual = new Node(Token.SCRIPT);
actual.addChildToFront(function);
String difference = expected.checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
private void assertContainsAnonFunc(boolean expected, String js) {
Node funcParent = findParentOfFuncDescendant(parse(js));
assertNotNull("Expected function node in parse tree of: " + js, funcParent);
Node funcNode = getFuncChild(funcParent);
assertEquals(expected, NodeUtil.isFunctionExpression(funcNode));
}
private Node findParentOfFuncDescendant(Node n) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (c.getType() == Token.FUNCTION) {
return n;
}
Node result = findParentOfFuncDescendant(c);
if (result != null) {
return result;
}
}
return null;
}
private Node getFuncChild(Node n) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (c.getType() == Token.FUNCTION) {
return c;
}
}
return null;
}
public void testContainsType() {
assertTrue(NodeUtil.containsType(
parse("this"), Token.THIS));
assertTrue(NodeUtil.containsType(
parse("function foo(){}(this)"), Token.THIS));
assertTrue(NodeUtil.containsType(
parse("b?this:null"), Token.THIS));
assertFalse(NodeUtil.containsType(
parse("a"), Token.THIS));
assertFalse(NodeUtil.containsType(
parse("function foo(){}"), Token.THIS));
assertFalse(NodeUtil.containsType(
parse("(b?foo():null)"), Token.THIS));
}
public void testReferencesThis() {
assertTrue(NodeUtil.referencesThis(
parse("this")));
assertTrue(NodeUtil.referencesThis(
parse("function foo(){}(this)")));
assertTrue(NodeUtil.referencesThis(
parse("b?this:null")));
assertFalse(NodeUtil.referencesThis(
parse("a")));
assertFalse(NodeUtil.referencesThis(
parse("function foo(){}")));
assertFalse(NodeUtil.referencesThis(
parse("(b?foo():null)")));
}
public void testGetNodeTypeReferenceCount() {
assertEquals(0, NodeUtil.getNodeTypeReferenceCount(
parse("function foo(){}"), Token.THIS,
Predicates.<Node>alwaysTrue()));
assertEquals(1, NodeUtil.getNodeTypeReferenceCount(
parse("this"), Token.THIS,
Predicates.<Node>alwaysTrue()));
assertEquals(2, NodeUtil.getNodeTypeReferenceCount(
parse("this;function foo(){}(this)"), Token.THIS,
Predicates.<Node>alwaysTrue()));
}
public void testIsNameReferenceCount() {
assertTrue(NodeUtil.isNameReferenced(
parse("function foo(){}"), "foo"));
assertTrue(NodeUtil.isNameReferenced(
parse("var foo = function(){}"), "foo"));
assertFalse(NodeUtil.isNameReferenced(
parse("function foo(){}"), "undefined"));
assertTrue(NodeUtil.isNameReferenced(
parse("undefined"), "undefined"));
assertTrue(NodeUtil.isNameReferenced(
parse("undefined;function foo(){}(undefined)"), "undefined"));
assertTrue(NodeUtil.isNameReferenced(
parse("goo.foo"), "goo"));
assertFalse(NodeUtil.isNameReferenced(
parse("goo.foo"), "foo"));
}
public void testGetNameReferenceCount() {
assertEquals(0, NodeUtil.getNameReferenceCount(
parse("function foo(){}"), "undefined"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("undefined"), "undefined"));
assertEquals(2, NodeUtil.getNameReferenceCount(
parse("undefined;function foo(){}(undefined)"), "undefined"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("goo.foo"), "goo"));
assertEquals(0, NodeUtil.getNameReferenceCount(
parse("goo.foo"), "foo"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("function foo(){}"), "foo"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("var foo = function(){}"), "foo"));
}
public void testGetVarsDeclaredInBranch() {
Compiler compiler = new Compiler();
assertNodeNames(Sets.newHashSet("foo"),
NodeUtil.getVarsDeclaredInBranch(
parse("var foo;")));
assertNodeNames(Sets.newHashSet("foo","goo"),
NodeUtil.getVarsDeclaredInBranch(
parse("var foo,goo;")));
assertNodeNames(Sets.<String>newHashSet(),
NodeUtil.getVarsDeclaredInBranch(
parse("foo();")));
assertNodeNames(Sets.<String>newHashSet(),
NodeUtil.getVarsDeclaredInBranch(
parse("function(){var foo;}")));
assertNodeNames(Sets.newHashSet("goo"),
NodeUtil.getVarsDeclaredInBranch(
parse("var goo;function(){var foo;}")));
}
private void assertNodeNames(Set<String> nodeNames, Collection<Node> nodes) {
Set<String> actualNames = Sets.newHashSet();
for (Node node : nodes) {
actualNames.add(node.getString());
}
assertEquals(nodeNames, actualNames);
}
public void testIsControlStructureCodeBlock() {
Compiler compiler = new Compiler();
Node root = parse("if (x) foo(); else boo();");
Node ifNode = root.getFirstChild();
Node ifCondition = ifNode.getFirstChild();
Node ifCase = ifNode.getFirstChild().getNext();
Node elseCase = ifNode.getLastChild();
assertFalse(NodeUtil.isControlStructureCodeBlock(ifNode, ifCondition));
assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, ifCase));
assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, elseCase));
}
public void testIsFunctionExpression1() {
Compiler compiler = new Compiler();
Node root = parse("(function foo() {})");
Node StatementNode = root.getFirstChild();
assertTrue(NodeUtil.isExpressionNode(StatementNode));
Node functionNode = StatementNode.getFirstChild();
assertTrue(NodeUtil.isFunction(functionNode));
assertTrue(NodeUtil.isFunctionExpression(functionNode));
}
public void testIsFunctionExpression2() {
Compiler compiler = new Compiler();
Node root = parse("function foo() {}");
Node functionNode = root.getFirstChild();
assertTrue(NodeUtil.isFunction(functionNode));
assertFalse(NodeUtil.isFunctionExpression(functionNode));
}
public void testRemoveTryChild() {
Compiler compiler = new Compiler();
Node root = parse("try {foo()} catch(e) {} finally {}");
// Test removing the finally clause.
Node actual = root.cloneTree();
Node tryNode = actual.getFirstChild();
Node tryBlock = tryNode.getFirstChild();
Node catchBlocks = tryNode.getFirstChild().getNext();
Node finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(tryNode, finallyBlock);
String expected = "try {foo()} catch(e) {}";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the try clause.
actual = root.cloneTree();
tryNode = actual.getFirstChild();
tryBlock = tryNode.getFirstChild();
catchBlocks = tryNode.getFirstChild().getNext();
finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(tryNode, tryBlock);
expected = "try {} catch(e) {} finally {}";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the catch clause.
actual = root.cloneTree();
tryNode = actual.getFirstChild();
tryBlock = tryNode.getFirstChild();
catchBlocks = tryNode.getFirstChild().getNext();
Node catchBlock = catchBlocks.getFirstChild();
finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(catchBlocks, catchBlock);
expected = "try {foo()} finally {}";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveVarChild() {
Compiler compiler = new Compiler();
// Test removing the first child.
Node actual = parse("var foo, goo, hoo");
Node varNode = actual.getFirstChild();
Node nameNode = varNode.getFirstChild();
NodeUtil.removeChild(varNode, nameNode);
String expected = "var goo, hoo";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the second child.
actual = parse("var foo, goo, hoo");
varNode = actual.getFirstChild();
nameNode = varNode.getFirstChild().getNext();
NodeUtil.removeChild(varNode, nameNode);
expected = "var foo, hoo";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the last child of several children.
actual = parse("var foo, hoo");
varNode = actual.getFirstChild();
nameNode = varNode.getFirstChild().getNext();
NodeUtil.removeChild(varNode, nameNode);
expected = "var foo";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the last.
actual = parse("var hoo");
varNode = actual.getFirstChild();
nameNode = varNode.getFirstChild();
NodeUtil.removeChild(varNode, nameNode);
expected = "";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveLabelChild1() {
Compiler compiler = new Compiler();
// Test removing the first child.
Node actual = parse("foo: goo()");
Node labelNode = actual.getFirstChild();
Node callExpressNode = labelNode.getLastChild();
NodeUtil.removeChild(labelNode, callExpressNode);
String expected = "";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveLabelChild2() {
// Test removing the first child.
Node actual = parse("achoo: foo: goo()");
Node labelNode = actual.getFirstChild();
Node callExpressNode = labelNode.getLastChild();
NodeUtil.removeChild(labelNode, callExpressNode);
String expected = "";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveForChild() {
Compiler compiler = new Compiler();
// Test removing the initializer.
Node actual = parse("for(var a=0;a<0;a++)foo()");
Node forNode = actual.getFirstChild();
Node child = forNode.getFirstChild();
NodeUtil.removeChild(forNode, child);
String expected = "for(;a<0;a++)foo()";
String difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the condition.
actual = parse("for(var a=0;a<0;a++)foo()");
forNode = actual.getFirstChild();
child = forNode.getFirstChild().getNext();
NodeUtil.removeChild(forNode, child);
expected = "for(var a=0;;a++)foo()";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the increment.
actual = parse("for(var a=0;a<0;a++)foo()");
forNode = actual.getFirstChild();
child = forNode.getFirstChild().getNext().getNext();
NodeUtil.removeChild(forNode, child);
expected = "for(var a=0;a<0;)foo()";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the body.
actual = parse("for(var a=0;a<0;a++)foo()");
forNode = actual.getFirstChild();
child = forNode.getLastChild();
NodeUtil.removeChild(forNode, child);
expected = "for(var a=0;a<0;a++);";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the body.
actual = parse("for(a in ack)foo();");
forNode = actual.getFirstChild();
child = forNode.getLastChild();
NodeUtil.removeChild(forNode, child);
expected = "for(a in ack);";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
}
public void testMergeBlock1() {
Compiler compiler = new Compiler();
// Test removing the initializer.
Node actual = parse("{{a();b();}}");
Node parentBlock = actual.getFirstChild();
Node childBlock = parentBlock.getFirstChild();
assertTrue(NodeUtil.tryMergeBlock(childBlock));
String expected = "{a();b();}";
String difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
}
public void testMergeBlock2() {
Compiler compiler = new Compiler();
// Test removing the initializer.
Node actual = parse("foo:{a();}");
Node parentLabel = actual.getFirstChild();
Node childBlock = parentLabel.getLastChild();
assertFalse(NodeUtil.tryMergeBlock(childBlock));
}
public void testMergeBlock3() {
Compiler compiler = new Compiler();
// Test removing the initializer.
String code = "foo:{a();boo()}";
Node actual = parse("foo:{a();boo()}");
Node parentLabel = actual.getFirstChild();
Node childBlock = parentLabel.getLastChild();
assertFalse(NodeUtil.tryMergeBlock(childBlock));
String expected = code;
String difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
}
public void testGetSourceName() {
Node n = new Node(Token.BLOCK);
Node parent = new Node(Token.BLOCK, n);
parent.putProp(Node.SOURCENAME_PROP, "foo");
assertEquals("foo", NodeUtil.getSourceName(n));
}
public void testIsLabelName() {
Compiler compiler = new Compiler();
// Test removing the initializer.
String code = "a:while(1) {a; continue a; break a; break;}";
Node actual = parse(code);
Node labelNode = actual.getFirstChild();
assertTrue(labelNode.getType() == Token.LABEL);
assertTrue(NodeUtil.isLabelName(labelNode.getFirstChild()));
assertFalse(NodeUtil.isLabelName(labelNode.getLastChild()));
Node whileNode = labelNode.getLastChild();
assertTrue(whileNode.getType() == Token.WHILE);
Node whileBlock = whileNode.getLastChild();
assertTrue(whileBlock.getType() == Token.BLOCK);
assertFalse(NodeUtil.isLabelName(whileBlock));
Node firstStatement = whileBlock.getFirstChild();
assertTrue(firstStatement.getType() == Token.EXPR_RESULT);
Node variableReference = firstStatement.getFirstChild();
assertTrue(variableReference.getType() == Token.NAME);
assertFalse(NodeUtil.isLabelName(variableReference));
Node continueStatement = firstStatement.getNext();
assertTrue(continueStatement.getType() == Token.CONTINUE);
assertTrue(NodeUtil.isLabelName(continueStatement.getFirstChild()));
Node firstBreak = continueStatement.getNext();
assertTrue(firstBreak.getType() == Token.BREAK);
assertTrue(NodeUtil.isLabelName(firstBreak.getFirstChild()));
Node secondBreak = firstBreak.getNext();
assertTrue(secondBreak.getType() == Token.BREAK);
assertFalse(secondBreak.hasChildren());
assertFalse(NodeUtil.isLabelName(secondBreak.getFirstChild()));
}
public void testLocalValue1() throws Exception {
// Names are not known to be local.
assertFalse(testLocalValue("x"));
assertFalse(testLocalValue("x()"));
assertFalse(testLocalValue("this"));
assertFalse(testLocalValue("arguments"));
// new objects are local
assertTrue(testLocalValue("new x()"));
// property references are assume to be non-local
assertFalse(testLocalValue("(new x()).y"));
assertFalse(testLocalValue("(new x())['y']"));
// Primitive values are local
assertTrue(testLocalValue("null"));
assertTrue(testLocalValue("undefined"));
assertTrue(testLocalValue("Infinity"));
assertTrue(testLocalValue("NaN"));
assertTrue(testLocalValue("1"));
assertTrue(testLocalValue("'a'"));
assertTrue(testLocalValue("true"));
assertTrue(testLocalValue("false"));
assertTrue(testLocalValue("[]"));
assertTrue(testLocalValue("{}"));
// The contents of arrays and objects don't matter
assertTrue(testLocalValue("[x]"));
assertTrue(testLocalValue("{'a':x}"));
// Pre-increment results in primitive number
assertTrue(testLocalValue("++x"));
assertTrue(testLocalValue("--x"));
// Post-increment, the previous value matters.
assertFalse(testLocalValue("x++"));
assertFalse(testLocalValue("x--"));
// The left side of an only assign matters if it is an alias or mutable.
assertTrue(testLocalValue("x=1"));
assertFalse(testLocalValue("x=[]"));
assertFalse(testLocalValue("x=y"));
// The right hand side of assignment opts don't matter, as they force
// a local result.
assertTrue(testLocalValue("x+=y"));
assertTrue(testLocalValue("x*=y"));
// Comparisons always result in locals, as they force a local boolean
// result.
assertTrue(testLocalValue("x==y"));
assertTrue(testLocalValue("x!=y"));
assertTrue(testLocalValue("x>y"));
// Only the right side of a comma matters
assertTrue(testLocalValue("(1,2)"));
assertTrue(testLocalValue("(x,1)"));
assertFalse(testLocalValue("(x,y)"));
// Both the operands of OR matter
assertTrue(testLocalValue("1||2"));
assertFalse(testLocalValue("x||1"));
assertFalse(testLocalValue("x||y"));
assertFalse(testLocalValue("1||y"));
// Both the operands of AND matter
assertTrue(testLocalValue("1&&2"));
assertFalse(testLocalValue("x&&1"));
assertFalse(testLocalValue("x&&y"));
assertFalse(testLocalValue("1&&y"));
// Only the results of HOOK matter
assertTrue(testLocalValue("x?1:2"));
assertFalse(testLocalValue("x?x:2"));
assertFalse(testLocalValue("x?1:x"));
assertFalse(testLocalValue("x?x:y"));
// Results of ops are local values
assertTrue(testLocalValue("!y"));
assertTrue(testLocalValue("~y"));
assertTrue(testLocalValue("y + 1"));
assertTrue(testLocalValue("y + z"));
assertTrue(testLocalValue("y * z"));
assertTrue(testLocalValue("'a' in x"));
assertTrue(testLocalValue("typeof x"));
assertTrue(testLocalValue("x instanceof y"));
assertTrue(testLocalValue("void x"));
assertTrue(testLocalValue("void 0"));
assertFalse(testLocalValue("{}.x"));
}
private boolean testLocalValue(String js) {
Node script = parse("var test = " + js +";");
Preconditions.checkState(script.getType() == Token.SCRIPT);
Node var = script.getFirstChild();
Preconditions.checkState(var.getType() == Token.VAR);
Node name = var.getFirstChild();
Preconditions.checkState(name.getType() == Token.NAME);
Node value = name.getFirstChild();
return NodeUtil.evaluatesToLocalValue(value);
}
public void testValidDefine() {
assertTrue(testValidDefineValue("1"));
assertTrue(testValidDefineValue("-3"));
assertTrue(testValidDefineValue("true"));
assertTrue(testValidDefineValue("false"));
assertTrue(testValidDefineValue("'foo'"));
assertFalse(testValidDefineValue("x"));
assertFalse(testValidDefineValue("null"));
assertFalse(testValidDefineValue("undefined"));
assertFalse(testValidDefineValue("NaN"));
assertTrue(testValidDefineValue("!true"));
assertTrue(testValidDefineValue("-true"));
assertTrue(testValidDefineValue("1 & 8"));
assertTrue(testValidDefineValue("1 + 8"));
assertTrue(testValidDefineValue("'a' + 'b'"));
assertFalse(testValidDefineValue("1 & foo"));
}
private boolean testValidDefineValue(String js) {
Node script = parse("var test = " + js +";");
Node var = script.getFirstChild();
Node name = var.getFirstChild();
Node value = name.getFirstChild();
ImmutableSet<String> defines = ImmutableSet.of();
return NodeUtil.isValidDefineValue(value, defines);
}
} | // You are a professional Java test case writer, please create a test case named `testValidDefine` for the issue `Closure-255`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-255
//
// ## Issue-Title:
// closure-compiler @define annotation does not allow line to be split on 80 characters.
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Create a JavaScript file with the followiing:
// /\*\* @define {string} \*/
// var CONSTANT = "some very long string name that I want to wrap " +
// "and so break using a + since I don't want to " +
// "introduce a newline into the string."
// 2. Run closure-compiler on the .js file.
// 3. See it generate an error on the '+'.
//
// **What is the expected output? What do you see instead?**
// It should work, since the line is assigning a constant value to the var.
//
// **Please provide any additional information below.**
// Removing the '+' and making the string all one line does work correctly.
//
//
public void testValidDefine() {
| 1,089 | 94 | 1,070 | test/com/google/javascript/jscomp/NodeUtilTest.java | test | ```markdown
## Issue-ID: Closure-255
## Issue-Title:
closure-compiler @define annotation does not allow line to be split on 80 characters.
## Issue-Description:
**What steps will reproduce the problem?**
1. Create a JavaScript file with the followiing:
/\*\* @define {string} \*/
var CONSTANT = "some very long string name that I want to wrap " +
"and so break using a + since I don't want to " +
"introduce a newline into the string."
2. Run closure-compiler on the .js file.
3. See it generate an error on the '+'.
**What is the expected output? What do you see instead?**
It should work, since the line is assigning a constant value to the var.
**Please provide any additional information below.**
Removing the '+' and making the string all one line does work correctly.
```
You are a professional Java test case writer, please create a test case named `testValidDefine` for the issue `Closure-255`, utilizing the provided issue report information and the following function signature.
```java
public void testValidDefine() {
```
| 1,070 | [
"com.google.javascript.jscomp.NodeUtil"
] | 568bd6d640661c966c75934d3e21b23b274d58c1a9a396e2afc9d1fe8029ee25 | public void testValidDefine() | // You are a professional Java test case writer, please create a test case named `testValidDefine` for the issue `Closure-255`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-255
//
// ## Issue-Title:
// closure-compiler @define annotation does not allow line to be split on 80 characters.
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Create a JavaScript file with the followiing:
// /\*\* @define {string} \*/
// var CONSTANT = "some very long string name that I want to wrap " +
// "and so break using a + since I don't want to " +
// "introduce a newline into the string."
// 2. Run closure-compiler on the .js file.
// 3. See it generate an error on the '+'.
//
// **What is the expected output? What do you see instead?**
// It should work, since the line is assigning a constant value to the var.
//
// **Please provide any additional information below.**
// Removing the '+' and making the string all one line does work correctly.
//
//
| 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;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.TernaryValue;
import junit.framework.TestCase;
import java.util.Collection;
import java.util.List;
import java.util.Set;
public class NodeUtilTest extends TestCase {
private static Node parse(String js) {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode(js);
assertEquals(0, compiler.getErrorCount());
return n;
}
static Node getNode(String js) {
Node root = parse("var a=(" + js + ");");
Node expr = root.getFirstChild();
Node var = expr.getFirstChild();
return var.getFirstChild();
}
public void testIsLiteralOrConstValue() {
assertLiteralAndImmutable(getNode("10"));
assertLiteralAndImmutable(getNode("-10"));
assertLiteralButNotImmutable(getNode("[10, 20]"));
assertLiteralButNotImmutable(getNode("{'a': 20}"));
assertLiteralButNotImmutable(getNode("[10, , 1.0, [undefined], 'a']"));
assertLiteralButNotImmutable(getNode("/abc/"));
assertLiteralAndImmutable(getNode("\"string\""));
assertLiteralAndImmutable(getNode("'aaa'"));
assertLiteralAndImmutable(getNode("null"));
assertLiteralAndImmutable(getNode("undefined"));
assertLiteralAndImmutable(getNode("void 0"));
assertNotLiteral(getNode("abc"));
assertNotLiteral(getNode("[10, foo(), 20]"));
assertNotLiteral(getNode("foo()"));
assertNotLiteral(getNode("c + d"));
assertNotLiteral(getNode("{'a': foo()}"));
assertNotLiteral(getNode("void foo()"));
}
public void assertLiteralAndImmutable(Node n) {
assertTrue(NodeUtil.isLiteralValue(n, true));
assertTrue(NodeUtil.isLiteralValue(n, false));
assertTrue(NodeUtil.isImmutableValue(n));
}
public void assertLiteralButNotImmutable(Node n) {
assertTrue(NodeUtil.isLiteralValue(n, true));
assertTrue(NodeUtil.isLiteralValue(n, false));
assertFalse(NodeUtil.isImmutableValue(n));
}
public void assertNotLiteral(Node n) {
assertFalse(NodeUtil.isLiteralValue(n, true));
assertFalse(NodeUtil.isLiteralValue(n, false));
assertFalse(NodeUtil.isImmutableValue(n));
}
public void testGetBooleanValue() {
assertBooleanTrue("true");
assertBooleanTrue("10");
assertBooleanTrue("'0'");
assertBooleanTrue("/a/");
assertBooleanTrue("{}");
assertBooleanTrue("[]");
assertBooleanFalse("false");
assertBooleanFalse("null");
assertBooleanFalse("0");
assertBooleanFalse("''");
assertBooleanFalse("undefined");
assertBooleanFalse("void 0");
assertBooleanFalse("void foo()");
assertBooleanUnknown("b");
assertBooleanUnknown("-'0.0'");
}
private void assertBooleanTrue(String val) {
assertEquals(TernaryValue.TRUE, NodeUtil.getBooleanValue(getNode(val)));
}
private void assertBooleanFalse(String val) {
assertEquals(TernaryValue.FALSE, NodeUtil.getBooleanValue(getNode(val)));
}
private void assertBooleanUnknown(String val) {
assertEquals(TernaryValue.UNKNOWN, NodeUtil.getBooleanValue(getNode(val)));
}
public void testGetExpressionBooleanValue() {
assertExpressionBooleanTrue("a=true");
assertExpressionBooleanFalse("a=false");
assertExpressionBooleanTrue("a=(false,true)");
assertExpressionBooleanFalse("a=(true,false)");
assertExpressionBooleanTrue("a=(false || true)");
assertExpressionBooleanFalse("a=(true && false)");
assertExpressionBooleanTrue("a=!(true && false)");
assertExpressionBooleanTrue("a,true");
assertExpressionBooleanFalse("a,false");
assertExpressionBooleanTrue("true||false");
assertExpressionBooleanFalse("false||false");
assertExpressionBooleanTrue("true&&true");
assertExpressionBooleanFalse("true&&false");
assertExpressionBooleanFalse("!true");
assertExpressionBooleanTrue("!false");
assertExpressionBooleanTrue("!''");
// Assignment ops other than ASSIGN are unknown.
assertExpressionBooleanUnknown("a *= 2");
// Complex expressions that contain anything other then "=", ",", or "!" are
// unknown.
assertExpressionBooleanUnknown("2 + 2");
assertExpressionBooleanTrue("a=1");
assertExpressionBooleanTrue("a=/a/");
assertExpressionBooleanTrue("a={}");
assertExpressionBooleanTrue("true");
assertExpressionBooleanTrue("10");
assertExpressionBooleanTrue("'0'");
assertExpressionBooleanTrue("/a/");
assertExpressionBooleanTrue("{}");
assertExpressionBooleanTrue("[]");
assertExpressionBooleanFalse("false");
assertExpressionBooleanFalse("null");
assertExpressionBooleanFalse("0");
assertExpressionBooleanFalse("''");
assertExpressionBooleanFalse("undefined");
assertExpressionBooleanFalse("void 0");
assertExpressionBooleanFalse("void foo()");
assertExpressionBooleanTrue("a?true:true");
assertExpressionBooleanFalse("a?false:false");
assertExpressionBooleanUnknown("a?true:false");
assertExpressionBooleanUnknown("a?true:foo()");
assertExpressionBooleanUnknown("b");
assertExpressionBooleanUnknown("-'0.0'");
}
private void assertExpressionBooleanTrue(String val) {
assertEquals(TernaryValue.TRUE,
NodeUtil.getExpressionBooleanValue(getNode(val)));
}
private void assertExpressionBooleanFalse(String val) {
assertEquals(TernaryValue.FALSE,
NodeUtil.getExpressionBooleanValue(getNode(val)));
}
private void assertExpressionBooleanUnknown(String val) {
assertEquals(TernaryValue.UNKNOWN,
NodeUtil.getExpressionBooleanValue(getNode(val)));
}
public void testGetStringValue() {
assertEquals("true", NodeUtil.getStringValue(getNode("true")));
assertEquals("10", NodeUtil.getStringValue(getNode("10")));
assertEquals("1", NodeUtil.getStringValue(getNode("1.0")));
assertEquals("0", NodeUtil.getStringValue(getNode("'0'")));
assertEquals(null, NodeUtil.getStringValue(getNode("/a/")));
assertEquals(null, NodeUtil.getStringValue(getNode("{}")));
assertEquals(null, NodeUtil.getStringValue(getNode("[]")));
assertEquals("false", NodeUtil.getStringValue(getNode("false")));
assertEquals("null", NodeUtil.getStringValue(getNode("null")));
assertEquals("0", NodeUtil.getStringValue(getNode("0")));
assertEquals("", NodeUtil.getStringValue(getNode("''")));
assertEquals("undefined", NodeUtil.getStringValue(getNode("undefined")));
assertEquals("undefined", NodeUtil.getStringValue(getNode("void 0")));
assertEquals("undefined", NodeUtil.getStringValue(getNode("void foo()")));
}
public void testGetFunctionName1() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("function name(){}");
testGetFunctionName(parent.getFirstChild(), "name");
}
public void testGetFunctionName2() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("var name = function(){}")
.getFirstChild().getFirstChild();
testGetFunctionName(parent.getFirstChild(), "name");
}
public void testGetFunctionName3() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("qualified.name = function(){}")
.getFirstChild().getFirstChild();
testGetFunctionName(parent.getLastChild(), "qualified.name");
}
public void testGetFunctionName4() throws Exception {
Compiler compiler = new Compiler();
Node parent = compiler.parseTestCode("var name2 = function name1(){}")
.getFirstChild().getFirstChild();
testGetFunctionName(parent.getFirstChild(), "name2");
}
public void testGetFunctionName5() throws Exception {
Compiler compiler = new Compiler();
Node n = compiler.parseTestCode("qualified.name2 = function name1(){}");
Node parent = n.getFirstChild().getFirstChild();
testGetFunctionName(parent.getLastChild(), "qualified.name2");
}
private void testGetFunctionName(Node function, String name) {
assertEquals(Token.FUNCTION, function.getType());
assertEquals(name, NodeUtil.getFunctionName(function));
}
public void testContainsFunctionDeclaration() {
assertTrue(NodeUtil.containsFunction(
getNode("function foo(){}")));
assertTrue(NodeUtil.containsFunction(
getNode("(b?function(){}:null)")));
assertFalse(NodeUtil.containsFunction(
getNode("(b?foo():null)")));
assertFalse(NodeUtil.containsFunction(
getNode("foo()")));
}
private void assertSideEffect(boolean se, String js) {
Node n = parse(js);
assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild()));
}
private void assertSideEffect(boolean se, String js, boolean GlobalRegExp) {
Node n = parse(js);
Compiler compiler = new Compiler();
compiler.setHasRegExpGlobalReferences(GlobalRegExp);
assertEquals(se, NodeUtil.mayHaveSideEffects(n.getFirstChild(), compiler));
}
public void testMayHaveSideEffects() {
assertSideEffect(true, "i++");
assertSideEffect(true, "[b, [a, i++]]");
assertSideEffect(true, "i=3");
assertSideEffect(true, "[0, i=3]");
assertSideEffect(true, "b()");
assertSideEffect(true, "[1, b()]");
assertSideEffect(true, "b.b=4");
assertSideEffect(true, "b.b--");
assertSideEffect(true, "i--");
assertSideEffect(true, "a[0][i=4]");
assertSideEffect(true, "a += 3");
assertSideEffect(true, "a, b, z += 4");
assertSideEffect(true, "a ? c : d++");
assertSideEffect(true, "a + c++");
assertSideEffect(true, "a + c - d()");
assertSideEffect(true, "a + c - d()");
assertSideEffect(true, "function foo() {}");
assertSideEffect(true, "while(true);");
assertSideEffect(true, "if(true){a()}");
assertSideEffect(false, "if(true){a}");
assertSideEffect(false, "(function() { })");
assertSideEffect(false, "(function() { i++ })");
assertSideEffect(false, "[function a(){}]");
assertSideEffect(false, "a");
assertSideEffect(false, "[b, c [d, [e]]]");
assertSideEffect(false, "({a: x, b: y, c: z})");
assertSideEffect(false, "/abc/gi");
assertSideEffect(false, "'a'");
assertSideEffect(false, "0");
assertSideEffect(false, "a + c");
assertSideEffect(false, "'c' + a[0]");
assertSideEffect(false, "a[0][1]");
assertSideEffect(false, "'a' + c");
assertSideEffect(false, "'a' + a.name");
assertSideEffect(false, "1, 2, 3");
assertSideEffect(false, "a, b, 3");
assertSideEffect(false, "(function(a, b) { })");
assertSideEffect(false, "a ? c : d");
assertSideEffect(false, "'1' + navigator.userAgent");
assertSideEffect(false, "new RegExp('foobar', 'i')");
assertSideEffect(true, "new RegExp(SomethingWacky(), 'i')");
assertSideEffect(false, "new Array()");
assertSideEffect(false, "new Array");
assertSideEffect(false, "new Array(4)");
assertSideEffect(false, "new Array('a', 'b', 'c')");
assertSideEffect(true, "new SomeClassINeverHeardOf()");
assertSideEffect(true, "new SomeClassINeverHeardOf()");
assertSideEffect(false, "({}).foo = 4");
assertSideEffect(false, "([]).foo = 4");
assertSideEffect(false, "(function() {}).foo = 4");
assertSideEffect(true, "this.foo = 4");
assertSideEffect(true, "a.foo = 4");
assertSideEffect(true, "(function() { return n; })().foo = 4");
assertSideEffect(true, "([]).foo = bar()");
assertSideEffect(false, "undefined");
assertSideEffect(false, "void 0");
assertSideEffect(true, "void foo()");
assertSideEffect(false, "-Infinity");
assertSideEffect(false, "Infinity");
assertSideEffect(false, "NaN");
assertSideEffect(false, "({}||[]).foo = 2;");
assertSideEffect(false, "(true ? {} : []).foo = 2;");
assertSideEffect(false, "({},[]).foo = 2;");
}
public void testRegExpSideEffect() {
// A RegExp Object by itself doesn't have any side-effects
assertSideEffect(false, "/abc/gi", true);
assertSideEffect(false, "/abc/gi", false);
// RegExp instance methods have global side-effects, so whether they are
// considered side-effect free depends on whether the global properties
// are referenced.
assertSideEffect(true, "(/abc/gi).test('')", true);
assertSideEffect(false, "(/abc/gi).test('')", false);
assertSideEffect(true, "(/abc/gi).test(a)", true);
assertSideEffect(false, "(/abc/gi).test(b)", false);
assertSideEffect(true, "(/abc/gi).exec('')", true);
assertSideEffect(false, "(/abc/gi).exec('')", false);
// Some RegExp object method that may have side-effects.
assertSideEffect(true, "(/abc/gi).foo('')", true);
assertSideEffect(true, "(/abc/gi).foo('')", false);
// Try the string RegExp ops.
assertSideEffect(true, "''.match('a')", true);
assertSideEffect(false, "''.match('a')", false);
assertSideEffect(true, "''.match(/(a)/)", true);
assertSideEffect(false, "''.match(/(a)/)", false);
assertSideEffect(true, "''.replace('a')", true);
assertSideEffect(false, "''.replace('a')", false);
assertSideEffect(true, "''.search('a')", true);
assertSideEffect(false, "''.search('a')", false);
assertSideEffect(true, "''.split('a')", true);
assertSideEffect(false, "''.split('a')", false);
// Some non-RegExp string op that may have side-effects.
assertSideEffect(true, "''.foo('a')", true);
assertSideEffect(true, "''.foo('a')", false);
// 'a' might be a RegExp object with the 'g' flag, in which case
// the state might change by running any of the string ops.
// Specifically, using these methods resets the "lastIndex" if used
// in combination with a RegExp instance "exec" method.
assertSideEffect(true, "''.match(a)", true);
assertSideEffect(true, "''.match(a)", false);
}
private void assertMutableState(boolean se, String js) {
Node n = parse(js);
assertEquals(se, NodeUtil.mayEffectMutableState(n.getFirstChild()));
}
public void testMayEffectMutableState() {
assertMutableState(true, "i++");
assertMutableState(true, "[b, [a, i++]]");
assertMutableState(true, "i=3");
assertMutableState(true, "[0, i=3]");
assertMutableState(true, "b()");
assertMutableState(true, "void b()");
assertMutableState(true, "[1, b()]");
assertMutableState(true, "b.b=4");
assertMutableState(true, "b.b--");
assertMutableState(true, "i--");
assertMutableState(true, "a[0][i=4]");
assertMutableState(true, "a += 3");
assertMutableState(true, "a, b, z += 4");
assertMutableState(true, "a ? c : d++");
assertMutableState(true, "a + c++");
assertMutableState(true, "a + c - d()");
assertMutableState(true, "a + c - d()");
assertMutableState(true, "function foo() {}");
assertMutableState(true, "while(true);");
assertMutableState(true, "if(true){a()}");
assertMutableState(false, "if(true){a}");
assertMutableState(true, "(function() { })");
assertMutableState(true, "(function() { i++ })");
assertMutableState(true, "[function a(){}]");
assertMutableState(false, "a");
assertMutableState(true, "[b, c [d, [e]]]");
assertMutableState(true, "({a: x, b: y, c: z})");
// Note: RegEx objects are not immutable, for instance, the exec
// method maintains state for "global" searches.
assertMutableState(true, "/abc/gi");
assertMutableState(false, "'a'");
assertMutableState(false, "0");
assertMutableState(false, "a + c");
assertMutableState(false, "'c' + a[0]");
assertMutableState(false, "a[0][1]");
assertMutableState(false, "'a' + c");
assertMutableState(false, "'a' + a.name");
assertMutableState(false, "1, 2, 3");
assertMutableState(false, "a, b, 3");
assertMutableState(true, "(function(a, b) { })");
assertMutableState(false, "a ? c : d");
assertMutableState(false, "'1' + navigator.userAgent");
assertMutableState(true, "new RegExp('foobar', 'i')");
assertMutableState(true, "new RegExp(SomethingWacky(), 'i')");
assertMutableState(true, "new Array()");
assertMutableState(true, "new Array");
assertMutableState(true, "new Array(4)");
assertMutableState(true, "new Array('a', 'b', 'c')");
assertMutableState(true, "new SomeClassINeverHeardOf()");
}
public void testIsFunctionExpression() {
assertContainsAnonFunc(true, "(function(){})");
assertContainsAnonFunc(true, "[function a(){}]");
assertContainsAnonFunc(false, "{x: function a(){}}");
assertContainsAnonFunc(true, "(function a(){})()");
assertContainsAnonFunc(true, "x = function a(){};");
assertContainsAnonFunc(true, "var x = function a(){};");
assertContainsAnonFunc(true, "if (function a(){});");
assertContainsAnonFunc(true, "while (function a(){});");
assertContainsAnonFunc(true, "do; while (function a(){});");
assertContainsAnonFunc(true, "for (function a(){};;);");
assertContainsAnonFunc(true, "for (;function a(){};);");
assertContainsAnonFunc(true, "for (;;function a(){});");
assertContainsAnonFunc(true, "for (p in function a(){});");
assertContainsAnonFunc(true, "with (function a(){}) {}");
assertContainsAnonFunc(false, "function a(){}");
assertContainsAnonFunc(false, "if (x) function a(){};");
assertContainsAnonFunc(false, "if (x) { function a(){} }");
assertContainsAnonFunc(false, "if (x); else function a(){};");
assertContainsAnonFunc(false, "while (x) function a(){};");
assertContainsAnonFunc(false, "do function a(){} while (0);");
assertContainsAnonFunc(false, "for (;;) function a(){}");
assertContainsAnonFunc(false, "for (p in o) function a(){};");
assertContainsAnonFunc(false, "with (x) function a(){}");
}
public void testNewFunctionNode() {
Node expected = parse("function foo(p1, p2, p3) { throw 2; }");
Node body = new Node(Token.BLOCK, new Node(Token.THROW, Node.newNumber(2)));
List<Node> params = Lists.newArrayList(Node.newString(Token.NAME, "p1"),
Node.newString(Token.NAME, "p2"),
Node.newString(Token.NAME, "p3"));
Node function = NodeUtil.newFunctionNode(
"foo", params, body, -1, -1);
Node actual = new Node(Token.SCRIPT);
actual.addChildToFront(function);
String difference = expected.checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
private void assertContainsAnonFunc(boolean expected, String js) {
Node funcParent = findParentOfFuncDescendant(parse(js));
assertNotNull("Expected function node in parse tree of: " + js, funcParent);
Node funcNode = getFuncChild(funcParent);
assertEquals(expected, NodeUtil.isFunctionExpression(funcNode));
}
private Node findParentOfFuncDescendant(Node n) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (c.getType() == Token.FUNCTION) {
return n;
}
Node result = findParentOfFuncDescendant(c);
if (result != null) {
return result;
}
}
return null;
}
private Node getFuncChild(Node n) {
for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
if (c.getType() == Token.FUNCTION) {
return c;
}
}
return null;
}
public void testContainsType() {
assertTrue(NodeUtil.containsType(
parse("this"), Token.THIS));
assertTrue(NodeUtil.containsType(
parse("function foo(){}(this)"), Token.THIS));
assertTrue(NodeUtil.containsType(
parse("b?this:null"), Token.THIS));
assertFalse(NodeUtil.containsType(
parse("a"), Token.THIS));
assertFalse(NodeUtil.containsType(
parse("function foo(){}"), Token.THIS));
assertFalse(NodeUtil.containsType(
parse("(b?foo():null)"), Token.THIS));
}
public void testReferencesThis() {
assertTrue(NodeUtil.referencesThis(
parse("this")));
assertTrue(NodeUtil.referencesThis(
parse("function foo(){}(this)")));
assertTrue(NodeUtil.referencesThis(
parse("b?this:null")));
assertFalse(NodeUtil.referencesThis(
parse("a")));
assertFalse(NodeUtil.referencesThis(
parse("function foo(){}")));
assertFalse(NodeUtil.referencesThis(
parse("(b?foo():null)")));
}
public void testGetNodeTypeReferenceCount() {
assertEquals(0, NodeUtil.getNodeTypeReferenceCount(
parse("function foo(){}"), Token.THIS,
Predicates.<Node>alwaysTrue()));
assertEquals(1, NodeUtil.getNodeTypeReferenceCount(
parse("this"), Token.THIS,
Predicates.<Node>alwaysTrue()));
assertEquals(2, NodeUtil.getNodeTypeReferenceCount(
parse("this;function foo(){}(this)"), Token.THIS,
Predicates.<Node>alwaysTrue()));
}
public void testIsNameReferenceCount() {
assertTrue(NodeUtil.isNameReferenced(
parse("function foo(){}"), "foo"));
assertTrue(NodeUtil.isNameReferenced(
parse("var foo = function(){}"), "foo"));
assertFalse(NodeUtil.isNameReferenced(
parse("function foo(){}"), "undefined"));
assertTrue(NodeUtil.isNameReferenced(
parse("undefined"), "undefined"));
assertTrue(NodeUtil.isNameReferenced(
parse("undefined;function foo(){}(undefined)"), "undefined"));
assertTrue(NodeUtil.isNameReferenced(
parse("goo.foo"), "goo"));
assertFalse(NodeUtil.isNameReferenced(
parse("goo.foo"), "foo"));
}
public void testGetNameReferenceCount() {
assertEquals(0, NodeUtil.getNameReferenceCount(
parse("function foo(){}"), "undefined"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("undefined"), "undefined"));
assertEquals(2, NodeUtil.getNameReferenceCount(
parse("undefined;function foo(){}(undefined)"), "undefined"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("goo.foo"), "goo"));
assertEquals(0, NodeUtil.getNameReferenceCount(
parse("goo.foo"), "foo"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("function foo(){}"), "foo"));
assertEquals(1, NodeUtil.getNameReferenceCount(
parse("var foo = function(){}"), "foo"));
}
public void testGetVarsDeclaredInBranch() {
Compiler compiler = new Compiler();
assertNodeNames(Sets.newHashSet("foo"),
NodeUtil.getVarsDeclaredInBranch(
parse("var foo;")));
assertNodeNames(Sets.newHashSet("foo","goo"),
NodeUtil.getVarsDeclaredInBranch(
parse("var foo,goo;")));
assertNodeNames(Sets.<String>newHashSet(),
NodeUtil.getVarsDeclaredInBranch(
parse("foo();")));
assertNodeNames(Sets.<String>newHashSet(),
NodeUtil.getVarsDeclaredInBranch(
parse("function(){var foo;}")));
assertNodeNames(Sets.newHashSet("goo"),
NodeUtil.getVarsDeclaredInBranch(
parse("var goo;function(){var foo;}")));
}
private void assertNodeNames(Set<String> nodeNames, Collection<Node> nodes) {
Set<String> actualNames = Sets.newHashSet();
for (Node node : nodes) {
actualNames.add(node.getString());
}
assertEquals(nodeNames, actualNames);
}
public void testIsControlStructureCodeBlock() {
Compiler compiler = new Compiler();
Node root = parse("if (x) foo(); else boo();");
Node ifNode = root.getFirstChild();
Node ifCondition = ifNode.getFirstChild();
Node ifCase = ifNode.getFirstChild().getNext();
Node elseCase = ifNode.getLastChild();
assertFalse(NodeUtil.isControlStructureCodeBlock(ifNode, ifCondition));
assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, ifCase));
assertTrue(NodeUtil.isControlStructureCodeBlock(ifNode, elseCase));
}
public void testIsFunctionExpression1() {
Compiler compiler = new Compiler();
Node root = parse("(function foo() {})");
Node StatementNode = root.getFirstChild();
assertTrue(NodeUtil.isExpressionNode(StatementNode));
Node functionNode = StatementNode.getFirstChild();
assertTrue(NodeUtil.isFunction(functionNode));
assertTrue(NodeUtil.isFunctionExpression(functionNode));
}
public void testIsFunctionExpression2() {
Compiler compiler = new Compiler();
Node root = parse("function foo() {}");
Node functionNode = root.getFirstChild();
assertTrue(NodeUtil.isFunction(functionNode));
assertFalse(NodeUtil.isFunctionExpression(functionNode));
}
public void testRemoveTryChild() {
Compiler compiler = new Compiler();
Node root = parse("try {foo()} catch(e) {} finally {}");
// Test removing the finally clause.
Node actual = root.cloneTree();
Node tryNode = actual.getFirstChild();
Node tryBlock = tryNode.getFirstChild();
Node catchBlocks = tryNode.getFirstChild().getNext();
Node finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(tryNode, finallyBlock);
String expected = "try {foo()} catch(e) {}";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the try clause.
actual = root.cloneTree();
tryNode = actual.getFirstChild();
tryBlock = tryNode.getFirstChild();
catchBlocks = tryNode.getFirstChild().getNext();
finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(tryNode, tryBlock);
expected = "try {} catch(e) {} finally {}";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the catch clause.
actual = root.cloneTree();
tryNode = actual.getFirstChild();
tryBlock = tryNode.getFirstChild();
catchBlocks = tryNode.getFirstChild().getNext();
Node catchBlock = catchBlocks.getFirstChild();
finallyBlock = tryNode.getLastChild();
NodeUtil.removeChild(catchBlocks, catchBlock);
expected = "try {foo()} finally {}";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveVarChild() {
Compiler compiler = new Compiler();
// Test removing the first child.
Node actual = parse("var foo, goo, hoo");
Node varNode = actual.getFirstChild();
Node nameNode = varNode.getFirstChild();
NodeUtil.removeChild(varNode, nameNode);
String expected = "var goo, hoo";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the second child.
actual = parse("var foo, goo, hoo");
varNode = actual.getFirstChild();
nameNode = varNode.getFirstChild().getNext();
NodeUtil.removeChild(varNode, nameNode);
expected = "var foo, hoo";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the last child of several children.
actual = parse("var foo, hoo");
varNode = actual.getFirstChild();
nameNode = varNode.getFirstChild().getNext();
NodeUtil.removeChild(varNode, nameNode);
expected = "var foo";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
// Test removing the last.
actual = parse("var hoo");
varNode = actual.getFirstChild();
nameNode = varNode.getFirstChild();
NodeUtil.removeChild(varNode, nameNode);
expected = "";
difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveLabelChild1() {
Compiler compiler = new Compiler();
// Test removing the first child.
Node actual = parse("foo: goo()");
Node labelNode = actual.getFirstChild();
Node callExpressNode = labelNode.getLastChild();
NodeUtil.removeChild(labelNode, callExpressNode);
String expected = "";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveLabelChild2() {
// Test removing the first child.
Node actual = parse("achoo: foo: goo()");
Node labelNode = actual.getFirstChild();
Node callExpressNode = labelNode.getLastChild();
NodeUtil.removeChild(labelNode, callExpressNode);
String expected = "";
String difference = parse(expected).checkTreeEquals(actual);
if (difference != null) {
assertTrue("Nodes do not match:\n" + difference, false);
}
}
public void testRemoveForChild() {
Compiler compiler = new Compiler();
// Test removing the initializer.
Node actual = parse("for(var a=0;a<0;a++)foo()");
Node forNode = actual.getFirstChild();
Node child = forNode.getFirstChild();
NodeUtil.removeChild(forNode, child);
String expected = "for(;a<0;a++)foo()";
String difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the condition.
actual = parse("for(var a=0;a<0;a++)foo()");
forNode = actual.getFirstChild();
child = forNode.getFirstChild().getNext();
NodeUtil.removeChild(forNode, child);
expected = "for(var a=0;;a++)foo()";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the increment.
actual = parse("for(var a=0;a<0;a++)foo()");
forNode = actual.getFirstChild();
child = forNode.getFirstChild().getNext().getNext();
NodeUtil.removeChild(forNode, child);
expected = "for(var a=0;a<0;)foo()";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the body.
actual = parse("for(var a=0;a<0;a++)foo()");
forNode = actual.getFirstChild();
child = forNode.getLastChild();
NodeUtil.removeChild(forNode, child);
expected = "for(var a=0;a<0;a++);";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
// Test removing the body.
actual = parse("for(a in ack)foo();");
forNode = actual.getFirstChild();
child = forNode.getLastChild();
NodeUtil.removeChild(forNode, child);
expected = "for(a in ack);";
difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
}
public void testMergeBlock1() {
Compiler compiler = new Compiler();
// Test removing the initializer.
Node actual = parse("{{a();b();}}");
Node parentBlock = actual.getFirstChild();
Node childBlock = parentBlock.getFirstChild();
assertTrue(NodeUtil.tryMergeBlock(childBlock));
String expected = "{a();b();}";
String difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
}
public void testMergeBlock2() {
Compiler compiler = new Compiler();
// Test removing the initializer.
Node actual = parse("foo:{a();}");
Node parentLabel = actual.getFirstChild();
Node childBlock = parentLabel.getLastChild();
assertFalse(NodeUtil.tryMergeBlock(childBlock));
}
public void testMergeBlock3() {
Compiler compiler = new Compiler();
// Test removing the initializer.
String code = "foo:{a();boo()}";
Node actual = parse("foo:{a();boo()}");
Node parentLabel = actual.getFirstChild();
Node childBlock = parentLabel.getLastChild();
assertFalse(NodeUtil.tryMergeBlock(childBlock));
String expected = code;
String difference = parse(expected).checkTreeEquals(actual);
assertNull("Nodes do not match:\n" + difference, difference);
}
public void testGetSourceName() {
Node n = new Node(Token.BLOCK);
Node parent = new Node(Token.BLOCK, n);
parent.putProp(Node.SOURCENAME_PROP, "foo");
assertEquals("foo", NodeUtil.getSourceName(n));
}
public void testIsLabelName() {
Compiler compiler = new Compiler();
// Test removing the initializer.
String code = "a:while(1) {a; continue a; break a; break;}";
Node actual = parse(code);
Node labelNode = actual.getFirstChild();
assertTrue(labelNode.getType() == Token.LABEL);
assertTrue(NodeUtil.isLabelName(labelNode.getFirstChild()));
assertFalse(NodeUtil.isLabelName(labelNode.getLastChild()));
Node whileNode = labelNode.getLastChild();
assertTrue(whileNode.getType() == Token.WHILE);
Node whileBlock = whileNode.getLastChild();
assertTrue(whileBlock.getType() == Token.BLOCK);
assertFalse(NodeUtil.isLabelName(whileBlock));
Node firstStatement = whileBlock.getFirstChild();
assertTrue(firstStatement.getType() == Token.EXPR_RESULT);
Node variableReference = firstStatement.getFirstChild();
assertTrue(variableReference.getType() == Token.NAME);
assertFalse(NodeUtil.isLabelName(variableReference));
Node continueStatement = firstStatement.getNext();
assertTrue(continueStatement.getType() == Token.CONTINUE);
assertTrue(NodeUtil.isLabelName(continueStatement.getFirstChild()));
Node firstBreak = continueStatement.getNext();
assertTrue(firstBreak.getType() == Token.BREAK);
assertTrue(NodeUtil.isLabelName(firstBreak.getFirstChild()));
Node secondBreak = firstBreak.getNext();
assertTrue(secondBreak.getType() == Token.BREAK);
assertFalse(secondBreak.hasChildren());
assertFalse(NodeUtil.isLabelName(secondBreak.getFirstChild()));
}
public void testLocalValue1() throws Exception {
// Names are not known to be local.
assertFalse(testLocalValue("x"));
assertFalse(testLocalValue("x()"));
assertFalse(testLocalValue("this"));
assertFalse(testLocalValue("arguments"));
// new objects are local
assertTrue(testLocalValue("new x()"));
// property references are assume to be non-local
assertFalse(testLocalValue("(new x()).y"));
assertFalse(testLocalValue("(new x())['y']"));
// Primitive values are local
assertTrue(testLocalValue("null"));
assertTrue(testLocalValue("undefined"));
assertTrue(testLocalValue("Infinity"));
assertTrue(testLocalValue("NaN"));
assertTrue(testLocalValue("1"));
assertTrue(testLocalValue("'a'"));
assertTrue(testLocalValue("true"));
assertTrue(testLocalValue("false"));
assertTrue(testLocalValue("[]"));
assertTrue(testLocalValue("{}"));
// The contents of arrays and objects don't matter
assertTrue(testLocalValue("[x]"));
assertTrue(testLocalValue("{'a':x}"));
// Pre-increment results in primitive number
assertTrue(testLocalValue("++x"));
assertTrue(testLocalValue("--x"));
// Post-increment, the previous value matters.
assertFalse(testLocalValue("x++"));
assertFalse(testLocalValue("x--"));
// The left side of an only assign matters if it is an alias or mutable.
assertTrue(testLocalValue("x=1"));
assertFalse(testLocalValue("x=[]"));
assertFalse(testLocalValue("x=y"));
// The right hand side of assignment opts don't matter, as they force
// a local result.
assertTrue(testLocalValue("x+=y"));
assertTrue(testLocalValue("x*=y"));
// Comparisons always result in locals, as they force a local boolean
// result.
assertTrue(testLocalValue("x==y"));
assertTrue(testLocalValue("x!=y"));
assertTrue(testLocalValue("x>y"));
// Only the right side of a comma matters
assertTrue(testLocalValue("(1,2)"));
assertTrue(testLocalValue("(x,1)"));
assertFalse(testLocalValue("(x,y)"));
// Both the operands of OR matter
assertTrue(testLocalValue("1||2"));
assertFalse(testLocalValue("x||1"));
assertFalse(testLocalValue("x||y"));
assertFalse(testLocalValue("1||y"));
// Both the operands of AND matter
assertTrue(testLocalValue("1&&2"));
assertFalse(testLocalValue("x&&1"));
assertFalse(testLocalValue("x&&y"));
assertFalse(testLocalValue("1&&y"));
// Only the results of HOOK matter
assertTrue(testLocalValue("x?1:2"));
assertFalse(testLocalValue("x?x:2"));
assertFalse(testLocalValue("x?1:x"));
assertFalse(testLocalValue("x?x:y"));
// Results of ops are local values
assertTrue(testLocalValue("!y"));
assertTrue(testLocalValue("~y"));
assertTrue(testLocalValue("y + 1"));
assertTrue(testLocalValue("y + z"));
assertTrue(testLocalValue("y * z"));
assertTrue(testLocalValue("'a' in x"));
assertTrue(testLocalValue("typeof x"));
assertTrue(testLocalValue("x instanceof y"));
assertTrue(testLocalValue("void x"));
assertTrue(testLocalValue("void 0"));
assertFalse(testLocalValue("{}.x"));
}
private boolean testLocalValue(String js) {
Node script = parse("var test = " + js +";");
Preconditions.checkState(script.getType() == Token.SCRIPT);
Node var = script.getFirstChild();
Preconditions.checkState(var.getType() == Token.VAR);
Node name = var.getFirstChild();
Preconditions.checkState(name.getType() == Token.NAME);
Node value = name.getFirstChild();
return NodeUtil.evaluatesToLocalValue(value);
}
public void testValidDefine() {
assertTrue(testValidDefineValue("1"));
assertTrue(testValidDefineValue("-3"));
assertTrue(testValidDefineValue("true"));
assertTrue(testValidDefineValue("false"));
assertTrue(testValidDefineValue("'foo'"));
assertFalse(testValidDefineValue("x"));
assertFalse(testValidDefineValue("null"));
assertFalse(testValidDefineValue("undefined"));
assertFalse(testValidDefineValue("NaN"));
assertTrue(testValidDefineValue("!true"));
assertTrue(testValidDefineValue("-true"));
assertTrue(testValidDefineValue("1 & 8"));
assertTrue(testValidDefineValue("1 + 8"));
assertTrue(testValidDefineValue("'a' + 'b'"));
assertFalse(testValidDefineValue("1 & foo"));
}
private boolean testValidDefineValue(String js) {
Node script = parse("var test = " + js +";");
Node var = script.getFirstChild();
Node name = var.getFirstChild();
Node value = name.getFirstChild();
ImmutableSet<String> defines = ImmutableSet.of();
return NodeUtil.isValidDefineValue(value, defines);
}
} |
||
@Test
public void testCrossProductCancellation() {
Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
checkVector(Vector3D.crossProduct(v1, v2), -1, 2, 1);
double scale = FastMath.scalb(1.0, 100);
Vector3D big1 = new Vector3D(scale, v1);
Vector3D small2 = new Vector3D(1 / scale, v2);
checkVector(Vector3D.crossProduct(big1, small2), -1, 2, 1);
} | org.apache.commons.math.geometry.Vector3DTest::testCrossProductCancellation | src/test/java/org/apache/commons/math/geometry/Vector3DTest.java | 165 | src/test/java/org/apache/commons/math/geometry/Vector3DTest.java | testCrossProductCancellation | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.geometry;
import org.apache.commons.math.geometry.Vector3D;
import org.apache.commons.math.util.FastMath;
import org.apache.commons.math.exception.MathArithmeticException;
import org.junit.Assert;
import org.junit.Test;
public class Vector3DTest {
@Test
public void testConstructors() {
double r = FastMath.sqrt(2) /2;
checkVector(new Vector3D(2, new Vector3D(FastMath.PI / 3, -FastMath.PI / 4)),
r, r * FastMath.sqrt(3), -2 * r);
checkVector(new Vector3D(2, Vector3D.PLUS_I,
-3, Vector3D.MINUS_K),
2, 0, 3);
checkVector(new Vector3D(2, Vector3D.PLUS_I,
5, Vector3D.PLUS_J,
-3, Vector3D.MINUS_K),
2, 5, 3);
checkVector(new Vector3D(2, Vector3D.PLUS_I,
5, Vector3D.PLUS_J,
5, Vector3D.MINUS_J,
-3, Vector3D.MINUS_K),
2, 0, 3);
}
@Test
public void testCoordinates() {
Vector3D v = new Vector3D(1, 2, 3);
Assert.assertTrue(FastMath.abs(v.getX() - 1) < 1.0e-12);
Assert.assertTrue(FastMath.abs(v.getY() - 2) < 1.0e-12);
Assert.assertTrue(FastMath.abs(v.getZ() - 3) < 1.0e-12);
}
@Test
public void testNorm1() {
Assert.assertEquals(0.0, Vector3D.ZERO.getNorm1(), 0);
Assert.assertEquals(6.0, new Vector3D(1, -2, 3).getNorm1(), 0);
}
@Test
public void testNorm() {
Assert.assertEquals(0.0, Vector3D.ZERO.getNorm(), 0);
Assert.assertEquals(FastMath.sqrt(14), new Vector3D(1, 2, 3).getNorm(), 1.0e-12);
}
@Test
public void testNormInf() {
Assert.assertEquals(0.0, Vector3D.ZERO.getNormInf(), 0);
Assert.assertEquals(3.0, new Vector3D(1, -2, 3).getNormInf(), 0);
}
@Test
public void testDistance1() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distance1(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(12.0, Vector3D.distance1(v1, v2), 1.0e-12);
Assert.assertEquals(v1.subtract(v2).getNorm1(), Vector3D.distance1(v1, v2), 1.0e-12);
}
@Test
public void testDistance() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distance(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(FastMath.sqrt(50), Vector3D.distance(v1, v2), 1.0e-12);
Assert.assertEquals(v1.subtract(v2).getNorm(), Vector3D.distance(v1, v2), 1.0e-12);
}
@Test
public void testDistanceSq() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distanceSq(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(50.0, Vector3D.distanceSq(v1, v2), 1.0e-12);
Assert.assertEquals(Vector3D.distance(v1, v2) * Vector3D.distance(v1, v2),
Vector3D.distanceSq(v1, v2), 1.0e-12);
}
@Test
public void testDistanceInf() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distanceInf(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(5.0, Vector3D.distanceInf(v1, v2), 1.0e-12);
Assert.assertEquals(v1.subtract(v2).getNormInf(), Vector3D.distanceInf(v1, v2), 1.0e-12);
}
@Test
public void testSubtract() {
Vector3D v1 = new Vector3D(1, 2, 3);
Vector3D v2 = new Vector3D(-3, -2, -1);
v1 = v1.subtract(v2);
checkVector(v1, 4, 4, 4);
checkVector(v2.subtract(v1), -7, -6, -5);
checkVector(v2.subtract(3, v1), -15, -14, -13);
}
@Test
public void testAdd() {
Vector3D v1 = new Vector3D(1, 2, 3);
Vector3D v2 = new Vector3D(-3, -2, -1);
v1 = v1.add(v2);
checkVector(v1, -2, 0, 2);
checkVector(v2.add(v1), -5, -2, 1);
checkVector(v2.add(3, v1), -9, -2, 5);
}
@Test
public void testScalarProduct() {
Vector3D v = new Vector3D(1, 2, 3);
v = v.scalarMultiply(3);
checkVector(v, 3, 6, 9);
checkVector(v.scalarMultiply(0.5), 1.5, 3, 4.5);
}
@Test
public void testVectorialProducts() {
Vector3D v1 = new Vector3D(2, 1, -4);
Vector3D v2 = new Vector3D(3, 1, -1);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(v1, v2) - 11) < 1.0e-12);
Vector3D v3 = Vector3D.crossProduct(v1, v2);
checkVector(v3, 3, -10, -1);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(v1, v3)) < 1.0e-12);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(v2, v3)) < 1.0e-12);
}
@Test
public void testCrossProductCancellation() {
Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
checkVector(Vector3D.crossProduct(v1, v2), -1, 2, 1);
double scale = FastMath.scalb(1.0, 100);
Vector3D big1 = new Vector3D(scale, v1);
Vector3D small2 = new Vector3D(1 / scale, v2);
checkVector(Vector3D.crossProduct(big1, small2), -1, 2, 1);
}
@Test
public void testAngular() {
Assert.assertEquals(0, Vector3D.PLUS_I.getAlpha(), 1.0e-10);
Assert.assertEquals(0, Vector3D.PLUS_I.getDelta(), 1.0e-10);
Assert.assertEquals(FastMath.PI / 2, Vector3D.PLUS_J.getAlpha(), 1.0e-10);
Assert.assertEquals(0, Vector3D.PLUS_J.getDelta(), 1.0e-10);
Assert.assertEquals(0, Vector3D.PLUS_K.getAlpha(), 1.0e-10);
Assert.assertEquals(FastMath.PI / 2, Vector3D.PLUS_K.getDelta(), 1.0e-10);
Vector3D u = new Vector3D(-1, 1, -1);
Assert.assertEquals(3 * FastMath.PI /4, u.getAlpha(), 1.0e-10);
Assert.assertEquals(-1.0 / FastMath.sqrt(3), FastMath.sin(u.getDelta()), 1.0e-10);
}
@Test
public void testAngularSeparation() {
Vector3D v1 = new Vector3D(2, -1, 4);
Vector3D k = v1.normalize();
Vector3D i = k.orthogonal();
Vector3D v2 = k.scalarMultiply(FastMath.cos(1.2)).add(i.scalarMultiply(FastMath.sin(1.2)));
Assert.assertTrue(FastMath.abs(Vector3D.angle(v1, v2) - 1.2) < 1.0e-12);
}
@Test
public void testNormalize() {
Assert.assertEquals(1.0, new Vector3D(5, -4, 2).normalize().getNorm(), 1.0e-12);
try {
Vector3D.ZERO.normalize();
Assert.fail("an exception should have been thrown");
} catch (MathArithmeticException ae) {
// expected behavior
}
}
@Test
public void testOrthogonal() {
Vector3D v1 = new Vector3D(0.1, 2.5, 1.3);
Assert.assertEquals(0.0, Vector3D.dotProduct(v1, v1.orthogonal()), 1.0e-12);
Vector3D v2 = new Vector3D(2.3, -0.003, 7.6);
Assert.assertEquals(0.0, Vector3D.dotProduct(v2, v2.orthogonal()), 1.0e-12);
Vector3D v3 = new Vector3D(-1.7, 1.4, 0.2);
Assert.assertEquals(0.0, Vector3D.dotProduct(v3, v3.orthogonal()), 1.0e-12);
try {
new Vector3D(0, 0, 0).orthogonal();
Assert.fail("an exception should have been thrown");
} catch (MathArithmeticException ae) {
// expected behavior
}
}
@Test
public void testAngle() {
Assert.assertEquals(0.22572612855273393616,
Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(4, 5, 6)),
1.0e-12);
Assert.assertEquals(7.98595620686106654517199e-8,
Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(2, 4, 6.000001)),
1.0e-12);
Assert.assertEquals(3.14159257373023116985197793156,
Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(-2, -4, -6.000001)),
1.0e-12);
try {
Vector3D.angle(Vector3D.ZERO, Vector3D.PLUS_I);
Assert.fail("an exception should have been thrown");
} catch (MathArithmeticException ae) {
// expected behavior
}
}
private void checkVector(Vector3D v, double x, double y, double z) {
Assert.assertEquals(x, v.getX(), 1.0e-12);
Assert.assertEquals(y, v.getY(), 1.0e-12);
Assert.assertEquals(z, v.getZ(), 1.0e-12);
}
} | // You are a professional Java test case writer, please create a test case named `testCrossProductCancellation` for the issue `Math-MATH-554`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-554
//
// ## Issue-Title:
// Vector3D.crossProduct is sensitive to numerical cancellation
//
// ## Issue-Description:
//
// Cross product implementation uses the naive formulas (y1 z2 - y2 z1, ...). These formulas fail when vectors are almost colinear, like in the following example:
//
//
//
//
// ```
// Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
// Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
// System.out.println(Vector3D.crossProduct(v1, v2));
//
// ```
//
//
// The previous code displays
//
//
// { -1, 2, 0 }
// instead of the correct answer
//
//
// { -1, 2, 1 }
//
//
//
@Test
public void testCrossProductCancellation() {
| 165 | 55 | 154 | src/test/java/org/apache/commons/math/geometry/Vector3DTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-554
## Issue-Title:
Vector3D.crossProduct is sensitive to numerical cancellation
## Issue-Description:
Cross product implementation uses the naive formulas (y1 z2 - y2 z1, ...). These formulas fail when vectors are almost colinear, like in the following example:
```
Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
System.out.println(Vector3D.crossProduct(v1, v2));
```
The previous code displays
{ -1, 2, 0 }
instead of the correct answer
{ -1, 2, 1 }
```
You are a professional Java test case writer, please create a test case named `testCrossProductCancellation` for the issue `Math-MATH-554`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testCrossProductCancellation() {
```
| 154 | [
"org.apache.commons.math.geometry.Vector3D"
] | 5779bde6ee18d450226a96e12a75fc5e8261970311eed8e29094b77715d33cf5 | @Test
public void testCrossProductCancellation() | // You are a professional Java test case writer, please create a test case named `testCrossProductCancellation` for the issue `Math-MATH-554`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-554
//
// ## Issue-Title:
// Vector3D.crossProduct is sensitive to numerical cancellation
//
// ## Issue-Description:
//
// Cross product implementation uses the naive formulas (y1 z2 - y2 z1, ...). These formulas fail when vectors are almost colinear, like in the following example:
//
//
//
//
// ```
// Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
// Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
// System.out.println(Vector3D.crossProduct(v1, v2));
//
// ```
//
//
// The previous code displays
//
//
// { -1, 2, 0 }
// instead of the correct answer
//
//
// { -1, 2, 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.geometry;
import org.apache.commons.math.geometry.Vector3D;
import org.apache.commons.math.util.FastMath;
import org.apache.commons.math.exception.MathArithmeticException;
import org.junit.Assert;
import org.junit.Test;
public class Vector3DTest {
@Test
public void testConstructors() {
double r = FastMath.sqrt(2) /2;
checkVector(new Vector3D(2, new Vector3D(FastMath.PI / 3, -FastMath.PI / 4)),
r, r * FastMath.sqrt(3), -2 * r);
checkVector(new Vector3D(2, Vector3D.PLUS_I,
-3, Vector3D.MINUS_K),
2, 0, 3);
checkVector(new Vector3D(2, Vector3D.PLUS_I,
5, Vector3D.PLUS_J,
-3, Vector3D.MINUS_K),
2, 5, 3);
checkVector(new Vector3D(2, Vector3D.PLUS_I,
5, Vector3D.PLUS_J,
5, Vector3D.MINUS_J,
-3, Vector3D.MINUS_K),
2, 0, 3);
}
@Test
public void testCoordinates() {
Vector3D v = new Vector3D(1, 2, 3);
Assert.assertTrue(FastMath.abs(v.getX() - 1) < 1.0e-12);
Assert.assertTrue(FastMath.abs(v.getY() - 2) < 1.0e-12);
Assert.assertTrue(FastMath.abs(v.getZ() - 3) < 1.0e-12);
}
@Test
public void testNorm1() {
Assert.assertEquals(0.0, Vector3D.ZERO.getNorm1(), 0);
Assert.assertEquals(6.0, new Vector3D(1, -2, 3).getNorm1(), 0);
}
@Test
public void testNorm() {
Assert.assertEquals(0.0, Vector3D.ZERO.getNorm(), 0);
Assert.assertEquals(FastMath.sqrt(14), new Vector3D(1, 2, 3).getNorm(), 1.0e-12);
}
@Test
public void testNormInf() {
Assert.assertEquals(0.0, Vector3D.ZERO.getNormInf(), 0);
Assert.assertEquals(3.0, new Vector3D(1, -2, 3).getNormInf(), 0);
}
@Test
public void testDistance1() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distance1(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(12.0, Vector3D.distance1(v1, v2), 1.0e-12);
Assert.assertEquals(v1.subtract(v2).getNorm1(), Vector3D.distance1(v1, v2), 1.0e-12);
}
@Test
public void testDistance() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distance(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(FastMath.sqrt(50), Vector3D.distance(v1, v2), 1.0e-12);
Assert.assertEquals(v1.subtract(v2).getNorm(), Vector3D.distance(v1, v2), 1.0e-12);
}
@Test
public void testDistanceSq() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distanceSq(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(50.0, Vector3D.distanceSq(v1, v2), 1.0e-12);
Assert.assertEquals(Vector3D.distance(v1, v2) * Vector3D.distance(v1, v2),
Vector3D.distanceSq(v1, v2), 1.0e-12);
}
@Test
public void testDistanceInf() {
Vector3D v1 = new Vector3D(1, -2, 3);
Vector3D v2 = new Vector3D(-4, 2, 0);
Assert.assertEquals(0.0, Vector3D.distanceInf(Vector3D.MINUS_I, Vector3D.MINUS_I), 0);
Assert.assertEquals(5.0, Vector3D.distanceInf(v1, v2), 1.0e-12);
Assert.assertEquals(v1.subtract(v2).getNormInf(), Vector3D.distanceInf(v1, v2), 1.0e-12);
}
@Test
public void testSubtract() {
Vector3D v1 = new Vector3D(1, 2, 3);
Vector3D v2 = new Vector3D(-3, -2, -1);
v1 = v1.subtract(v2);
checkVector(v1, 4, 4, 4);
checkVector(v2.subtract(v1), -7, -6, -5);
checkVector(v2.subtract(3, v1), -15, -14, -13);
}
@Test
public void testAdd() {
Vector3D v1 = new Vector3D(1, 2, 3);
Vector3D v2 = new Vector3D(-3, -2, -1);
v1 = v1.add(v2);
checkVector(v1, -2, 0, 2);
checkVector(v2.add(v1), -5, -2, 1);
checkVector(v2.add(3, v1), -9, -2, 5);
}
@Test
public void testScalarProduct() {
Vector3D v = new Vector3D(1, 2, 3);
v = v.scalarMultiply(3);
checkVector(v, 3, 6, 9);
checkVector(v.scalarMultiply(0.5), 1.5, 3, 4.5);
}
@Test
public void testVectorialProducts() {
Vector3D v1 = new Vector3D(2, 1, -4);
Vector3D v2 = new Vector3D(3, 1, -1);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(v1, v2) - 11) < 1.0e-12);
Vector3D v3 = Vector3D.crossProduct(v1, v2);
checkVector(v3, 3, -10, -1);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(v1, v3)) < 1.0e-12);
Assert.assertTrue(FastMath.abs(Vector3D.dotProduct(v2, v3)) < 1.0e-12);
}
@Test
public void testCrossProductCancellation() {
Vector3D v1 = new Vector3D(9070467121.0, 4535233560.0, 1);
Vector3D v2 = new Vector3D(9070467123.0, 4535233561.0, 1);
checkVector(Vector3D.crossProduct(v1, v2), -1, 2, 1);
double scale = FastMath.scalb(1.0, 100);
Vector3D big1 = new Vector3D(scale, v1);
Vector3D small2 = new Vector3D(1 / scale, v2);
checkVector(Vector3D.crossProduct(big1, small2), -1, 2, 1);
}
@Test
public void testAngular() {
Assert.assertEquals(0, Vector3D.PLUS_I.getAlpha(), 1.0e-10);
Assert.assertEquals(0, Vector3D.PLUS_I.getDelta(), 1.0e-10);
Assert.assertEquals(FastMath.PI / 2, Vector3D.PLUS_J.getAlpha(), 1.0e-10);
Assert.assertEquals(0, Vector3D.PLUS_J.getDelta(), 1.0e-10);
Assert.assertEquals(0, Vector3D.PLUS_K.getAlpha(), 1.0e-10);
Assert.assertEquals(FastMath.PI / 2, Vector3D.PLUS_K.getDelta(), 1.0e-10);
Vector3D u = new Vector3D(-1, 1, -1);
Assert.assertEquals(3 * FastMath.PI /4, u.getAlpha(), 1.0e-10);
Assert.assertEquals(-1.0 / FastMath.sqrt(3), FastMath.sin(u.getDelta()), 1.0e-10);
}
@Test
public void testAngularSeparation() {
Vector3D v1 = new Vector3D(2, -1, 4);
Vector3D k = v1.normalize();
Vector3D i = k.orthogonal();
Vector3D v2 = k.scalarMultiply(FastMath.cos(1.2)).add(i.scalarMultiply(FastMath.sin(1.2)));
Assert.assertTrue(FastMath.abs(Vector3D.angle(v1, v2) - 1.2) < 1.0e-12);
}
@Test
public void testNormalize() {
Assert.assertEquals(1.0, new Vector3D(5, -4, 2).normalize().getNorm(), 1.0e-12);
try {
Vector3D.ZERO.normalize();
Assert.fail("an exception should have been thrown");
} catch (MathArithmeticException ae) {
// expected behavior
}
}
@Test
public void testOrthogonal() {
Vector3D v1 = new Vector3D(0.1, 2.5, 1.3);
Assert.assertEquals(0.0, Vector3D.dotProduct(v1, v1.orthogonal()), 1.0e-12);
Vector3D v2 = new Vector3D(2.3, -0.003, 7.6);
Assert.assertEquals(0.0, Vector3D.dotProduct(v2, v2.orthogonal()), 1.0e-12);
Vector3D v3 = new Vector3D(-1.7, 1.4, 0.2);
Assert.assertEquals(0.0, Vector3D.dotProduct(v3, v3.orthogonal()), 1.0e-12);
try {
new Vector3D(0, 0, 0).orthogonal();
Assert.fail("an exception should have been thrown");
} catch (MathArithmeticException ae) {
// expected behavior
}
}
@Test
public void testAngle() {
Assert.assertEquals(0.22572612855273393616,
Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(4, 5, 6)),
1.0e-12);
Assert.assertEquals(7.98595620686106654517199e-8,
Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(2, 4, 6.000001)),
1.0e-12);
Assert.assertEquals(3.14159257373023116985197793156,
Vector3D.angle(new Vector3D(1, 2, 3), new Vector3D(-2, -4, -6.000001)),
1.0e-12);
try {
Vector3D.angle(Vector3D.ZERO, Vector3D.PLUS_I);
Assert.fail("an exception should have been thrown");
} catch (MathArithmeticException ae) {
// expected behavior
}
}
private void checkVector(Vector3D v, double x, double y, double z) {
Assert.assertEquals(x, v.getX(), 1.0e-12);
Assert.assertEquals(y, v.getY(), 1.0e-12);
Assert.assertEquals(z, v.getZ(), 1.0e-12);
}
} |
||
@Test
public void testEscapeSurrogatePairs() throws Exception {
assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
// Examples from https://en.wikipedia.org/wiki/UTF-16
assertEquals("\uD800\uDC00", StringEscapeUtils.escapeCsv("\uD800\uDC00"));
assertEquals("\uD834\uDD1E", StringEscapeUtils.escapeCsv("\uD834\uDD1E"));
assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeCsv("\uDBFF\uDFFD"));
} | org.apache.commons.lang3.StringUtilsTest::testEscapeSurrogatePairs | src/test/java/org/apache/commons/lang3/StringUtilsTest.java | 2,192 | src/test/java/org/apache/commons/lang3/StringUtilsTest.java | testEscapeSurrogatePairs | /*
* 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 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.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import org.apache.commons.lang3.text.WordUtils;
import org.junit.Test;
/**
* Unit tests {@link org.apache.commons.lang3.StringUtils}.
*
* @version $Id$
*/
public class StringUtilsTest {
static final String WHITESPACE;
static final String NON_WHITESPACE;
static final String TRIMMABLE;
static final String NON_TRIMMABLE;
static {
String ws = "";
String nws = "";
String tr = "";
String ntr = "";
for (int i = 0; i < Character.MAX_VALUE; i++) {
if (Character.isWhitespace((char) i)) {
ws += String.valueOf((char) i);
if (i > 32) {
ntr += String.valueOf((char) i);
}
} else if (i < 40) {
nws += String.valueOf((char) i);
}
}
for (int i = 0; i <= 32; i++) {
tr += String.valueOf((char) i);
}
WHITESPACE = ws;
NON_WHITESPACE = nws;
TRIMMABLE = tr;
NON_TRIMMABLE = ntr;
}
private static final String[] ARRAY_LIST = { "foo", "bar", "baz" };
private static final String[] EMPTY_ARRAY_LIST = {};
private static final String[] NULL_ARRAY_LIST = {null};
private static final Object[] NULL_TO_STRING_LIST = {
new Object(){
@Override
public String toString() {
return null;
}
}
};
private static final String[] MIXED_ARRAY_LIST = {null, "", "foo"};
private static final Object[] MIXED_TYPE_LIST = {"foo", Long.valueOf(2L)};
private static final long[] LONG_PRIM_LIST = {1, 2};
private static final int[] INT_PRIM_LIST = {1, 2};
private static final byte[] BYTE_PRIM_LIST = {1, 2};
private static final short[] SHORT_PRIM_LIST = {1, 2};
private static final char[] CHAR_PRIM_LIST = {'1', '2'};
private static final float[] FLOAT_PRIM_LIST = {1, 2};
private static final double[] DOUBLE_PRIM_LIST = {1, 2};
private static final String SEPARATOR = ",";
private static final char SEPARATOR_CHAR = ';';
private static final String TEXT_LIST = "foo,bar,baz";
private static final String TEXT_LIST_CHAR = "foo;bar;baz";
private static final String TEXT_LIST_NOSEP = "foobarbaz";
private static final String FOO_UNCAP = "foo";
private static final String FOO_CAP = "Foo";
private static final String SENTENCE_UNCAP = "foo bar baz";
private static final String SENTENCE_CAP = "Foo Bar Baz";
//-----------------------------------------------------------------------
@Test
public void testConstructor() {
assertNotNull(new StringUtils());
Constructor<?>[] cons = StringUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertTrue(Modifier.isPublic(cons[0].getModifiers()));
assertTrue(Modifier.isPublic(StringUtils.class.getModifiers()));
assertFalse(Modifier.isFinal(StringUtils.class.getModifiers()));
}
//-----------------------------------------------------------------------
@Test
public void testCaseFunctions() {
assertEquals(null, StringUtils.upperCase(null));
assertEquals(null, StringUtils.upperCase(null, Locale.ENGLISH));
assertEquals(null, StringUtils.lowerCase(null));
assertEquals(null, StringUtils.lowerCase(null, Locale.ENGLISH));
assertEquals(null, StringUtils.capitalize(null));
assertEquals(null, StringUtils.uncapitalize(null));
assertEquals("capitalize(empty-string) failed",
"", StringUtils.capitalize("") );
assertEquals("capitalize(single-char-string) failed",
"X", StringUtils.capitalize("x") );
assertEquals("uncapitalize(String) failed",
FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) );
assertEquals("uncapitalize(empty-string) failed",
"", StringUtils.uncapitalize("") );
assertEquals("uncapitalize(single-char-string) failed",
"x", StringUtils.uncapitalize("X") );
// reflection type of tests: Sentences.
assertEquals("uncapitalize(capitalize(String)) failed",
SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP)) );
assertEquals("capitalize(uncapitalize(String)) failed",
SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)) );
// reflection type of tests: One word.
assertEquals("uncapitalize(capitalize(String)) failed",
FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP)) );
assertEquals("capitalize(uncapitalize(String)) failed",
FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)) );
assertEquals("upperCase(String) failed",
"FOO TEST THING", StringUtils.upperCase("fOo test THING") );
assertEquals("upperCase(empty-string) failed",
"", StringUtils.upperCase("") );
assertEquals("lowerCase(String) failed",
"foo test thing", StringUtils.lowerCase("fOo test THING") );
assertEquals("lowerCase(empty-string) failed",
"", StringUtils.lowerCase("") );
assertEquals("upperCase(String, Locale) failed",
"FOO TEST THING", StringUtils.upperCase("fOo test THING", Locale.ENGLISH) );
assertEquals("upperCase(empty-string, Locale) failed",
"", StringUtils.upperCase("", Locale.ENGLISH) );
assertEquals("lowerCase(String, Locale) failed",
"foo test thing", StringUtils.lowerCase("fOo test THING", Locale.ENGLISH) );
assertEquals("lowerCase(empty-string, Locale) failed",
"", StringUtils.lowerCase("", Locale.ENGLISH) );
}
@Test
public void testSwapCase_String() {
assertEquals(null, StringUtils.swapCase(null));
assertEquals("", StringUtils.swapCase(""));
assertEquals(" ", StringUtils.swapCase(" "));
assertEquals("i", WordUtils.swapCase("I") );
assertEquals("I", WordUtils.swapCase("i") );
assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123") );
assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123") );
assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") );
assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") );
String test = "This String contains a TitleCase character: \u01C8";
String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
assertEquals(expect, WordUtils.swapCase(test));
}
//-----------------------------------------------------------------------
@Test
public void testJoin_Objects() {
assertEquals("abc", StringUtils.join("a", "b", "c"));
assertEquals("a", StringUtils.join(null, "", "a"));
assertEquals(null, StringUtils.join((Object[])null));
}
@Test
public void testJoin_Objectarray() {
// assertEquals(null, StringUtils.join(null)); // generates warning
assertEquals(null, StringUtils.join((Object[]) null)); // equivalent explicit cast
// test additional varargs calls
assertEquals("", StringUtils.join()); // empty array
assertEquals("", StringUtils.join((Object) null)); // => new Object[]{null}
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST));
assertEquals("", StringUtils.join(NULL_ARRAY_LIST));
assertEquals("null", StringUtils.join(NULL_TO_STRING_LIST));
assertEquals("abc", StringUtils.join(new String[] {"a", "b", "c"}));
assertEquals("a", StringUtils.join(new String[] {null, "a", ""}));
assertEquals("foo", StringUtils.join(MIXED_ARRAY_LIST));
assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST));
}
@Test
public void testJoin_ArrayCharSeparator() {
assertEquals(null, StringUtils.join((Object[]) null, ','));
assertEquals(TEXT_LIST_CHAR, StringUtils.join(ARRAY_LIST, SEPARATOR_CHAR));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR_CHAR));
assertEquals(";;foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR_CHAR));
assertEquals("foo;2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR_CHAR));
assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, '/', 0, MIXED_ARRAY_LIST.length-1));
assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 1));
assertEquals("null", StringUtils.join(NULL_TO_STRING_LIST,'/', 0, 1));
assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 2));
assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, '/', 1, 2));
assertEquals("", StringUtils.join(MIXED_TYPE_LIST, '/', 2, 1));
}
@Test
public void testJoin_ArrayOfChars() {
assertEquals(null, StringUtils.join((char[]) null, ','));
assertEquals("1;2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfBytes() {
assertEquals(null, StringUtils.join((byte[]) null, ','));
assertEquals("1;2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfInts() {
assertEquals(null, StringUtils.join((int[]) null, ','));
assertEquals("1;2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfLongs() {
assertEquals(null, StringUtils.join((long[]) null, ','));
assertEquals("1;2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfFloats() {
assertEquals(null, StringUtils.join((float[]) null, ','));
assertEquals("1.0;2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfDoubles() {
assertEquals(null, StringUtils.join((double[]) null, ','));
assertEquals("1.0;2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfShorts() {
assertEquals(null, StringUtils.join((short[]) null, ','));
assertEquals("1;2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayString() {
assertEquals(null, StringUtils.join((Object[]) null, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, ""));
assertEquals("", StringUtils.join(NULL_ARRAY_LIST, null));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, null));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, ""));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR));
assertEquals(TEXT_LIST, StringUtils.join(ARRAY_LIST, SEPARATOR));
assertEquals(",,foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR));
assertEquals("foo,2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR));
assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, "/", 0, MIXED_ARRAY_LIST.length-1));
assertEquals("", StringUtils.join(MIXED_ARRAY_LIST, "", 0, MIXED_ARRAY_LIST.length-1));
assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, "/", 0, 1));
assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, "/", 0, 2));
assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, "/", 1, 2));
assertEquals("", StringUtils.join(MIXED_TYPE_LIST, "/", 2, 1));
}
@Test
public void testJoin_IteratorChar() {
assertEquals(null, StringUtils.join((Iterator<?>) null, ','));
assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR_CHAR));
assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), 'x'));
}
@Test
public void testJoin_IteratorString() {
assertEquals(null, StringUtils.join((Iterator<?>) null, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), ""));
assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), "x"));
assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), null));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), ""));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR));
assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR));
}
@Test
public void testJoin_IterableChar() {
assertEquals(null, StringUtils.join((Iterable<?>) null, ','));
assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR_CHAR));
assertEquals("foo", StringUtils.join(Collections.singleton("foo"), 'x'));
}
@Test
public void testJoin_IterableString() {
assertEquals(null, StringUtils.join((Iterable<?>) null, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), ""));
assertEquals("foo", StringUtils.join(Collections.singleton("foo"), "x"));
assertEquals("foo", StringUtils.join(Collections.singleton("foo"), null));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), ""));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR));
assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR));
}
@Test
public void testSplit_String() {
assertArrayEquals(null, StringUtils.split(null));
assertEquals(0, StringUtils.split("").length);
String str = "a b .c";
String[] res = StringUtils.split(str);
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(".c", res[2]);
str = " a ";
res = StringUtils.split(str);
assertEquals(1, res.length);
assertEquals("a", res[0]);
str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c";
res = StringUtils.split(str);
assertEquals(2, res.length);
assertEquals("a", res[0]);
assertEquals("b" + NON_WHITESPACE + "c", res[1]);
}
@Test
public void testSplit_StringChar() {
assertArrayEquals(null, StringUtils.split(null, '.'));
assertEquals(0, StringUtils.split("", '.').length);
String str = "a.b.. c";
String[] res = StringUtils.split(str, '.');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(" c", res[2]);
str = ".a.";
res = StringUtils.split(str, '.');
assertEquals(1, res.length);
assertEquals("a", res[0]);
str = "a b c";
res = StringUtils.split(str,' ');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
}
@Test
public void testSplit_StringString_StringStringInt() {
assertArrayEquals(null, StringUtils.split(null, "."));
assertArrayEquals(null, StringUtils.split(null, ".", 3));
assertEquals(0, StringUtils.split("", ".").length);
assertEquals(0, StringUtils.split("", ".", 3).length);
innerTestSplit('.', ".", ' ');
innerTestSplit('.', ".", ',');
innerTestSplit('.', ".,", 'x');
for (int i = 0; i < WHITESPACE.length(); i++) {
for (int j = 0; j < NON_WHITESPACE.length(); j++) {
innerTestSplit(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j));
innerTestSplit(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j));
}
}
String[] results;
String[] expectedResults = {"ab", "de fg"};
results = StringUtils.split("ab de fg", null, 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
String[] expectedResults2 = {"ab", "cd:ef"};
results = StringUtils.split("ab:cd:ef",":", 2);
assertEquals(expectedResults2.length, results.length);
for (int i = 0; i < expectedResults2.length; i++) {
assertEquals(expectedResults2[i], results[i]);
}
}
private void innerTestSplit(char separator, String sepStr, char noMatch) {
String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
"), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
final String str = "a" + separator + "b" + separator + separator + noMatch + "c";
String[] res;
// (str, sepStr)
res = StringUtils.split(str, sepStr);
assertEquals(msg, 3, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, noMatch + "c", res[2]);
final String str2 = separator + "a" + separator;
res = StringUtils.split(str2, sepStr);
assertEquals(msg, 1, res.length);
assertEquals(msg, "a", res[0]);
res = StringUtils.split(str, sepStr, -1);
assertEquals(msg, 3, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, noMatch + "c", res[2]);
res = StringUtils.split(str, sepStr, 0);
assertEquals(msg, 3, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, noMatch + "c", res[2]);
res = StringUtils.split(str, sepStr, 1);
assertEquals(msg, 1, res.length);
assertEquals(msg, str, res[0]);
res = StringUtils.split(str, sepStr, 2);
assertEquals(msg, 2, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, str.substring(2), res[1]);
}
@Test
public void testSplitByWholeString_StringStringBoolean() {
assertArrayEquals( null, StringUtils.splitByWholeSeparator( null, "." ) ) ;
assertEquals( 0, StringUtils.splitByWholeSeparator( "", "." ).length ) ;
String stringToSplitOnNulls = "ab de fg" ;
String[] splitOnNullExpectedResults = { "ab", "de", "fg" } ;
String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null ) ;
assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
}
String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously" ;
String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy" ) ;
assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i+= 1 ) {
assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
}
String[] splitWithMultipleSeparatorExpectedResults = {"ab", "cd", "ef"};
String[] splitWithMultipleSeparator = StringUtils.splitByWholeSeparator("ab:cd::ef", ":");
assertEquals( splitWithMultipleSeparatorExpectedResults.length, splitWithMultipleSeparator.length );
for( int i = 0; i < splitWithMultipleSeparatorExpectedResults.length ; i++ ) {
assertEquals( splitWithMultipleSeparatorExpectedResults[i], splitWithMultipleSeparator[i] ) ;
}
}
@Test
public void testSplitByWholeString_StringStringBooleanInt() {
assertArrayEquals( null, StringUtils.splitByWholeSeparator( null, ".", 3 ) ) ;
assertEquals( 0, StringUtils.splitByWholeSeparator( "", ".", 3 ).length ) ;
String stringToSplitOnNulls = "ab de fg" ;
String[] splitOnNullExpectedResults = { "ab", "de fg" } ;
//String[] splitOnNullExpectedResults = { "ab", "de" } ;
String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null, 2 ) ;
assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
}
String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously" ;
String[] splitOnStringExpectedResults = { "abstemiously", "abstemiouslyaeiouyabstemiously" } ;
//String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy", 2 ) ;
assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i++ ) {
assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
}
}
@Test
public void testSplitByWholeSeparatorPreserveAllTokens_StringStringInt() {
assertArrayEquals( null, StringUtils.splitByWholeSeparatorPreserveAllTokens( null, ".", -1 ) ) ;
assertEquals( 0, StringUtils.splitByWholeSeparatorPreserveAllTokens( "", ".", -1 ).length ) ;
// test whitespace
String input = "ab de fg" ;
String[] expected = new String[] { "ab", "", "", "de", "fg" } ;
String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, null, -1 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
// test delimiter singlechar
input = "1::2:::3::::4";
expected = new String[] { "1", "", "2", "", "", "3", "", "", "", "4" };
actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, ":", -1 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
// test delimiter multichar
input = "1::2:::3::::4";
expected = new String[] { "1", "2", ":3", "", "4" };
actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, "::", -1 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
// test delimiter char with max
input = "1::2::3:4";
expected = new String[] { "1", "", "2", ":3:4" };
actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, ":", 4 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
}
@Test
public void testSplitPreserveAllTokens_String() {
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null));
assertEquals(0, StringUtils.splitPreserveAllTokens("").length);
String str = "abc def";
String[] res = StringUtils.splitPreserveAllTokens(str);
assertEquals(2, res.length);
assertEquals("abc", res[0]);
assertEquals("def", res[1]);
str = "abc def";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(3, res.length);
assertEquals("abc", res[0]);
assertEquals("", res[1]);
assertEquals("def", res[2]);
str = " abc ";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(3, res.length);
assertEquals("", res[0]);
assertEquals("abc", res[1]);
assertEquals("", res[2]);
str = "a b .c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(".c", res[2]);
str = " a b .c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("b", res[2]);
assertEquals(".c", res[3]);
str = "a b .c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(5, res.length);
assertEquals("a", res[0]);
assertEquals("", res[1]);
assertEquals("b", res[2]);
assertEquals("", res[3]);
assertEquals(".c", res[4]);
str = " a ";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
assertEquals("", res[3]);
str = " a b";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
assertEquals("b", res[3]);
str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(WHITESPACE.length() + 1, res.length);
assertEquals("a", res[0]);
for(int i = 1; i < WHITESPACE.length()-1; i++)
{
assertEquals("", res[i]);
}
assertEquals("b" + NON_WHITESPACE + "c", res[WHITESPACE.length()]);
}
@Test
public void testSplitPreserveAllTokens_StringChar() {
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null, '.'));
assertEquals(0, StringUtils.splitPreserveAllTokens("", '.').length);
String str = "a.b. c";
String[] res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(" c", res[2]);
str = "a.b.. c";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(4, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("", res[2]);
assertEquals(" c", res[3]);
str = ".a.";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(3, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
str = ".a..";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
assertEquals("", res[3]);
str = "..a.";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("", res[1]);
assertEquals("a", res[2]);
assertEquals("", res[3]);
str = "..a";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(3, res.length);
assertEquals("", res[0]);
assertEquals("", res[1]);
assertEquals("a", res[2]);
str = "a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
str = "a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(5, res.length);
assertEquals("a", res[0]);
assertEquals("", res[1]);
assertEquals("b", res[2]);
assertEquals("", res[3]);
assertEquals("c", res[4]);
str = " a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("b", res[2]);
assertEquals("c", res[3]);
str = " a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(5, res.length);
assertEquals("", res[0]);
assertEquals("", res[1]);
assertEquals("a", res[2]);
assertEquals("b", res[3]);
assertEquals("c", res[4]);
str = "a b c ";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(4, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
assertEquals("", res[3]);
str = "a b c ";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(5, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
assertEquals("", res[3]);
assertEquals("", res[3]);
// Match example in javadoc
{
String[] results;
String[] expectedResults = {"a", "", "b", "c"};
results = StringUtils.splitPreserveAllTokens("a..b.c",'.');
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
}
@Test
public void testSplitPreserveAllTokens_StringString_StringStringInt() {
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null, "."));
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null, ".", 3));
assertEquals(0, StringUtils.splitPreserveAllTokens("", ".").length);
assertEquals(0, StringUtils.splitPreserveAllTokens("", ".", 3).length);
innerTestSplitPreserveAllTokens('.', ".", ' ');
innerTestSplitPreserveAllTokens('.', ".", ',');
innerTestSplitPreserveAllTokens('.', ".,", 'x');
for (int i = 0; i < WHITESPACE.length(); i++) {
for (int j = 0; j < NON_WHITESPACE.length(); j++) {
innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j));
innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j));
}
}
{
String[] results;
String[] expectedResults = {"ab", "de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", " de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "::de:fg"};
results = StringUtils.splitPreserveAllTokens("ab:::de:fg", ":", 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", " de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 3);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", "", "de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 4);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] expectedResults = {"ab", "cd:ef"};
String[] results;
results = StringUtils.splitPreserveAllTokens("ab:cd:ef",":", 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", ":cd:ef"};
results = StringUtils.splitPreserveAllTokens("ab::cd:ef",":", 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", ":cd:ef"};
results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 3);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", "", "cd:ef"};
results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 4);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"", "ab", "", "", "cd:ef"};
results = StringUtils.splitPreserveAllTokens(":ab:::cd:ef",":", 5);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"", "", "ab", "", "", "cd:ef"};
results = StringUtils.splitPreserveAllTokens("::ab:::cd:ef",":", 6);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
}
private void innerTestSplitPreserveAllTokens(char separator, String sepStr, char noMatch) {
String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
"), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
final String str = "a" + separator + "b" + separator + separator + noMatch + "c";
String[] res;
// (str, sepStr)
res = StringUtils.splitPreserveAllTokens(str, sepStr);
assertEquals(msg, 4, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, "", res[2]);
assertEquals(msg, noMatch + "c", res[3]);
final String str2 = separator + "a" + separator;
res = StringUtils.splitPreserveAllTokens(str2, sepStr);
assertEquals(msg, 3, res.length);
assertEquals(msg, "", res[0]);
assertEquals(msg, "a", res[1]);
assertEquals(msg, "", res[2]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, -1);
assertEquals(msg, 4, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, "", res[2]);
assertEquals(msg, noMatch + "c", res[3]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, 0);
assertEquals(msg, 4, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, "", res[2]);
assertEquals(msg, noMatch + "c", res[3]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, 1);
assertEquals(msg, 1, res.length);
assertEquals(msg, str, res[0]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, 2);
assertEquals(msg, 2, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, str.substring(2), res[1]);
}
@Test
public void testSplitByCharacterType() {
assertNull(StringUtils.splitByCharacterType(null));
assertEquals(0, StringUtils.splitByCharacterType("").length);
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterType("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterType("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", ":", "cd", ":",
"ef" }, StringUtils.splitByCharacterType("ab:cd:ef")));
assertTrue(ArrayUtils.isEquals(new String[] { "number", "5" },
StringUtils.splitByCharacterType("number5")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "B", "ar" },
StringUtils.splitByCharacterType("fooBar")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "200", "B", "ar" },
StringUtils.splitByCharacterType("foo200Bar")));
assertTrue(ArrayUtils.isEquals(new String[] { "ASFR", "ules" },
StringUtils.splitByCharacterType("ASFRules")));
}
@Test
public void testSplitByCharacterTypeCamelCase() {
assertNull(StringUtils.splitByCharacterTypeCamelCase(null));
assertEquals(0, StringUtils.splitByCharacterTypeCamelCase("").length);
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterTypeCamelCase("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterTypeCamelCase("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", ":", "cd", ":",
"ef" }, StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef")));
assertTrue(ArrayUtils.isEquals(new String[] { "number", "5" },
StringUtils.splitByCharacterTypeCamelCase("number5")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "Bar" },
StringUtils.splitByCharacterTypeCamelCase("fooBar")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "200", "Bar" },
StringUtils.splitByCharacterTypeCamelCase("foo200Bar")));
assertTrue(ArrayUtils.isEquals(new String[] { "ASF", "Rules" },
StringUtils.splitByCharacterTypeCamelCase("ASFRules")));
}
@Test
public void testDeleteWhitespace_String() {
assertEquals(null, StringUtils.deleteWhitespace(null));
assertEquals("", StringUtils.deleteWhitespace(""));
assertEquals("", StringUtils.deleteWhitespace(" \u000C \t\t\u001F\n\n \u000B "));
assertEquals("", StringUtils.deleteWhitespace(StringUtilsTest.WHITESPACE));
assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.deleteWhitespace(StringUtilsTest.NON_WHITESPACE));
// Note: u-2007 and u-000A both cause problems in the source code
// it should ignore 2007 but delete 000A
assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace(" \u00A0 \t\t\n\n \u202F "));
assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace("\u00A0\u202F"));
assertEquals("test", StringUtils.deleteWhitespace("\u000Bt \t\n\u0009e\rs\n\n \tt"));
}
@Test
public void testLang623() {
assertEquals("t", StringUtils.replaceChars("\u00DE", '\u00DE', 't'));
assertEquals("t", StringUtils.replaceChars("\u00FE", '\u00FE', 't'));
}
@Test
public void testReplace_StringStringString() {
assertEquals(null, StringUtils.replace(null, null, null));
assertEquals(null, StringUtils.replace(null, null, "any"));
assertEquals(null, StringUtils.replace(null, "any", null));
assertEquals(null, StringUtils.replace(null, "any", "any"));
assertEquals("", StringUtils.replace("", null, null));
assertEquals("", StringUtils.replace("", null, "any"));
assertEquals("", StringUtils.replace("", "any", null));
assertEquals("", StringUtils.replace("", "any", "any"));
assertEquals("FOO", StringUtils.replace("FOO", "", "any"));
assertEquals("FOO", StringUtils.replace("FOO", null, "any"));
assertEquals("FOO", StringUtils.replace("FOO", "F", null));
assertEquals("FOO", StringUtils.replace("FOO", null, null));
assertEquals("", StringUtils.replace("foofoofoo", "foo", ""));
assertEquals("barbarbar", StringUtils.replace("foofoofoo", "foo", "bar"));
assertEquals("farfarfar", StringUtils.replace("foofoofoo", "oo", "ar"));
}
@Test
public void testReplacePattern() {
assertEquals("X", StringUtils.replacePattern("<A>\nxy\n</A>", "<A>.*</A>", "X"));
}
@Test
public void testRemovePattern() {
assertEquals("", StringUtils.removePattern("<A>x\\ny</A>", "<A>.*</A>"));
}
@Test
public void testReplace_StringStringStringInt() {
assertEquals(null, StringUtils.replace(null, null, null, 2));
assertEquals(null, StringUtils.replace(null, null, "any", 2));
assertEquals(null, StringUtils.replace(null, "any", null, 2));
assertEquals(null, StringUtils.replace(null, "any", "any", 2));
assertEquals("", StringUtils.replace("", null, null, 2));
assertEquals("", StringUtils.replace("", null, "any", 2));
assertEquals("", StringUtils.replace("", "any", null, 2));
assertEquals("", StringUtils.replace("", "any", "any", 2));
String str = new String(new char[] {'o', 'o', 'f', 'o', 'o'});
assertSame(str, StringUtils.replace(str, "x", "", -1));
assertEquals("f", StringUtils.replace("oofoo", "o", "", -1));
assertEquals("oofoo", StringUtils.replace("oofoo", "o", "", 0));
assertEquals("ofoo", StringUtils.replace("oofoo", "o", "", 1));
assertEquals("foo", StringUtils.replace("oofoo", "o", "", 2));
assertEquals("fo", StringUtils.replace("oofoo", "o", "", 3));
assertEquals("f", StringUtils.replace("oofoo", "o", "", 4));
assertEquals("f", StringUtils.replace("oofoo", "o", "", -5));
assertEquals("f", StringUtils.replace("oofoo", "o", "", 1000));
}
@Test
public void testReplaceOnce_StringStringString() {
assertEquals(null, StringUtils.replaceOnce(null, null, null));
assertEquals(null, StringUtils.replaceOnce(null, null, "any"));
assertEquals(null, StringUtils.replaceOnce(null, "any", null));
assertEquals(null, StringUtils.replaceOnce(null, "any", "any"));
assertEquals("", StringUtils.replaceOnce("", null, null));
assertEquals("", StringUtils.replaceOnce("", null, "any"));
assertEquals("", StringUtils.replaceOnce("", "any", null));
assertEquals("", StringUtils.replaceOnce("", "any", "any"));
assertEquals("FOO", StringUtils.replaceOnce("FOO", "", "any"));
assertEquals("FOO", StringUtils.replaceOnce("FOO", null, "any"));
assertEquals("FOO", StringUtils.replaceOnce("FOO", "F", null));
assertEquals("FOO", StringUtils.replaceOnce("FOO", null, null));
assertEquals("foofoo", StringUtils.replaceOnce("foofoofoo", "foo", ""));
}
/**
* Test method for 'StringUtils.replaceEach(String, String[], String[])'
*/
@Test
public void testReplace_StringStringArrayStringArray() {
//JAVADOC TESTS START
assertNull(StringUtils.replaceEach(null, new String[]{"a"}, new String[]{"b"}));
assertEquals(StringUtils.replaceEach("", new String[]{"a"}, new String[]{"b"}),"");
assertEquals(StringUtils.replaceEach("aba", null, null),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[0], null),"aba");
assertEquals(StringUtils.replaceEach("aba", null, new String[0]),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, null),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}),"b");
assertEquals(StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}),"aba");
assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}),"wcte");
assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}),"dcte");
//JAVADOC TESTS END
assertEquals("bcc", StringUtils.replaceEach("abc", new String[]{"a", "b"}, new String[]{"b", "c"}));
assertEquals("q651.506bera", StringUtils.replaceEach("d216.102oren",
new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D",
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9"},
new String[]{"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "5", "6", "7", "8", "9", "1", "2", "3", "4"}));
// Test null safety inside arrays - LANG-552
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{null}),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a", "b"}, new String[]{"c", null}),"cbc");
}
/**
* Test method for 'StringUtils.replaceEachRepeatedly(String, String[], String[])'
*/
@Test
public void testReplace_StringStringArrayStringArrayBoolean() {
//JAVADOC TESTS START
assertNull(StringUtils.replaceEachRepeatedly(null, new String[]{"a"}, new String[]{"b"}));
assertEquals(StringUtils.replaceEachRepeatedly("", new String[]{"a"}, new String[]{"b"}),"");
assertEquals(StringUtils.replaceEachRepeatedly("aba", null, null),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", null, new String[0]),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}),"b");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}),"wcte");
assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}),"tcte");
try {
StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"});
fail("Should be a circular reference");
} catch (IllegalStateException e) {}
//JAVADOC TESTS END
}
@Test
public void testReplaceChars_StringCharChar() {
assertEquals(null, StringUtils.replaceChars(null, 'b', 'z'));
assertEquals("", StringUtils.replaceChars("", 'b', 'z'));
assertEquals("azcza", StringUtils.replaceChars("abcba", 'b', 'z'));
assertEquals("abcba", StringUtils.replaceChars("abcba", 'x', 'z'));
}
@Test
public void testReplaceChars_StringStringString() {
assertEquals(null, StringUtils.replaceChars(null, null, null));
assertEquals(null, StringUtils.replaceChars(null, "", null));
assertEquals(null, StringUtils.replaceChars(null, "a", null));
assertEquals(null, StringUtils.replaceChars(null, null, ""));
assertEquals(null, StringUtils.replaceChars(null, null, "x"));
assertEquals("", StringUtils.replaceChars("", null, null));
assertEquals("", StringUtils.replaceChars("", "", null));
assertEquals("", StringUtils.replaceChars("", "a", null));
assertEquals("", StringUtils.replaceChars("", null, ""));
assertEquals("", StringUtils.replaceChars("", null, "x"));
assertEquals("abc", StringUtils.replaceChars("abc", null, null));
assertEquals("abc", StringUtils.replaceChars("abc", null, ""));
assertEquals("abc", StringUtils.replaceChars("abc", null, "x"));
assertEquals("abc", StringUtils.replaceChars("abc", "", null));
assertEquals("abc", StringUtils.replaceChars("abc", "", ""));
assertEquals("abc", StringUtils.replaceChars("abc", "", "x"));
assertEquals("ac", StringUtils.replaceChars("abc", "b", null));
assertEquals("ac", StringUtils.replaceChars("abc", "b", ""));
assertEquals("axc", StringUtils.replaceChars("abc", "b", "x"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz"));
assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx"));
assertEquals("abcba", StringUtils.replaceChars("abcba", "z", "w"));
assertSame("abcba", StringUtils.replaceChars("abcba", "z", "w"));
// Javadoc examples:
assertEquals("jelly", StringUtils.replaceChars("hello", "ho", "jy"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz"));
assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx"));
// From http://issues.apache.org/bugzilla/show_bug.cgi?id=25454
assertEquals("bcc", StringUtils.replaceChars("abc", "ab", "bc"));
assertEquals("q651.506bera", StringUtils.replaceChars("d216.102oren",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234"));
}
@Test
public void testOverlay_StringStringIntInt() {
assertEquals(null, StringUtils.overlay(null, null, 2, 4));
assertEquals(null, StringUtils.overlay(null, null, -2, -4));
assertEquals("", StringUtils.overlay("", null, 0, 0));
assertEquals("", StringUtils.overlay("", "", 0, 0));
assertEquals("zzzz", StringUtils.overlay("", "zzzz", 0, 0));
assertEquals("zzzz", StringUtils.overlay("", "zzzz", 2, 4));
assertEquals("zzzz", StringUtils.overlay("", "zzzz", -2, -4));
assertEquals("abef", StringUtils.overlay("abcdef", null, 2, 4));
assertEquals("abef", StringUtils.overlay("abcdef", null, 4, 2));
assertEquals("abef", StringUtils.overlay("abcdef", "", 2, 4));
assertEquals("abef", StringUtils.overlay("abcdef", "", 4, 2));
assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 2, 4));
assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 4, 2));
assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", -1, 4));
assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", 4, -1));
assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -2, -1));
assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -1, -2));
assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 4, 10));
assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 4));
assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 8, 10));
assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 8));
}
@Test
public void testRepeat_StringInt() {
assertEquals(null, StringUtils.repeat(null, 2));
assertEquals("", StringUtils.repeat("ab", 0));
assertEquals("", StringUtils.repeat("", 3));
assertEquals("aaa", StringUtils.repeat("a", 3));
assertEquals("ababab", StringUtils.repeat("ab", 3));
assertEquals("abcabcabc", StringUtils.repeat("abc", 3));
String str = StringUtils.repeat("a", 10000); // bigger than pad limit
assertEquals(10000, str.length());
assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
}
@Test
public void testRepeat_StringStringInt() {
assertEquals(null, StringUtils.repeat(null, null, 2));
assertEquals(null, StringUtils.repeat(null, "x", 2));
assertEquals("", StringUtils.repeat("", null, 2));
assertEquals("", StringUtils.repeat("ab", "", 0));
assertEquals("", StringUtils.repeat("", "", 2));
assertEquals("xx", StringUtils.repeat("", "x", 3));
assertEquals("?, ?, ?", StringUtils.repeat("?", ", ", 3));
}
@Test
public void testChop() {
String[][] chopCases = {
{ FOO_UNCAP + "\r\n", FOO_UNCAP } ,
{ FOO_UNCAP + "\n" , FOO_UNCAP } ,
{ FOO_UNCAP + "\r", FOO_UNCAP },
{ FOO_UNCAP + " \r", FOO_UNCAP + " " },
{ "foo", "fo"},
{ "foo\nfoo", "foo\nfo" },
{ "\n", "" },
{ "\r", "" },
{ "\r\n", "" },
{ null, null },
{ "", "" },
{ "a", "" },
};
for (String[] chopCase : chopCases) {
String original = chopCase[0];
String expectedResult = chopCase[1];
assertEquals("chop(String) failed",
expectedResult, StringUtils.chop(original));
}
}
@SuppressWarnings("deprecation") // intentional test of deprecated method
@Test
public void testChomp() {
String[][] chompCases = {
{ FOO_UNCAP + "\r\n", FOO_UNCAP },
{ FOO_UNCAP + "\n" , FOO_UNCAP },
{ FOO_UNCAP + "\r", FOO_UNCAP },
{ FOO_UNCAP + " \r", FOO_UNCAP + " " },
{ FOO_UNCAP, FOO_UNCAP },
{ FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"},
{ FOO_UNCAP + "\r\n\r\n", FOO_UNCAP + "\r\n" },
{ "foo\nfoo", "foo\nfoo" },
{ "foo\n\rfoo", "foo\n\rfoo" },
{ "\n", "" },
{ "\r", "" },
{ "a", "a" },
{ "\r\n", "" },
{ "", "" },
{ null, null },
{ FOO_UNCAP + "\n\r", FOO_UNCAP + "\n"}
};
for (String[] chompCase : chompCases) {
String original = chompCase[0];
String expectedResult = chompCase[1];
assertEquals("chomp(String) failed",
expectedResult, StringUtils.chomp(original));
}
assertEquals("chomp(String, String) failed",
"foo", StringUtils.chomp("foobar", "bar"));
assertEquals("chomp(String, String) failed",
"foobar", StringUtils.chomp("foobar", "baz"));
assertEquals("chomp(String, String) failed",
"foo", StringUtils.chomp("foo", "foooo"));
assertEquals("chomp(String, String) failed",
"foobar", StringUtils.chomp("foobar", ""));
assertEquals("chomp(String, String) failed",
"foobar", StringUtils.chomp("foobar", null));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("", "foo"));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("", null));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("", ""));
assertEquals("chomp(String, String) failed",
null, StringUtils.chomp(null, "foo"));
assertEquals("chomp(String, String) failed",
null, StringUtils.chomp(null, null));
assertEquals("chomp(String, String) failed",
null, StringUtils.chomp(null, ""));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("foo", "foo"));
assertEquals("chomp(String, String) failed",
" ", StringUtils.chomp(" foo", "foo"));
assertEquals("chomp(String, String) failed",
"foo ", StringUtils.chomp("foo ", "foo"));
}
//-----------------------------------------------------------------------
@Test
public void testRightPad_StringInt() {
assertEquals(null, StringUtils.rightPad(null, 5));
assertEquals(" ", StringUtils.rightPad("", 5));
assertEquals("abc ", StringUtils.rightPad("abc", 5));
assertEquals("abc", StringUtils.rightPad("abc", 2));
assertEquals("abc", StringUtils.rightPad("abc", -1));
}
@Test
public void testRightPad_StringIntChar() {
assertEquals(null, StringUtils.rightPad(null, 5, ' '));
assertEquals(" ", StringUtils.rightPad("", 5, ' '));
assertEquals("abc ", StringUtils.rightPad("abc", 5, ' '));
assertEquals("abc", StringUtils.rightPad("abc", 2, ' '));
assertEquals("abc", StringUtils.rightPad("abc", -1, ' '));
assertEquals("abcxx", StringUtils.rightPad("abc", 5, 'x'));
String str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length
assertEquals(10000, str.length());
assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
}
@Test
public void testRightPad_StringIntString() {
assertEquals(null, StringUtils.rightPad(null, 5, "-+"));
assertEquals(" ", StringUtils.rightPad("", 5, " "));
assertEquals(null, StringUtils.rightPad(null, 8, null));
assertEquals("abc-+-+", StringUtils.rightPad("abc", 7, "-+"));
assertEquals("abc-+~", StringUtils.rightPad("abc", 6, "-+~"));
assertEquals("abc-+", StringUtils.rightPad("abc", 5, "-+~"));
assertEquals("abc", StringUtils.rightPad("abc", 2, " "));
assertEquals("abc", StringUtils.rightPad("abc", -1, " "));
assertEquals("abc ", StringUtils.rightPad("abc", 5, null));
assertEquals("abc ", StringUtils.rightPad("abc", 5, ""));
}
//-----------------------------------------------------------------------
@Test
public void testLeftPad_StringInt() {
assertEquals(null, StringUtils.leftPad(null, 5));
assertEquals(" ", StringUtils.leftPad("", 5));
assertEquals(" abc", StringUtils.leftPad("abc", 5));
assertEquals("abc", StringUtils.leftPad("abc", 2));
}
@Test
public void testLeftPad_StringIntChar() {
assertEquals(null, StringUtils.leftPad(null, 5, ' '));
assertEquals(" ", StringUtils.leftPad("", 5, ' '));
assertEquals(" abc", StringUtils.leftPad("abc", 5, ' '));
assertEquals("xxabc", StringUtils.leftPad("abc", 5, 'x'));
assertEquals("\uffff\uffffabc", StringUtils.leftPad("abc", 5, '\uffff'));
assertEquals("abc", StringUtils.leftPad("abc", 2, ' '));
String str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length
assertEquals(10000, str.length());
assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
}
@Test
public void testLeftPad_StringIntString() {
assertEquals(null, StringUtils.leftPad(null, 5, "-+"));
assertEquals(null, StringUtils.leftPad(null, 5, null));
assertEquals(" ", StringUtils.leftPad("", 5, " "));
assertEquals("-+-+abc", StringUtils.leftPad("abc", 7, "-+"));
assertEquals("-+~abc", StringUtils.leftPad("abc", 6, "-+~"));
assertEquals("-+abc", StringUtils.leftPad("abc", 5, "-+~"));
assertEquals("abc", StringUtils.leftPad("abc", 2, " "));
assertEquals("abc", StringUtils.leftPad("abc", -1, " "));
assertEquals(" abc", StringUtils.leftPad("abc", 5, null));
assertEquals(" abc", StringUtils.leftPad("abc", 5, ""));
}
@Test
public void testLengthString() {
assertEquals(0, StringUtils.length(null));
assertEquals(0, StringUtils.length(""));
assertEquals(0, StringUtils.length(StringUtils.EMPTY));
assertEquals(1, StringUtils.length("A"));
assertEquals(1, StringUtils.length(" "));
assertEquals(8, StringUtils.length("ABCDEFGH"));
}
@Test
public void testLengthStringBuffer() {
assertEquals(0, StringUtils.length(new StringBuffer("")));
assertEquals(0, StringUtils.length(new StringBuffer(StringUtils.EMPTY)));
assertEquals(1, StringUtils.length(new StringBuffer("A")));
assertEquals(1, StringUtils.length(new StringBuffer(" ")));
assertEquals(8, StringUtils.length(new StringBuffer("ABCDEFGH")));
}
@Test
public void testLengthStringBuilder() {
assertEquals(0, StringUtils.length(new StringBuilder("")));
assertEquals(0, StringUtils.length(new StringBuilder(StringUtils.EMPTY)));
assertEquals(1, StringUtils.length(new StringBuilder("A")));
assertEquals(1, StringUtils.length(new StringBuilder(" ")));
assertEquals(8, StringUtils.length(new StringBuilder("ABCDEFGH")));
}
@Test
public void testLength_CharBuffer() {
assertEquals(0, StringUtils.length(CharBuffer.wrap("")));
assertEquals(1, StringUtils.length(CharBuffer.wrap("A")));
assertEquals(1, StringUtils.length(CharBuffer.wrap(" ")));
assertEquals(8, StringUtils.length(CharBuffer.wrap("ABCDEFGH")));
}
//-----------------------------------------------------------------------
@Test
public void testCenter_StringInt() {
assertEquals(null, StringUtils.center(null, -1));
assertEquals(null, StringUtils.center(null, 4));
assertEquals(" ", StringUtils.center("", 4));
assertEquals("ab", StringUtils.center("ab", 0));
assertEquals("ab", StringUtils.center("ab", -1));
assertEquals("ab", StringUtils.center("ab", 1));
assertEquals(" ", StringUtils.center("", 4));
assertEquals(" ab ", StringUtils.center("ab", 4));
assertEquals("abcd", StringUtils.center("abcd", 2));
assertEquals(" a ", StringUtils.center("a", 4));
assertEquals(" a ", StringUtils.center("a", 5));
}
@Test
public void testCenter_StringIntChar() {
assertEquals(null, StringUtils.center(null, -1, ' '));
assertEquals(null, StringUtils.center(null, 4, ' '));
assertEquals(" ", StringUtils.center("", 4, ' '));
assertEquals("ab", StringUtils.center("ab", 0, ' '));
assertEquals("ab", StringUtils.center("ab", -1, ' '));
assertEquals("ab", StringUtils.center("ab", 1, ' '));
assertEquals(" ", StringUtils.center("", 4, ' '));
assertEquals(" ab ", StringUtils.center("ab", 4, ' '));
assertEquals("abcd", StringUtils.center("abcd", 2, ' '));
assertEquals(" a ", StringUtils.center("a", 4, ' '));
assertEquals(" a ", StringUtils.center("a", 5, ' '));
assertEquals("xxaxx", StringUtils.center("a", 5, 'x'));
}
@Test
public void testCenter_StringIntString() {
assertEquals(null, StringUtils.center(null, 4, null));
assertEquals(null, StringUtils.center(null, -1, " "));
assertEquals(null, StringUtils.center(null, 4, " "));
assertEquals(" ", StringUtils.center("", 4, " "));
assertEquals("ab", StringUtils.center("ab", 0, " "));
assertEquals("ab", StringUtils.center("ab", -1, " "));
assertEquals("ab", StringUtils.center("ab", 1, " "));
assertEquals(" ", StringUtils.center("", 4, " "));
assertEquals(" ab ", StringUtils.center("ab", 4, " "));
assertEquals("abcd", StringUtils.center("abcd", 2, " "));
assertEquals(" a ", StringUtils.center("a", 4, " "));
assertEquals("yayz", StringUtils.center("a", 4, "yz"));
assertEquals("yzyayzy", StringUtils.center("a", 7, "yz"));
assertEquals(" abc ", StringUtils.center("abc", 7, null));
assertEquals(" abc ", StringUtils.center("abc", 7, ""));
}
//-----------------------------------------------------------------------
@Test
public void testReverse_String() {
assertEquals(null, StringUtils.reverse(null) );
assertEquals("", StringUtils.reverse("") );
assertEquals("sdrawkcab", StringUtils.reverse("backwards") );
}
@Test
public void testReverseDelimited_StringChar() {
assertEquals(null, StringUtils.reverseDelimited(null, '.') );
assertEquals("", StringUtils.reverseDelimited("", '.') );
assertEquals("c.b.a", StringUtils.reverseDelimited("a.b.c", '.') );
assertEquals("a b c", StringUtils.reverseDelimited("a b c", '.') );
assertEquals("", StringUtils.reverseDelimited("", '.') );
}
//-----------------------------------------------------------------------
@Test
public void testDefault_String() {
assertEquals("", StringUtils.defaultString(null));
assertEquals("", StringUtils.defaultString(""));
assertEquals("abc", StringUtils.defaultString("abc"));
}
@Test
public void testDefault_StringString() {
assertEquals("NULL", StringUtils.defaultString(null, "NULL"));
assertEquals("", StringUtils.defaultString("", "NULL"));
assertEquals("abc", StringUtils.defaultString("abc", "NULL"));
}
@Test
public void testDefaultIfEmpty_StringString() {
assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL"));
assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL"));
assertEquals("abc", StringUtils.defaultIfEmpty("abc", "NULL"));
assertNull(StringUtils.defaultIfEmpty("", null));
// Tests compatibility for the API return type
String s = StringUtils.defaultIfEmpty("abc", "NULL");
assertEquals("abc", s);
}
@Test
public void testDefaultIfBlank_StringString() {
assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL"));
assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL"));
assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL"));
assertEquals("abc", StringUtils.defaultIfBlank("abc", "NULL"));
assertNull(StringUtils.defaultIfBlank("", null));
// Tests compatibility for the API return type
String s = StringUtils.defaultIfBlank("abc", "NULL");
assertEquals("abc", s);
}
@Test
public void testDefaultIfEmpty_StringBuilders() {
assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuilder(""), new StringBuilder("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL")).toString());
assertNull(StringUtils.defaultIfEmpty(new StringBuilder(""), null));
// Tests compatibility for the API return type
StringBuilder s = StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfBlank_StringBuilders() {
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuilder(""), new StringBuilder("NULL")).toString());
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuilder(" "), new StringBuilder("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL")).toString());
assertNull(StringUtils.defaultIfBlank(new StringBuilder(""), null));
// Tests compatibility for the API return type
StringBuilder s = StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfEmpty_StringBuffers() {
assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuffer(""), new StringBuffer("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL")).toString());
assertNull(StringUtils.defaultIfEmpty(new StringBuffer(""), null));
// Tests compatibility for the API return type
StringBuffer s = StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfBlank_StringBuffers() {
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuffer(""), new StringBuffer("NULL")).toString());
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuffer(" "), new StringBuffer("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL")).toString());
assertNull(StringUtils.defaultIfBlank(new StringBuffer(""), null));
// Tests compatibility for the API return type
StringBuffer s = StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfEmpty_CharBuffers() {
assertEquals("NULL", StringUtils.defaultIfEmpty(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString());
assertNull(StringUtils.defaultIfEmpty(CharBuffer.wrap(""), null));
// Tests compatibility for the API return type
CharBuffer s = StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfBlank_CharBuffers() {
assertEquals("NULL", StringUtils.defaultIfBlank(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString());
assertEquals("NULL", StringUtils.defaultIfBlank(CharBuffer.wrap(" "), CharBuffer.wrap("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString());
assertNull(StringUtils.defaultIfBlank(CharBuffer.wrap(""), null));
// Tests compatibility for the API return type
CharBuffer s = StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
assertEquals("abc", s.toString());
}
//-----------------------------------------------------------------------
@Test
public void testAbbreviate_StringInt() {
assertEquals(null, StringUtils.abbreviate(null, 10));
assertEquals("", StringUtils.abbreviate("", 10));
assertEquals("short", StringUtils.abbreviate("short", 10));
assertEquals("Now is ...", StringUtils.abbreviate("Now is the time for all good men to come to the aid of their party.", 10));
String raspberry = "raspberry peach";
assertEquals("raspberry p...", StringUtils.abbreviate(raspberry, 14));
assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 15));
assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 16));
assertEquals("abc...", StringUtils.abbreviate("abcdefg", 6));
assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 7));
assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8));
assertEquals("a...", StringUtils.abbreviate("abcdefg", 4));
assertEquals("", StringUtils.abbreviate("", 4));
try {
@SuppressWarnings("unused")
String res = StringUtils.abbreviate("abc", 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
}
@Test
public void testAbbreviate_StringIntInt() {
assertEquals(null, StringUtils.abbreviate(null, 10, 12));
assertEquals("", StringUtils.abbreviate("", 0, 10));
assertEquals("", StringUtils.abbreviate("", 2, 10));
try {
@SuppressWarnings("unused")
String res = StringUtils.abbreviate("abcdefghij", 0, 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
String res = StringUtils.abbreviate("abcdefghij", 5, 6);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
String raspberry = "raspberry peach";
assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15));
assertEquals(null, StringUtils.abbreviate(null, 7, 14));
assertAbbreviateWithOffset("abcdefg...", -1, 10);
assertAbbreviateWithOffset("abcdefg...", 0, 10);
assertAbbreviateWithOffset("abcdefg...", 1, 10);
assertAbbreviateWithOffset("abcdefg...", 2, 10);
assertAbbreviateWithOffset("abcdefg...", 3, 10);
assertAbbreviateWithOffset("abcdefg...", 4, 10);
assertAbbreviateWithOffset("...fghi...", 5, 10);
assertAbbreviateWithOffset("...ghij...", 6, 10);
assertAbbreviateWithOffset("...hijk...", 7, 10);
assertAbbreviateWithOffset("...ijklmno", 8, 10);
assertAbbreviateWithOffset("...ijklmno", 9, 10);
assertAbbreviateWithOffset("...ijklmno", 10, 10);
assertAbbreviateWithOffset("...ijklmno", 10, 10);
assertAbbreviateWithOffset("...ijklmno", 11, 10);
assertAbbreviateWithOffset("...ijklmno", 12, 10);
assertAbbreviateWithOffset("...ijklmno", 13, 10);
assertAbbreviateWithOffset("...ijklmno", 14, 10);
assertAbbreviateWithOffset("...ijklmno", 15, 10);
assertAbbreviateWithOffset("...ijklmno", 16, 10);
assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10);
}
private void assertAbbreviateWithOffset(String expected, int offset, int maxWidth) {
String abcdefghijklmno = "abcdefghijklmno";
String message = "abbreviate(String,int,int) failed";
String actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth);
if (offset >= 0 && offset < abcdefghijklmno.length()) {
assertTrue(message + " -- should contain offset character",
actual.indexOf((char)('a'+offset)) != -1);
}
assertTrue(message + " -- should not be greater than maxWidth",
actual.length() <= maxWidth);
assertEquals(message, expected, actual);
}
@Test
public void testAbbreviateMiddle() {
// javadoc examples
assertNull( StringUtils.abbreviateMiddle(null, null, 0) );
assertEquals( "abc", StringUtils.abbreviateMiddle("abc", null, 0) );
assertEquals( "abc", StringUtils.abbreviateMiddle("abc", ".", 0) );
assertEquals( "abc", StringUtils.abbreviateMiddle("abc", ".", 3) );
assertEquals( "ab.f", StringUtils.abbreviateMiddle("abcdef", ".", 4) );
// JIRA issue (LANG-405) example (slightly different than actual expected result)
assertEquals(
"A very long text with un...f the text is complete.",
StringUtils.abbreviateMiddle(
"A very long text with unimportant stuff in the middle but interesting start and " +
"end to see if the text is complete.", "...", 50) );
// Test a much longer text :)
String longText = "Start text" + StringUtils.repeat("x", 10000) + "Close text";
assertEquals(
"Start text->Close text",
StringUtils.abbreviateMiddle( longText, "->", 22 ) );
// Test negative length
assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", -1));
// Test boundaries
// Fails to change anything as method ensures first and last char are kept
assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 1));
assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 2));
// Test length of n=1
assertEquals("a", StringUtils.abbreviateMiddle("a", ".", 1));
// Test smallest length that can lead to success
assertEquals("a.d", StringUtils.abbreviateMiddle("abcd", ".", 3));
// More from LANG-405
assertEquals("a..f", StringUtils.abbreviateMiddle("abcdef", "..", 4));
assertEquals("ab.ef", StringUtils.abbreviateMiddle("abcdef", ".", 5));
}
//-----------------------------------------------------------------------
@Test
public void testDifference_StringString() {
assertEquals(null, StringUtils.difference(null, null));
assertEquals("", StringUtils.difference("", ""));
assertEquals("abc", StringUtils.difference("", "abc"));
assertEquals("", StringUtils.difference("abc", ""));
assertEquals("i am a robot", StringUtils.difference(null, "i am a robot"));
assertEquals("i am a machine", StringUtils.difference("i am a machine", null));
assertEquals("robot", StringUtils.difference("i am a machine", "i am a robot"));
assertEquals("", StringUtils.difference("abc", "abc"));
assertEquals("you are a robot", StringUtils.difference("i am a robot", "you are a robot"));
}
@Test
public void testDifferenceAt_StringString() {
assertEquals(-1, StringUtils.indexOfDifference(null, null));
assertEquals(0, StringUtils.indexOfDifference(null, "i am a robot"));
assertEquals(-1, StringUtils.indexOfDifference("", ""));
assertEquals(0, StringUtils.indexOfDifference("", "abc"));
assertEquals(0, StringUtils.indexOfDifference("abc", ""));
assertEquals(0, StringUtils.indexOfDifference("i am a machine", null));
assertEquals(7, StringUtils.indexOfDifference("i am a machine", "i am a robot"));
assertEquals(-1, StringUtils.indexOfDifference("foo", "foo"));
assertEquals(0, StringUtils.indexOfDifference("i am a robot", "you are a robot"));
//System.out.println("indexOfDiff: " + StringUtils.indexOfDifference("i am a robot", "not machine"));
}
//-----------------------------------------------------------------------
@Test
public void testGetLevenshteinDistance_StringString() {
assertEquals(0, StringUtils.getLevenshteinDistance("", "") );
assertEquals(1, StringUtils.getLevenshteinDistance("", "a") );
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "") );
assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog") );
assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant") );
assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo") );
assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant") );
assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") );
assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo") );
assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo") );
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance("a", null);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance(null, "a");
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
}
@Test
public void testGetLevenshteinDistance_StringStringInt() {
// empty strings
assertEquals(0, StringUtils.getLevenshteinDistance("", "", 0));
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "", 8));
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "", 7));
assertEquals(-1, StringUtils.getLevenshteinDistance("aaapppp", "", 6));
// unequal strings, zero threshold
assertEquals(-1, StringUtils.getLevenshteinDistance("b", "a", 0));
assertEquals(-1, StringUtils.getLevenshteinDistance("a", "b", 0));
// equal strings
assertEquals(0, StringUtils.getLevenshteinDistance("aa", "aa", 0));
assertEquals(0, StringUtils.getLevenshteinDistance("aa", "aa", 2));
// same length
assertEquals(-1, StringUtils.getLevenshteinDistance("aaa", "bbb", 2));
assertEquals(3, StringUtils.getLevenshteinDistance("aaa", "bbb", 3));
// big stripe
assertEquals(6, StringUtils.getLevenshteinDistance("aaaaaa", "b", 10));
// distance less than threshold
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "b", 8));
assertEquals(3, StringUtils.getLevenshteinDistance("a", "bbb", 4));
// distance equal to threshold
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "b", 7));
assertEquals(3, StringUtils.getLevenshteinDistance("a", "bbb", 3));
// distance greater than threshold
assertEquals(-1, StringUtils.getLevenshteinDistance("a", "bbb", 2));
assertEquals(-1, StringUtils.getLevenshteinDistance("bbb", "a", 2));
assertEquals(-1, StringUtils.getLevenshteinDistance("aaapppp", "b", 6));
// stripe runs off array, strings not similar
assertEquals(-1, StringUtils.getLevenshteinDistance("a", "bbb", 1));
assertEquals(-1, StringUtils.getLevenshteinDistance("bbb", "a", 1));
// stripe runs off array, strings are similar
assertEquals(-1, StringUtils.getLevenshteinDistance("12345", "1234567", 1));
assertEquals(-1, StringUtils.getLevenshteinDistance("1234567", "12345", 1));
// old getLevenshteinDistance test cases
assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog",1) );
assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant",3) );
assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo",7) );
assertEquals(-1, StringUtils.getLevenshteinDistance("elephant", "hippo",6) );
assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant",7) );
assertEquals(-1, StringUtils.getLevenshteinDistance("hippo", "elephant",6) );
assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz",8) );
assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo",8) );
assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo",1) );
// exceptions
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance("a", null, 0);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance(null, "a", 0);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance("a", "a", -1);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
}
/**
* A sanity check for {@link StringUtils#EMPTY}.
*/
@Test
public void testEMPTY() {
assertNotNull(StringUtils.EMPTY);
assertEquals("", StringUtils.EMPTY);
assertEquals(0, StringUtils.EMPTY.length());
}
/**
* Test for {@link StringUtils#isAllLowerCase(CharSequence)}.
*/
@Test
public void testIsAllLowerCase() {
assertFalse(StringUtils.isAllLowerCase(null));
assertFalse(StringUtils.isAllLowerCase(StringUtils.EMPTY));
assertTrue(StringUtils.isAllLowerCase("abc"));
assertFalse(StringUtils.isAllLowerCase("abc "));
assertFalse(StringUtils.isAllLowerCase("abC"));
}
/**
* Test for {@link StringUtils#isAllUpperCase(CharSequence)}.
*/
@Test
public void testIsAllUpperCase() {
assertFalse(StringUtils.isAllUpperCase(null));
assertFalse(StringUtils.isAllUpperCase(StringUtils.EMPTY));
assertTrue(StringUtils.isAllUpperCase("ABC"));
assertFalse(StringUtils.isAllUpperCase("ABC "));
assertFalse(StringUtils.isAllUpperCase("aBC"));
}
@Test
public void testRemoveStart() {
// StringUtils.removeStart("", *) = ""
assertNull(StringUtils.removeStart(null, null));
assertNull(StringUtils.removeStart(null, ""));
assertNull(StringUtils.removeStart(null, "a"));
// StringUtils.removeStart(*, null) = *
assertEquals(StringUtils.removeStart("", null), "");
assertEquals(StringUtils.removeStart("", ""), "");
assertEquals(StringUtils.removeStart("", "a"), "");
// All others:
assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com");
assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com");
assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com");
assertEquals(StringUtils.removeStart("domain.com", null), "domain.com");
}
@Test
public void testRemoveStartIgnoreCase() {
// StringUtils.removeStart("", *) = ""
assertNull("removeStartIgnoreCase(null, null)", StringUtils.removeStartIgnoreCase(null, null));
assertNull("removeStartIgnoreCase(null, \"\")", StringUtils.removeStartIgnoreCase(null, ""));
assertNull("removeStartIgnoreCase(null, \"a\")", StringUtils.removeStartIgnoreCase(null, "a"));
// StringUtils.removeStart(*, null) = *
assertEquals("removeStartIgnoreCase(\"\", null)", StringUtils.removeStartIgnoreCase("", null), "");
assertEquals("removeStartIgnoreCase(\"\", \"\")", StringUtils.removeStartIgnoreCase("", ""), "");
assertEquals("removeStartIgnoreCase(\"\", \"a\")", StringUtils.removeStartIgnoreCase("", "a"), "");
// All others:
assertEquals("removeStartIgnoreCase(\"www.domain.com\", \"www.\")", StringUtils.removeStartIgnoreCase("www.domain.com", "www."), "domain.com");
assertEquals("removeStartIgnoreCase(\"domain.com\", \"www.\")", StringUtils.removeStartIgnoreCase("domain.com", "www."), "domain.com");
assertEquals("removeStartIgnoreCase(\"domain.com\", \"\")", StringUtils.removeStartIgnoreCase("domain.com", ""), "domain.com");
assertEquals("removeStartIgnoreCase(\"domain.com\", null)", StringUtils.removeStartIgnoreCase("domain.com", null), "domain.com");
// Case insensitive:
assertEquals("removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")", StringUtils.removeStartIgnoreCase("www.domain.com", "WWW."), "domain.com");
}
@Test
public void testRemoveEnd() {
// StringUtils.removeEnd("", *) = ""
assertNull(StringUtils.removeEnd(null, null));
assertNull(StringUtils.removeEnd(null, ""));
assertNull(StringUtils.removeEnd(null, "a"));
// StringUtils.removeEnd(*, null) = *
assertEquals(StringUtils.removeEnd("", null), "");
assertEquals(StringUtils.removeEnd("", ""), "");
assertEquals(StringUtils.removeEnd("", "a"), "");
// All others:
assertEquals(StringUtils.removeEnd("www.domain.com.", ".com"), "www.domain.com.");
assertEquals(StringUtils.removeEnd("www.domain.com", ".com"), "www.domain");
assertEquals(StringUtils.removeEnd("www.domain", ".com"), "www.domain");
assertEquals(StringUtils.removeEnd("domain.com", ""), "domain.com");
assertEquals(StringUtils.removeEnd("domain.com", null), "domain.com");
}
@Test
public void testRemoveEndIgnoreCase() {
// StringUtils.removeEndIgnoreCase("", *) = ""
assertNull("removeEndIgnoreCase(null, null)", StringUtils.removeEndIgnoreCase(null, null));
assertNull("removeEndIgnoreCase(null, \"\")", StringUtils.removeEndIgnoreCase(null, ""));
assertNull("removeEndIgnoreCase(null, \"a\")", StringUtils.removeEndIgnoreCase(null, "a"));
// StringUtils.removeEnd(*, null) = *
assertEquals("removeEndIgnoreCase(\"\", null)", StringUtils.removeEndIgnoreCase("", null), "");
assertEquals("removeEndIgnoreCase(\"\", \"\")", StringUtils.removeEndIgnoreCase("", ""), "");
assertEquals("removeEndIgnoreCase(\"\", \"a\")", StringUtils.removeEndIgnoreCase("", "a"), "");
// All others:
assertEquals("removeEndIgnoreCase(\"www.domain.com.\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.com.", ".com"), "www.domain.com.");
assertEquals("removeEndIgnoreCase(\"www.domain.com\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.com", ".com"), "www.domain");
assertEquals("removeEndIgnoreCase(\"www.domain\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain", ".com"), "www.domain");
assertEquals("removeEndIgnoreCase(\"domain.com\", \"\")", StringUtils.removeEndIgnoreCase("domain.com", ""), "domain.com");
assertEquals("removeEndIgnoreCase(\"domain.com\", null)", StringUtils.removeEndIgnoreCase("domain.com", null), "domain.com");
// Case insensitive:
assertEquals("removeEndIgnoreCase(\"www.domain.com\", \".COM\")", StringUtils.removeEndIgnoreCase("www.domain.com", ".COM"), "www.domain");
assertEquals("removeEndIgnoreCase(\"www.domain.COM\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.COM", ".com"), "www.domain");
}
@Test
public void testRemove_String() {
// StringUtils.remove(null, *) = null
assertEquals(null, StringUtils.remove(null, null));
assertEquals(null, StringUtils.remove(null, ""));
assertEquals(null, StringUtils.remove(null, "a"));
// StringUtils.remove("", *) = ""
assertEquals("", StringUtils.remove("", null));
assertEquals("", StringUtils.remove("", ""));
assertEquals("", StringUtils.remove("", "a"));
// StringUtils.remove(*, null) = *
assertEquals(null, StringUtils.remove(null, null));
assertEquals("", StringUtils.remove("", null));
assertEquals("a", StringUtils.remove("a", null));
// StringUtils.remove(*, "") = *
assertEquals(null, StringUtils.remove(null, ""));
assertEquals("", StringUtils.remove("", ""));
assertEquals("a", StringUtils.remove("a", ""));
// StringUtils.remove("queued", "ue") = "qd"
assertEquals("qd", StringUtils.remove("queued", "ue"));
// StringUtils.remove("queued", "zz") = "queued"
assertEquals("queued", StringUtils.remove("queued", "zz"));
}
@Test
public void testRemove_char() {
// StringUtils.remove(null, *) = null
assertEquals(null, StringUtils.remove(null, 'a'));
assertEquals(null, StringUtils.remove(null, 'a'));
assertEquals(null, StringUtils.remove(null, 'a'));
// StringUtils.remove("", *) = ""
assertEquals("", StringUtils.remove("", 'a'));
assertEquals("", StringUtils.remove("", 'a'));
assertEquals("", StringUtils.remove("", 'a'));
// StringUtils.remove("queued", 'u') = "qeed"
assertEquals("qeed", StringUtils.remove("queued", 'u'));
// StringUtils.remove("queued", 'z') = "queued"
assertEquals("queued", StringUtils.remove("queued", 'z'));
}
@Test
public void testDifferenceAt_StringArray() {
assertEquals(-1, StringUtils.indexOfDifference((String[])null));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {"abc"}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {null, null}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {"", ""}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"", null}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"abc", null, null}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {null, null, "abc"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"", "abc"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"abc", ""}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {"abc", "abc"}));
assertEquals(1, StringUtils.indexOfDifference(new String[] {"abc", "a"}));
assertEquals(2, StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}));
assertEquals(2, StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}));
assertEquals(7, StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}));
}
@Test
public void testGetCommonPrefix_StringArray() {
assertEquals("", StringUtils.getCommonPrefix((String[])null));
assertEquals("", StringUtils.getCommonPrefix());
assertEquals("abc", StringUtils.getCommonPrefix("abc"));
assertEquals("", StringUtils.getCommonPrefix(null, null));
assertEquals("", StringUtils.getCommonPrefix("", ""));
assertEquals("", StringUtils.getCommonPrefix("", null));
assertEquals("", StringUtils.getCommonPrefix("abc", null, null));
assertEquals("", StringUtils.getCommonPrefix(null, null, "abc"));
assertEquals("", StringUtils.getCommonPrefix("", "abc"));
assertEquals("", StringUtils.getCommonPrefix("abc", ""));
assertEquals("abc", StringUtils.getCommonPrefix("abc", "abc"));
assertEquals("a", StringUtils.getCommonPrefix("abc", "a"));
assertEquals("ab", StringUtils.getCommonPrefix("ab", "abxyz"));
assertEquals("ab", StringUtils.getCommonPrefix("abcde", "abxyz"));
assertEquals("", StringUtils.getCommonPrefix("abcde", "xyz"));
assertEquals("", StringUtils.getCommonPrefix("xyz", "abcde"));
assertEquals("i am a ", StringUtils.getCommonPrefix("i am a machine", "i am a robot"));
}
@Test
public void testNormalizeSpace() {
assertEquals(null, StringUtils.normalizeSpace(null));
assertEquals("", StringUtils.normalizeSpace(""));
assertEquals("", StringUtils.normalizeSpace(" "));
assertEquals("", StringUtils.normalizeSpace("\t"));
assertEquals("", StringUtils.normalizeSpace("\n"));
assertEquals("", StringUtils.normalizeSpace("\u0009"));
assertEquals("", StringUtils.normalizeSpace("\u000B"));
assertEquals("", StringUtils.normalizeSpace("\u000C"));
assertEquals("", StringUtils.normalizeSpace("\u001C"));
assertEquals("", StringUtils.normalizeSpace("\u001D"));
assertEquals("", StringUtils.normalizeSpace("\u001E"));
assertEquals("", StringUtils.normalizeSpace("\u001F"));
assertEquals("", StringUtils.normalizeSpace("\f"));
assertEquals("", StringUtils.normalizeSpace("\r"));
assertEquals("a", StringUtils.normalizeSpace(" a "));
assertEquals("a b c", StringUtils.normalizeSpace(" a b c "));
assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r b\u000B c\n"));
}
@Test
public void testLANG666() {
assertEquals("12",StringUtils.stripEnd("120.00", ".0"));
assertEquals("121",StringUtils.stripEnd("121.00", ".0"));
}
// Methods on StringUtils that are immutable in spirit (i.e. calculate the length)
// should take a CharSequence parameter. Methods that are mutable in spirit (i.e. capitalize)
// should take a String or String[] parameter and return String or String[].
// This test enforces that this is done.
@Test
public void testStringUtilsCharSequenceContract() {
Class<StringUtils> c = StringUtils.class;
Method[] methods = c.getMethods();
for (Method m : methods) {
if (m.getReturnType() == String.class || m.getReturnType() == String[].class) {
// Assume this is mutable and ensure the first parameter is not CharSequence.
// It may be String or it may be something else (String[], Object, Object[]) so
// don't actively test for that.
Class<?>[] params = m.getParameterTypes();
if ( params.length > 0 && (params[0] == CharSequence.class || params[0] == CharSequence[].class)) {
fail("The method " + m + " appears to be mutable in spirit and therefore must not accept a CharSequence");
}
} else {
// Assume this is immutable in spirit and ensure the first parameter is not String.
// As above, it may be something other than CharSequence.
Class<?>[] params = m.getParameterTypes();
if ( params.length > 0 && (params[0] == String.class || params[0] == String[].class)) {
fail("The method " + m + " appears to be immutable in spirit and therefore must not accept a String");
}
}
}
}
/**
* Tests {@link StringUtils#toString(byte[], String)}
*
* @throws UnsupportedEncodingException
* @see StringUtils#toString(byte[], String)
*/
@Test
public void testToString() throws UnsupportedEncodingException {
final String expectedString = "The quick brown fox jumped over the lazy dog.";
String encoding = SystemUtils.FILE_ENCODING;
byte[] expectedBytes = expectedString.getBytes(encoding);
// sanity check start
assertArrayEquals(expectedBytes, expectedString.getBytes());
// sanity check end
assertEquals(expectedString, StringUtils.toString(expectedBytes, null));
assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding));
encoding = "UTF-16";
expectedBytes = expectedString.getBytes(encoding);
assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding));
}
@Test
public void testEscapeSurrogatePairs() throws Exception {
assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
// Examples from https://en.wikipedia.org/wiki/UTF-16
assertEquals("\uD800\uDC00", StringEscapeUtils.escapeCsv("\uD800\uDC00"));
assertEquals("\uD834\uDD1E", StringEscapeUtils.escapeCsv("\uD834\uDD1E"));
assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeCsv("\uDBFF\uDFFD"));
}
} | // You are a professional Java test case writer, please create a test case named `testEscapeSurrogatePairs` for the issue `Lang-LANG-857`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-857
//
// ## Issue-Title:
// StringIndexOutOfBoundsException in CharSequenceTranslator
//
// ## Issue-Description:
//
// I found that there is bad surrogate pair handling in the CharSequenceTranslator
//
//
// This is a simple test case for this problem.
//
// \uD83D\uDE30 is a surrogate pair.
//
//
//
//
// ```
// @Test
// public void testEscapeSurrogatePairs() throws Exception {
// assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
// }
//
// ```
//
//
// You'll get the exception as shown below.
//
//
//
//
// ```
// java.lang.StringIndexOutOfBoundsException: String index out of range: 2
// at java.lang.String.charAt(String.java:658)
// at java.lang.Character.codePointAt(Character.java:4668)
// at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:95)
// at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:59)
// at org.apache.commons.lang3.StringEscapeUtils.escapeCsv(StringEscapeUtils.java:556)
//
// ```
//
//
// Patch attached, the method affected:
//
//
// 1. public final void translate(CharSequence input, Writer out) throws IOException
//
//
//
//
//
@Test
public void testEscapeSurrogatePairs() throws Exception {
| 2,192 | 6 | 2,184 | src/test/java/org/apache/commons/lang3/StringUtilsTest.java | src/test/java | ```markdown
## Issue-ID: Lang-LANG-857
## Issue-Title:
StringIndexOutOfBoundsException in CharSequenceTranslator
## Issue-Description:
I found that there is bad surrogate pair handling in the CharSequenceTranslator
This is a simple test case for this problem.
\uD83D\uDE30 is a surrogate pair.
```
@Test
public void testEscapeSurrogatePairs() throws Exception {
assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
}
```
You'll get the exception as shown below.
```
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at java.lang.Character.codePointAt(Character.java:4668)
at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:95)
at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:59)
at org.apache.commons.lang3.StringEscapeUtils.escapeCsv(StringEscapeUtils.java:556)
```
Patch attached, the method affected:
1. public final void translate(CharSequence input, Writer out) throws IOException
```
You are a professional Java test case writer, please create a test case named `testEscapeSurrogatePairs` for the issue `Lang-LANG-857`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testEscapeSurrogatePairs() throws Exception {
```
| 2,184 | [
"org.apache.commons.lang3.text.translate.CharSequenceTranslator"
] | 577ff93581b5f08a349ed281d8c82741bd052f7b7ac119197ec6f58dad1e2282 | @Test
public void testEscapeSurrogatePairs() throws Exception | // You are a professional Java test case writer, please create a test case named `testEscapeSurrogatePairs` for the issue `Lang-LANG-857`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-857
//
// ## Issue-Title:
// StringIndexOutOfBoundsException in CharSequenceTranslator
//
// ## Issue-Description:
//
// I found that there is bad surrogate pair handling in the CharSequenceTranslator
//
//
// This is a simple test case for this problem.
//
// \uD83D\uDE30 is a surrogate pair.
//
//
//
//
// ```
// @Test
// public void testEscapeSurrogatePairs() throws Exception {
// assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
// }
//
// ```
//
//
// You'll get the exception as shown below.
//
//
//
//
// ```
// java.lang.StringIndexOutOfBoundsException: String index out of range: 2
// at java.lang.String.charAt(String.java:658)
// at java.lang.Character.codePointAt(Character.java:4668)
// at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:95)
// at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:59)
// at org.apache.commons.lang3.StringEscapeUtils.escapeCsv(StringEscapeUtils.java:556)
//
// ```
//
//
// Patch attached, the method affected:
//
//
// 1. public final void translate(CharSequence input, Writer out) throws IOException
//
//
//
//
//
| 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 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.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.CharBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Locale;
import org.apache.commons.lang3.text.WordUtils;
import org.junit.Test;
/**
* Unit tests {@link org.apache.commons.lang3.StringUtils}.
*
* @version $Id$
*/
public class StringUtilsTest {
static final String WHITESPACE;
static final String NON_WHITESPACE;
static final String TRIMMABLE;
static final String NON_TRIMMABLE;
static {
String ws = "";
String nws = "";
String tr = "";
String ntr = "";
for (int i = 0; i < Character.MAX_VALUE; i++) {
if (Character.isWhitespace((char) i)) {
ws += String.valueOf((char) i);
if (i > 32) {
ntr += String.valueOf((char) i);
}
} else if (i < 40) {
nws += String.valueOf((char) i);
}
}
for (int i = 0; i <= 32; i++) {
tr += String.valueOf((char) i);
}
WHITESPACE = ws;
NON_WHITESPACE = nws;
TRIMMABLE = tr;
NON_TRIMMABLE = ntr;
}
private static final String[] ARRAY_LIST = { "foo", "bar", "baz" };
private static final String[] EMPTY_ARRAY_LIST = {};
private static final String[] NULL_ARRAY_LIST = {null};
private static final Object[] NULL_TO_STRING_LIST = {
new Object(){
@Override
public String toString() {
return null;
}
}
};
private static final String[] MIXED_ARRAY_LIST = {null, "", "foo"};
private static final Object[] MIXED_TYPE_LIST = {"foo", Long.valueOf(2L)};
private static final long[] LONG_PRIM_LIST = {1, 2};
private static final int[] INT_PRIM_LIST = {1, 2};
private static final byte[] BYTE_PRIM_LIST = {1, 2};
private static final short[] SHORT_PRIM_LIST = {1, 2};
private static final char[] CHAR_PRIM_LIST = {'1', '2'};
private static final float[] FLOAT_PRIM_LIST = {1, 2};
private static final double[] DOUBLE_PRIM_LIST = {1, 2};
private static final String SEPARATOR = ",";
private static final char SEPARATOR_CHAR = ';';
private static final String TEXT_LIST = "foo,bar,baz";
private static final String TEXT_LIST_CHAR = "foo;bar;baz";
private static final String TEXT_LIST_NOSEP = "foobarbaz";
private static final String FOO_UNCAP = "foo";
private static final String FOO_CAP = "Foo";
private static final String SENTENCE_UNCAP = "foo bar baz";
private static final String SENTENCE_CAP = "Foo Bar Baz";
//-----------------------------------------------------------------------
@Test
public void testConstructor() {
assertNotNull(new StringUtils());
Constructor<?>[] cons = StringUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertTrue(Modifier.isPublic(cons[0].getModifiers()));
assertTrue(Modifier.isPublic(StringUtils.class.getModifiers()));
assertFalse(Modifier.isFinal(StringUtils.class.getModifiers()));
}
//-----------------------------------------------------------------------
@Test
public void testCaseFunctions() {
assertEquals(null, StringUtils.upperCase(null));
assertEquals(null, StringUtils.upperCase(null, Locale.ENGLISH));
assertEquals(null, StringUtils.lowerCase(null));
assertEquals(null, StringUtils.lowerCase(null, Locale.ENGLISH));
assertEquals(null, StringUtils.capitalize(null));
assertEquals(null, StringUtils.uncapitalize(null));
assertEquals("capitalize(empty-string) failed",
"", StringUtils.capitalize("") );
assertEquals("capitalize(single-char-string) failed",
"X", StringUtils.capitalize("x") );
assertEquals("uncapitalize(String) failed",
FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) );
assertEquals("uncapitalize(empty-string) failed",
"", StringUtils.uncapitalize("") );
assertEquals("uncapitalize(single-char-string) failed",
"x", StringUtils.uncapitalize("X") );
// reflection type of tests: Sentences.
assertEquals("uncapitalize(capitalize(String)) failed",
SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP)) );
assertEquals("capitalize(uncapitalize(String)) failed",
SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP)) );
// reflection type of tests: One word.
assertEquals("uncapitalize(capitalize(String)) failed",
FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP)) );
assertEquals("capitalize(uncapitalize(String)) failed",
FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP)) );
assertEquals("upperCase(String) failed",
"FOO TEST THING", StringUtils.upperCase("fOo test THING") );
assertEquals("upperCase(empty-string) failed",
"", StringUtils.upperCase("") );
assertEquals("lowerCase(String) failed",
"foo test thing", StringUtils.lowerCase("fOo test THING") );
assertEquals("lowerCase(empty-string) failed",
"", StringUtils.lowerCase("") );
assertEquals("upperCase(String, Locale) failed",
"FOO TEST THING", StringUtils.upperCase("fOo test THING", Locale.ENGLISH) );
assertEquals("upperCase(empty-string, Locale) failed",
"", StringUtils.upperCase("", Locale.ENGLISH) );
assertEquals("lowerCase(String, Locale) failed",
"foo test thing", StringUtils.lowerCase("fOo test THING", Locale.ENGLISH) );
assertEquals("lowerCase(empty-string, Locale) failed",
"", StringUtils.lowerCase("", Locale.ENGLISH) );
}
@Test
public void testSwapCase_String() {
assertEquals(null, StringUtils.swapCase(null));
assertEquals("", StringUtils.swapCase(""));
assertEquals(" ", StringUtils.swapCase(" "));
assertEquals("i", WordUtils.swapCase("I") );
assertEquals("I", WordUtils.swapCase("i") );
assertEquals("I AM HERE 123", StringUtils.swapCase("i am here 123") );
assertEquals("i aM hERE 123", StringUtils.swapCase("I Am Here 123") );
assertEquals("I AM here 123", StringUtils.swapCase("i am HERE 123") );
assertEquals("i am here 123", StringUtils.swapCase("I AM HERE 123") );
String test = "This String contains a TitleCase character: \u01C8";
String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9";
assertEquals(expect, WordUtils.swapCase(test));
}
//-----------------------------------------------------------------------
@Test
public void testJoin_Objects() {
assertEquals("abc", StringUtils.join("a", "b", "c"));
assertEquals("a", StringUtils.join(null, "", "a"));
assertEquals(null, StringUtils.join((Object[])null));
}
@Test
public void testJoin_Objectarray() {
// assertEquals(null, StringUtils.join(null)); // generates warning
assertEquals(null, StringUtils.join((Object[]) null)); // equivalent explicit cast
// test additional varargs calls
assertEquals("", StringUtils.join()); // empty array
assertEquals("", StringUtils.join((Object) null)); // => new Object[]{null}
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST));
assertEquals("", StringUtils.join(NULL_ARRAY_LIST));
assertEquals("null", StringUtils.join(NULL_TO_STRING_LIST));
assertEquals("abc", StringUtils.join(new String[] {"a", "b", "c"}));
assertEquals("a", StringUtils.join(new String[] {null, "a", ""}));
assertEquals("foo", StringUtils.join(MIXED_ARRAY_LIST));
assertEquals("foo2", StringUtils.join(MIXED_TYPE_LIST));
}
@Test
public void testJoin_ArrayCharSeparator() {
assertEquals(null, StringUtils.join((Object[]) null, ','));
assertEquals(TEXT_LIST_CHAR, StringUtils.join(ARRAY_LIST, SEPARATOR_CHAR));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR_CHAR));
assertEquals(";;foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR_CHAR));
assertEquals("foo;2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR_CHAR));
assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, '/', 0, MIXED_ARRAY_LIST.length-1));
assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 1));
assertEquals("null", StringUtils.join(NULL_TO_STRING_LIST,'/', 0, 1));
assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, '/', 0, 2));
assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, '/', 1, 2));
assertEquals("", StringUtils.join(MIXED_TYPE_LIST, '/', 2, 1));
}
@Test
public void testJoin_ArrayOfChars() {
assertEquals(null, StringUtils.join((char[]) null, ','));
assertEquals("1;2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(CHAR_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfBytes() {
assertEquals(null, StringUtils.join((byte[]) null, ','));
assertEquals("1;2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(BYTE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfInts() {
assertEquals(null, StringUtils.join((int[]) null, ','));
assertEquals("1;2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(INT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfLongs() {
assertEquals(null, StringUtils.join((long[]) null, ','));
assertEquals("1;2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(LONG_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfFloats() {
assertEquals(null, StringUtils.join((float[]) null, ','));
assertEquals("1.0;2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2.0", StringUtils.join(FLOAT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfDoubles() {
assertEquals(null, StringUtils.join((double[]) null, ','));
assertEquals("1.0;2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2.0", StringUtils.join(DOUBLE_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayOfShorts() {
assertEquals(null, StringUtils.join((short[]) null, ','));
assertEquals("1;2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR));
assertEquals("2", StringUtils.join(SHORT_PRIM_LIST, SEPARATOR_CHAR, 1, 2));
}
@Test
public void testJoin_ArrayString() {
assertEquals(null, StringUtils.join((Object[]) null, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(ARRAY_LIST, ""));
assertEquals("", StringUtils.join(NULL_ARRAY_LIST, null));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, null));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, ""));
assertEquals("", StringUtils.join(EMPTY_ARRAY_LIST, SEPARATOR));
assertEquals(TEXT_LIST, StringUtils.join(ARRAY_LIST, SEPARATOR));
assertEquals(",,foo", StringUtils.join(MIXED_ARRAY_LIST, SEPARATOR));
assertEquals("foo,2", StringUtils.join(MIXED_TYPE_LIST, SEPARATOR));
assertEquals("/", StringUtils.join(MIXED_ARRAY_LIST, "/", 0, MIXED_ARRAY_LIST.length-1));
assertEquals("", StringUtils.join(MIXED_ARRAY_LIST, "", 0, MIXED_ARRAY_LIST.length-1));
assertEquals("foo", StringUtils.join(MIXED_TYPE_LIST, "/", 0, 1));
assertEquals("foo/2", StringUtils.join(MIXED_TYPE_LIST, "/", 0, 2));
assertEquals("2", StringUtils.join(MIXED_TYPE_LIST, "/", 1, 2));
assertEquals("", StringUtils.join(MIXED_TYPE_LIST, "/", 2, 1));
}
@Test
public void testJoin_IteratorChar() {
assertEquals(null, StringUtils.join((Iterator<?>) null, ','));
assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR_CHAR));
assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), 'x'));
}
@Test
public void testJoin_IteratorString() {
assertEquals(null, StringUtils.join((Iterator<?>) null, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), ""));
assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), "x"));
assertEquals("foo", StringUtils.join(Collections.singleton("foo").iterator(), null));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST).iterator(), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), ""));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST).iterator(), SEPARATOR));
assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST).iterator(), SEPARATOR));
}
@Test
public void testJoin_IterableChar() {
assertEquals(null, StringUtils.join((Iterable<?>) null, ','));
assertEquals(TEXT_LIST_CHAR, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), SEPARATOR_CHAR));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR_CHAR));
assertEquals("foo", StringUtils.join(Collections.singleton("foo"), 'x'));
}
@Test
public void testJoin_IterableString() {
assertEquals(null, StringUtils.join((Iterable<?>) null, null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), null));
assertEquals(TEXT_LIST_NOSEP, StringUtils.join(Arrays.asList(ARRAY_LIST), ""));
assertEquals("foo", StringUtils.join(Collections.singleton("foo"), "x"));
assertEquals("foo", StringUtils.join(Collections.singleton("foo"), null));
assertEquals("", StringUtils.join(Arrays.asList(NULL_ARRAY_LIST), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), null));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), ""));
assertEquals("", StringUtils.join(Arrays.asList(EMPTY_ARRAY_LIST), SEPARATOR));
assertEquals(TEXT_LIST, StringUtils.join(Arrays.asList(ARRAY_LIST), SEPARATOR));
}
@Test
public void testSplit_String() {
assertArrayEquals(null, StringUtils.split(null));
assertEquals(0, StringUtils.split("").length);
String str = "a b .c";
String[] res = StringUtils.split(str);
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(".c", res[2]);
str = " a ";
res = StringUtils.split(str);
assertEquals(1, res.length);
assertEquals("a", res[0]);
str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c";
res = StringUtils.split(str);
assertEquals(2, res.length);
assertEquals("a", res[0]);
assertEquals("b" + NON_WHITESPACE + "c", res[1]);
}
@Test
public void testSplit_StringChar() {
assertArrayEquals(null, StringUtils.split(null, '.'));
assertEquals(0, StringUtils.split("", '.').length);
String str = "a.b.. c";
String[] res = StringUtils.split(str, '.');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(" c", res[2]);
str = ".a.";
res = StringUtils.split(str, '.');
assertEquals(1, res.length);
assertEquals("a", res[0]);
str = "a b c";
res = StringUtils.split(str,' ');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
}
@Test
public void testSplit_StringString_StringStringInt() {
assertArrayEquals(null, StringUtils.split(null, "."));
assertArrayEquals(null, StringUtils.split(null, ".", 3));
assertEquals(0, StringUtils.split("", ".").length);
assertEquals(0, StringUtils.split("", ".", 3).length);
innerTestSplit('.', ".", ' ');
innerTestSplit('.', ".", ',');
innerTestSplit('.', ".,", 'x');
for (int i = 0; i < WHITESPACE.length(); i++) {
for (int j = 0; j < NON_WHITESPACE.length(); j++) {
innerTestSplit(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j));
innerTestSplit(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j));
}
}
String[] results;
String[] expectedResults = {"ab", "de fg"};
results = StringUtils.split("ab de fg", null, 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
String[] expectedResults2 = {"ab", "cd:ef"};
results = StringUtils.split("ab:cd:ef",":", 2);
assertEquals(expectedResults2.length, results.length);
for (int i = 0; i < expectedResults2.length; i++) {
assertEquals(expectedResults2[i], results[i]);
}
}
private void innerTestSplit(char separator, String sepStr, char noMatch) {
String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
"), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
final String str = "a" + separator + "b" + separator + separator + noMatch + "c";
String[] res;
// (str, sepStr)
res = StringUtils.split(str, sepStr);
assertEquals(msg, 3, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, noMatch + "c", res[2]);
final String str2 = separator + "a" + separator;
res = StringUtils.split(str2, sepStr);
assertEquals(msg, 1, res.length);
assertEquals(msg, "a", res[0]);
res = StringUtils.split(str, sepStr, -1);
assertEquals(msg, 3, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, noMatch + "c", res[2]);
res = StringUtils.split(str, sepStr, 0);
assertEquals(msg, 3, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, noMatch + "c", res[2]);
res = StringUtils.split(str, sepStr, 1);
assertEquals(msg, 1, res.length);
assertEquals(msg, str, res[0]);
res = StringUtils.split(str, sepStr, 2);
assertEquals(msg, 2, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, str.substring(2), res[1]);
}
@Test
public void testSplitByWholeString_StringStringBoolean() {
assertArrayEquals( null, StringUtils.splitByWholeSeparator( null, "." ) ) ;
assertEquals( 0, StringUtils.splitByWholeSeparator( "", "." ).length ) ;
String stringToSplitOnNulls = "ab de fg" ;
String[] splitOnNullExpectedResults = { "ab", "de", "fg" } ;
String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null ) ;
assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
}
String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiously" ;
String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy" ) ;
assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i+= 1 ) {
assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
}
String[] splitWithMultipleSeparatorExpectedResults = {"ab", "cd", "ef"};
String[] splitWithMultipleSeparator = StringUtils.splitByWholeSeparator("ab:cd::ef", ":");
assertEquals( splitWithMultipleSeparatorExpectedResults.length, splitWithMultipleSeparator.length );
for( int i = 0; i < splitWithMultipleSeparatorExpectedResults.length ; i++ ) {
assertEquals( splitWithMultipleSeparatorExpectedResults[i], splitWithMultipleSeparator[i] ) ;
}
}
@Test
public void testSplitByWholeString_StringStringBooleanInt() {
assertArrayEquals( null, StringUtils.splitByWholeSeparator( null, ".", 3 ) ) ;
assertEquals( 0, StringUtils.splitByWholeSeparator( "", ".", 3 ).length ) ;
String stringToSplitOnNulls = "ab de fg" ;
String[] splitOnNullExpectedResults = { "ab", "de fg" } ;
//String[] splitOnNullExpectedResults = { "ab", "de" } ;
String[] splitOnNullResults = StringUtils.splitByWholeSeparator( stringToSplitOnNulls, null, 2 ) ;
assertEquals( splitOnNullExpectedResults.length, splitOnNullResults.length ) ;
for ( int i = 0 ; i < splitOnNullExpectedResults.length ; i+= 1 ) {
assertEquals( splitOnNullExpectedResults[i], splitOnNullResults[i] ) ;
}
String stringToSplitOnCharactersAndString = "abstemiouslyaeiouyabstemiouslyaeiouyabstemiously" ;
String[] splitOnStringExpectedResults = { "abstemiously", "abstemiouslyaeiouyabstemiously" } ;
//String[] splitOnStringExpectedResults = { "abstemiously", "abstemiously" } ;
String[] splitOnStringResults = StringUtils.splitByWholeSeparator( stringToSplitOnCharactersAndString, "aeiouy", 2 ) ;
assertEquals( splitOnStringExpectedResults.length, splitOnStringResults.length ) ;
for ( int i = 0 ; i < splitOnStringExpectedResults.length ; i++ ) {
assertEquals( splitOnStringExpectedResults[i], splitOnStringResults[i] ) ;
}
}
@Test
public void testSplitByWholeSeparatorPreserveAllTokens_StringStringInt() {
assertArrayEquals( null, StringUtils.splitByWholeSeparatorPreserveAllTokens( null, ".", -1 ) ) ;
assertEquals( 0, StringUtils.splitByWholeSeparatorPreserveAllTokens( "", ".", -1 ).length ) ;
// test whitespace
String input = "ab de fg" ;
String[] expected = new String[] { "ab", "", "", "de", "fg" } ;
String[] actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, null, -1 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
// test delimiter singlechar
input = "1::2:::3::::4";
expected = new String[] { "1", "", "2", "", "", "3", "", "", "", "4" };
actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, ":", -1 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
// test delimiter multichar
input = "1::2:::3::::4";
expected = new String[] { "1", "2", ":3", "", "4" };
actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, "::", -1 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
// test delimiter char with max
input = "1::2::3:4";
expected = new String[] { "1", "", "2", ":3:4" };
actual = StringUtils.splitByWholeSeparatorPreserveAllTokens( input, ":", 4 ) ;
assertEquals( expected.length, actual.length ) ;
for ( int i = 0 ; i < actual.length ; i+= 1 ) {
assertEquals( expected[i], actual[i] );
}
}
@Test
public void testSplitPreserveAllTokens_String() {
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null));
assertEquals(0, StringUtils.splitPreserveAllTokens("").length);
String str = "abc def";
String[] res = StringUtils.splitPreserveAllTokens(str);
assertEquals(2, res.length);
assertEquals("abc", res[0]);
assertEquals("def", res[1]);
str = "abc def";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(3, res.length);
assertEquals("abc", res[0]);
assertEquals("", res[1]);
assertEquals("def", res[2]);
str = " abc ";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(3, res.length);
assertEquals("", res[0]);
assertEquals("abc", res[1]);
assertEquals("", res[2]);
str = "a b .c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(".c", res[2]);
str = " a b .c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("b", res[2]);
assertEquals(".c", res[3]);
str = "a b .c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(5, res.length);
assertEquals("a", res[0]);
assertEquals("", res[1]);
assertEquals("b", res[2]);
assertEquals("", res[3]);
assertEquals(".c", res[4]);
str = " a ";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
assertEquals("", res[3]);
str = " a b";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
assertEquals("b", res[3]);
str = "a" + WHITESPACE + "b" + NON_WHITESPACE + "c";
res = StringUtils.splitPreserveAllTokens(str);
assertEquals(WHITESPACE.length() + 1, res.length);
assertEquals("a", res[0]);
for(int i = 1; i < WHITESPACE.length()-1; i++)
{
assertEquals("", res[i]);
}
assertEquals("b" + NON_WHITESPACE + "c", res[WHITESPACE.length()]);
}
@Test
public void testSplitPreserveAllTokens_StringChar() {
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null, '.'));
assertEquals(0, StringUtils.splitPreserveAllTokens("", '.').length);
String str = "a.b. c";
String[] res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals(" c", res[2]);
str = "a.b.. c";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(4, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("", res[2]);
assertEquals(" c", res[3]);
str = ".a.";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(3, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
str = ".a..";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("", res[2]);
assertEquals("", res[3]);
str = "..a.";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("", res[1]);
assertEquals("a", res[2]);
assertEquals("", res[3]);
str = "..a";
res = StringUtils.splitPreserveAllTokens(str, '.');
assertEquals(3, res.length);
assertEquals("", res[0]);
assertEquals("", res[1]);
assertEquals("a", res[2]);
str = "a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(3, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
str = "a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(5, res.length);
assertEquals("a", res[0]);
assertEquals("", res[1]);
assertEquals("b", res[2]);
assertEquals("", res[3]);
assertEquals("c", res[4]);
str = " a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(4, res.length);
assertEquals("", res[0]);
assertEquals("a", res[1]);
assertEquals("b", res[2]);
assertEquals("c", res[3]);
str = " a b c";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(5, res.length);
assertEquals("", res[0]);
assertEquals("", res[1]);
assertEquals("a", res[2]);
assertEquals("b", res[3]);
assertEquals("c", res[4]);
str = "a b c ";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(4, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
assertEquals("", res[3]);
str = "a b c ";
res = StringUtils.splitPreserveAllTokens(str,' ');
assertEquals(5, res.length);
assertEquals("a", res[0]);
assertEquals("b", res[1]);
assertEquals("c", res[2]);
assertEquals("", res[3]);
assertEquals("", res[3]);
// Match example in javadoc
{
String[] results;
String[] expectedResults = {"a", "", "b", "c"};
results = StringUtils.splitPreserveAllTokens("a..b.c",'.');
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
}
@Test
public void testSplitPreserveAllTokens_StringString_StringStringInt() {
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null, "."));
assertArrayEquals(null, StringUtils.splitPreserveAllTokens(null, ".", 3));
assertEquals(0, StringUtils.splitPreserveAllTokens("", ".").length);
assertEquals(0, StringUtils.splitPreserveAllTokens("", ".", 3).length);
innerTestSplitPreserveAllTokens('.', ".", ' ');
innerTestSplitPreserveAllTokens('.', ".", ',');
innerTestSplitPreserveAllTokens('.', ".,", 'x');
for (int i = 0; i < WHITESPACE.length(); i++) {
for (int j = 0; j < NON_WHITESPACE.length(); j++) {
innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), null, NON_WHITESPACE.charAt(j));
innerTestSplitPreserveAllTokens(WHITESPACE.charAt(i), String.valueOf(WHITESPACE.charAt(i)), NON_WHITESPACE.charAt(j));
}
}
{
String[] results;
String[] expectedResults = {"ab", "de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", " de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "::de:fg"};
results = StringUtils.splitPreserveAllTokens("ab:::de:fg", ":", 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", " de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 3);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", "", "de fg"};
results = StringUtils.splitPreserveAllTokens("ab de fg", null, 4);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] expectedResults = {"ab", "cd:ef"};
String[] results;
results = StringUtils.splitPreserveAllTokens("ab:cd:ef",":", 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", ":cd:ef"};
results = StringUtils.splitPreserveAllTokens("ab::cd:ef",":", 2);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", ":cd:ef"};
results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 3);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"ab", "", "", "cd:ef"};
results = StringUtils.splitPreserveAllTokens("ab:::cd:ef",":", 4);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"", "ab", "", "", "cd:ef"};
results = StringUtils.splitPreserveAllTokens(":ab:::cd:ef",":", 5);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
{
String[] results;
String[] expectedResults = {"", "", "ab", "", "", "cd:ef"};
results = StringUtils.splitPreserveAllTokens("::ab:::cd:ef",":", 6);
assertEquals(expectedResults.length, results.length);
for (int i = 0; i < expectedResults.length; i++) {
assertEquals(expectedResults[i], results[i]);
}
}
}
private void innerTestSplitPreserveAllTokens(char separator, String sepStr, char noMatch) {
String msg = "Failed on separator hex(" + Integer.toHexString(separator) +
"), noMatch hex(" + Integer.toHexString(noMatch) + "), sepStr(" + sepStr + ")";
final String str = "a" + separator + "b" + separator + separator + noMatch + "c";
String[] res;
// (str, sepStr)
res = StringUtils.splitPreserveAllTokens(str, sepStr);
assertEquals(msg, 4, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, "", res[2]);
assertEquals(msg, noMatch + "c", res[3]);
final String str2 = separator + "a" + separator;
res = StringUtils.splitPreserveAllTokens(str2, sepStr);
assertEquals(msg, 3, res.length);
assertEquals(msg, "", res[0]);
assertEquals(msg, "a", res[1]);
assertEquals(msg, "", res[2]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, -1);
assertEquals(msg, 4, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, "", res[2]);
assertEquals(msg, noMatch + "c", res[3]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, 0);
assertEquals(msg, 4, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, "b", res[1]);
assertEquals(msg, "", res[2]);
assertEquals(msg, noMatch + "c", res[3]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, 1);
assertEquals(msg, 1, res.length);
assertEquals(msg, str, res[0]);
res = StringUtils.splitPreserveAllTokens(str, sepStr, 2);
assertEquals(msg, 2, res.length);
assertEquals(msg, "a", res[0]);
assertEquals(msg, str.substring(2), res[1]);
}
@Test
public void testSplitByCharacterType() {
assertNull(StringUtils.splitByCharacterType(null));
assertEquals(0, StringUtils.splitByCharacterType("").length);
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterType("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterType("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", ":", "cd", ":",
"ef" }, StringUtils.splitByCharacterType("ab:cd:ef")));
assertTrue(ArrayUtils.isEquals(new String[] { "number", "5" },
StringUtils.splitByCharacterType("number5")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "B", "ar" },
StringUtils.splitByCharacterType("fooBar")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "200", "B", "ar" },
StringUtils.splitByCharacterType("foo200Bar")));
assertTrue(ArrayUtils.isEquals(new String[] { "ASFR", "ules" },
StringUtils.splitByCharacterType("ASFRules")));
}
@Test
public void testSplitByCharacterTypeCamelCase() {
assertNull(StringUtils.splitByCharacterTypeCamelCase(null));
assertEquals(0, StringUtils.splitByCharacterTypeCamelCase("").length);
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterTypeCamelCase("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", " ", "de", " ",
"fg" }, StringUtils.splitByCharacterTypeCamelCase("ab de fg")));
assertTrue(ArrayUtils.isEquals(new String[] { "ab", ":", "cd", ":",
"ef" }, StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef")));
assertTrue(ArrayUtils.isEquals(new String[] { "number", "5" },
StringUtils.splitByCharacterTypeCamelCase("number5")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "Bar" },
StringUtils.splitByCharacterTypeCamelCase("fooBar")));
assertTrue(ArrayUtils.isEquals(new String[] { "foo", "200", "Bar" },
StringUtils.splitByCharacterTypeCamelCase("foo200Bar")));
assertTrue(ArrayUtils.isEquals(new String[] { "ASF", "Rules" },
StringUtils.splitByCharacterTypeCamelCase("ASFRules")));
}
@Test
public void testDeleteWhitespace_String() {
assertEquals(null, StringUtils.deleteWhitespace(null));
assertEquals("", StringUtils.deleteWhitespace(""));
assertEquals("", StringUtils.deleteWhitespace(" \u000C \t\t\u001F\n\n \u000B "));
assertEquals("", StringUtils.deleteWhitespace(StringUtilsTest.WHITESPACE));
assertEquals(StringUtilsTest.NON_WHITESPACE, StringUtils.deleteWhitespace(StringUtilsTest.NON_WHITESPACE));
// Note: u-2007 and u-000A both cause problems in the source code
// it should ignore 2007 but delete 000A
assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace(" \u00A0 \t\t\n\n \u202F "));
assertEquals("\u00A0\u202F", StringUtils.deleteWhitespace("\u00A0\u202F"));
assertEquals("test", StringUtils.deleteWhitespace("\u000Bt \t\n\u0009e\rs\n\n \tt"));
}
@Test
public void testLang623() {
assertEquals("t", StringUtils.replaceChars("\u00DE", '\u00DE', 't'));
assertEquals("t", StringUtils.replaceChars("\u00FE", '\u00FE', 't'));
}
@Test
public void testReplace_StringStringString() {
assertEquals(null, StringUtils.replace(null, null, null));
assertEquals(null, StringUtils.replace(null, null, "any"));
assertEquals(null, StringUtils.replace(null, "any", null));
assertEquals(null, StringUtils.replace(null, "any", "any"));
assertEquals("", StringUtils.replace("", null, null));
assertEquals("", StringUtils.replace("", null, "any"));
assertEquals("", StringUtils.replace("", "any", null));
assertEquals("", StringUtils.replace("", "any", "any"));
assertEquals("FOO", StringUtils.replace("FOO", "", "any"));
assertEquals("FOO", StringUtils.replace("FOO", null, "any"));
assertEquals("FOO", StringUtils.replace("FOO", "F", null));
assertEquals("FOO", StringUtils.replace("FOO", null, null));
assertEquals("", StringUtils.replace("foofoofoo", "foo", ""));
assertEquals("barbarbar", StringUtils.replace("foofoofoo", "foo", "bar"));
assertEquals("farfarfar", StringUtils.replace("foofoofoo", "oo", "ar"));
}
@Test
public void testReplacePattern() {
assertEquals("X", StringUtils.replacePattern("<A>\nxy\n</A>", "<A>.*</A>", "X"));
}
@Test
public void testRemovePattern() {
assertEquals("", StringUtils.removePattern("<A>x\\ny</A>", "<A>.*</A>"));
}
@Test
public void testReplace_StringStringStringInt() {
assertEquals(null, StringUtils.replace(null, null, null, 2));
assertEquals(null, StringUtils.replace(null, null, "any", 2));
assertEquals(null, StringUtils.replace(null, "any", null, 2));
assertEquals(null, StringUtils.replace(null, "any", "any", 2));
assertEquals("", StringUtils.replace("", null, null, 2));
assertEquals("", StringUtils.replace("", null, "any", 2));
assertEquals("", StringUtils.replace("", "any", null, 2));
assertEquals("", StringUtils.replace("", "any", "any", 2));
String str = new String(new char[] {'o', 'o', 'f', 'o', 'o'});
assertSame(str, StringUtils.replace(str, "x", "", -1));
assertEquals("f", StringUtils.replace("oofoo", "o", "", -1));
assertEquals("oofoo", StringUtils.replace("oofoo", "o", "", 0));
assertEquals("ofoo", StringUtils.replace("oofoo", "o", "", 1));
assertEquals("foo", StringUtils.replace("oofoo", "o", "", 2));
assertEquals("fo", StringUtils.replace("oofoo", "o", "", 3));
assertEquals("f", StringUtils.replace("oofoo", "o", "", 4));
assertEquals("f", StringUtils.replace("oofoo", "o", "", -5));
assertEquals("f", StringUtils.replace("oofoo", "o", "", 1000));
}
@Test
public void testReplaceOnce_StringStringString() {
assertEquals(null, StringUtils.replaceOnce(null, null, null));
assertEquals(null, StringUtils.replaceOnce(null, null, "any"));
assertEquals(null, StringUtils.replaceOnce(null, "any", null));
assertEquals(null, StringUtils.replaceOnce(null, "any", "any"));
assertEquals("", StringUtils.replaceOnce("", null, null));
assertEquals("", StringUtils.replaceOnce("", null, "any"));
assertEquals("", StringUtils.replaceOnce("", "any", null));
assertEquals("", StringUtils.replaceOnce("", "any", "any"));
assertEquals("FOO", StringUtils.replaceOnce("FOO", "", "any"));
assertEquals("FOO", StringUtils.replaceOnce("FOO", null, "any"));
assertEquals("FOO", StringUtils.replaceOnce("FOO", "F", null));
assertEquals("FOO", StringUtils.replaceOnce("FOO", null, null));
assertEquals("foofoo", StringUtils.replaceOnce("foofoofoo", "foo", ""));
}
/**
* Test method for 'StringUtils.replaceEach(String, String[], String[])'
*/
@Test
public void testReplace_StringStringArrayStringArray() {
//JAVADOC TESTS START
assertNull(StringUtils.replaceEach(null, new String[]{"a"}, new String[]{"b"}));
assertEquals(StringUtils.replaceEach("", new String[]{"a"}, new String[]{"b"}),"");
assertEquals(StringUtils.replaceEach("aba", null, null),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[0], null),"aba");
assertEquals(StringUtils.replaceEach("aba", null, new String[0]),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, null),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}),"b");
assertEquals(StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}),"aba");
assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}),"wcte");
assertEquals(StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}),"dcte");
//JAVADOC TESTS END
assertEquals("bcc", StringUtils.replaceEach("abc", new String[]{"a", "b"}, new String[]{"b", "c"}));
assertEquals("q651.506bera", StringUtils.replaceEach("d216.102oren",
new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D",
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9"},
new String[]{"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "a",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "N", "O", "P", "Q",
"R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "5", "6", "7", "8", "9", "1", "2", "3", "4"}));
// Test null safety inside arrays - LANG-552
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{null}),"aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a", "b"}, new String[]{"c", null}),"cbc");
}
/**
* Test method for 'StringUtils.replaceEachRepeatedly(String, String[], String[])'
*/
@Test
public void testReplace_StringStringArrayStringArrayBoolean() {
//JAVADOC TESTS START
assertNull(StringUtils.replaceEachRepeatedly(null, new String[]{"a"}, new String[]{"b"}));
assertEquals(StringUtils.replaceEachRepeatedly("", new String[]{"a"}, new String[]{"b"}),"");
assertEquals(StringUtils.replaceEachRepeatedly("aba", null, null),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", null, new String[0]),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[0], null),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}),"b");
assertEquals(StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}),"aba");
assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}),"wcte");
assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}),"tcte");
try {
StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"});
fail("Should be a circular reference");
} catch (IllegalStateException e) {}
//JAVADOC TESTS END
}
@Test
public void testReplaceChars_StringCharChar() {
assertEquals(null, StringUtils.replaceChars(null, 'b', 'z'));
assertEquals("", StringUtils.replaceChars("", 'b', 'z'));
assertEquals("azcza", StringUtils.replaceChars("abcba", 'b', 'z'));
assertEquals("abcba", StringUtils.replaceChars("abcba", 'x', 'z'));
}
@Test
public void testReplaceChars_StringStringString() {
assertEquals(null, StringUtils.replaceChars(null, null, null));
assertEquals(null, StringUtils.replaceChars(null, "", null));
assertEquals(null, StringUtils.replaceChars(null, "a", null));
assertEquals(null, StringUtils.replaceChars(null, null, ""));
assertEquals(null, StringUtils.replaceChars(null, null, "x"));
assertEquals("", StringUtils.replaceChars("", null, null));
assertEquals("", StringUtils.replaceChars("", "", null));
assertEquals("", StringUtils.replaceChars("", "a", null));
assertEquals("", StringUtils.replaceChars("", null, ""));
assertEquals("", StringUtils.replaceChars("", null, "x"));
assertEquals("abc", StringUtils.replaceChars("abc", null, null));
assertEquals("abc", StringUtils.replaceChars("abc", null, ""));
assertEquals("abc", StringUtils.replaceChars("abc", null, "x"));
assertEquals("abc", StringUtils.replaceChars("abc", "", null));
assertEquals("abc", StringUtils.replaceChars("abc", "", ""));
assertEquals("abc", StringUtils.replaceChars("abc", "", "x"));
assertEquals("ac", StringUtils.replaceChars("abc", "b", null));
assertEquals("ac", StringUtils.replaceChars("abc", "b", ""));
assertEquals("axc", StringUtils.replaceChars("abc", "b", "x"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz"));
assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx"));
assertEquals("abcba", StringUtils.replaceChars("abcba", "z", "w"));
assertSame("abcba", StringUtils.replaceChars("abcba", "z", "w"));
// Javadoc examples:
assertEquals("jelly", StringUtils.replaceChars("hello", "ho", "jy"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yz"));
assertEquals("ayya", StringUtils.replaceChars("abcba", "bc", "y"));
assertEquals("ayzya", StringUtils.replaceChars("abcba", "bc", "yzx"));
// From http://issues.apache.org/bugzilla/show_bug.cgi?id=25454
assertEquals("bcc", StringUtils.replaceChars("abc", "ab", "bc"));
assertEquals("q651.506bera", StringUtils.replaceChars("d216.102oren",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM567891234"));
}
@Test
public void testOverlay_StringStringIntInt() {
assertEquals(null, StringUtils.overlay(null, null, 2, 4));
assertEquals(null, StringUtils.overlay(null, null, -2, -4));
assertEquals("", StringUtils.overlay("", null, 0, 0));
assertEquals("", StringUtils.overlay("", "", 0, 0));
assertEquals("zzzz", StringUtils.overlay("", "zzzz", 0, 0));
assertEquals("zzzz", StringUtils.overlay("", "zzzz", 2, 4));
assertEquals("zzzz", StringUtils.overlay("", "zzzz", -2, -4));
assertEquals("abef", StringUtils.overlay("abcdef", null, 2, 4));
assertEquals("abef", StringUtils.overlay("abcdef", null, 4, 2));
assertEquals("abef", StringUtils.overlay("abcdef", "", 2, 4));
assertEquals("abef", StringUtils.overlay("abcdef", "", 4, 2));
assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 2, 4));
assertEquals("abzzzzef", StringUtils.overlay("abcdef", "zzzz", 4, 2));
assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", -1, 4));
assertEquals("zzzzef", StringUtils.overlay("abcdef", "zzzz", 4, -1));
assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -2, -1));
assertEquals("zzzzabcdef", StringUtils.overlay("abcdef", "zzzz", -1, -2));
assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 4, 10));
assertEquals("abcdzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 4));
assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 8, 10));
assertEquals("abcdefzzzz", StringUtils.overlay("abcdef", "zzzz", 10, 8));
}
@Test
public void testRepeat_StringInt() {
assertEquals(null, StringUtils.repeat(null, 2));
assertEquals("", StringUtils.repeat("ab", 0));
assertEquals("", StringUtils.repeat("", 3));
assertEquals("aaa", StringUtils.repeat("a", 3));
assertEquals("ababab", StringUtils.repeat("ab", 3));
assertEquals("abcabcabc", StringUtils.repeat("abc", 3));
String str = StringUtils.repeat("a", 10000); // bigger than pad limit
assertEquals(10000, str.length());
assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
}
@Test
public void testRepeat_StringStringInt() {
assertEquals(null, StringUtils.repeat(null, null, 2));
assertEquals(null, StringUtils.repeat(null, "x", 2));
assertEquals("", StringUtils.repeat("", null, 2));
assertEquals("", StringUtils.repeat("ab", "", 0));
assertEquals("", StringUtils.repeat("", "", 2));
assertEquals("xx", StringUtils.repeat("", "x", 3));
assertEquals("?, ?, ?", StringUtils.repeat("?", ", ", 3));
}
@Test
public void testChop() {
String[][] chopCases = {
{ FOO_UNCAP + "\r\n", FOO_UNCAP } ,
{ FOO_UNCAP + "\n" , FOO_UNCAP } ,
{ FOO_UNCAP + "\r", FOO_UNCAP },
{ FOO_UNCAP + " \r", FOO_UNCAP + " " },
{ "foo", "fo"},
{ "foo\nfoo", "foo\nfo" },
{ "\n", "" },
{ "\r", "" },
{ "\r\n", "" },
{ null, null },
{ "", "" },
{ "a", "" },
};
for (String[] chopCase : chopCases) {
String original = chopCase[0];
String expectedResult = chopCase[1];
assertEquals("chop(String) failed",
expectedResult, StringUtils.chop(original));
}
}
@SuppressWarnings("deprecation") // intentional test of deprecated method
@Test
public void testChomp() {
String[][] chompCases = {
{ FOO_UNCAP + "\r\n", FOO_UNCAP },
{ FOO_UNCAP + "\n" , FOO_UNCAP },
{ FOO_UNCAP + "\r", FOO_UNCAP },
{ FOO_UNCAP + " \r", FOO_UNCAP + " " },
{ FOO_UNCAP, FOO_UNCAP },
{ FOO_UNCAP + "\n\n", FOO_UNCAP + "\n"},
{ FOO_UNCAP + "\r\n\r\n", FOO_UNCAP + "\r\n" },
{ "foo\nfoo", "foo\nfoo" },
{ "foo\n\rfoo", "foo\n\rfoo" },
{ "\n", "" },
{ "\r", "" },
{ "a", "a" },
{ "\r\n", "" },
{ "", "" },
{ null, null },
{ FOO_UNCAP + "\n\r", FOO_UNCAP + "\n"}
};
for (String[] chompCase : chompCases) {
String original = chompCase[0];
String expectedResult = chompCase[1];
assertEquals("chomp(String) failed",
expectedResult, StringUtils.chomp(original));
}
assertEquals("chomp(String, String) failed",
"foo", StringUtils.chomp("foobar", "bar"));
assertEquals("chomp(String, String) failed",
"foobar", StringUtils.chomp("foobar", "baz"));
assertEquals("chomp(String, String) failed",
"foo", StringUtils.chomp("foo", "foooo"));
assertEquals("chomp(String, String) failed",
"foobar", StringUtils.chomp("foobar", ""));
assertEquals("chomp(String, String) failed",
"foobar", StringUtils.chomp("foobar", null));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("", "foo"));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("", null));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("", ""));
assertEquals("chomp(String, String) failed",
null, StringUtils.chomp(null, "foo"));
assertEquals("chomp(String, String) failed",
null, StringUtils.chomp(null, null));
assertEquals("chomp(String, String) failed",
null, StringUtils.chomp(null, ""));
assertEquals("chomp(String, String) failed",
"", StringUtils.chomp("foo", "foo"));
assertEquals("chomp(String, String) failed",
" ", StringUtils.chomp(" foo", "foo"));
assertEquals("chomp(String, String) failed",
"foo ", StringUtils.chomp("foo ", "foo"));
}
//-----------------------------------------------------------------------
@Test
public void testRightPad_StringInt() {
assertEquals(null, StringUtils.rightPad(null, 5));
assertEquals(" ", StringUtils.rightPad("", 5));
assertEquals("abc ", StringUtils.rightPad("abc", 5));
assertEquals("abc", StringUtils.rightPad("abc", 2));
assertEquals("abc", StringUtils.rightPad("abc", -1));
}
@Test
public void testRightPad_StringIntChar() {
assertEquals(null, StringUtils.rightPad(null, 5, ' '));
assertEquals(" ", StringUtils.rightPad("", 5, ' '));
assertEquals("abc ", StringUtils.rightPad("abc", 5, ' '));
assertEquals("abc", StringUtils.rightPad("abc", 2, ' '));
assertEquals("abc", StringUtils.rightPad("abc", -1, ' '));
assertEquals("abcxx", StringUtils.rightPad("abc", 5, 'x'));
String str = StringUtils.rightPad("aaa", 10000, 'a'); // bigger than pad length
assertEquals(10000, str.length());
assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
}
@Test
public void testRightPad_StringIntString() {
assertEquals(null, StringUtils.rightPad(null, 5, "-+"));
assertEquals(" ", StringUtils.rightPad("", 5, " "));
assertEquals(null, StringUtils.rightPad(null, 8, null));
assertEquals("abc-+-+", StringUtils.rightPad("abc", 7, "-+"));
assertEquals("abc-+~", StringUtils.rightPad("abc", 6, "-+~"));
assertEquals("abc-+", StringUtils.rightPad("abc", 5, "-+~"));
assertEquals("abc", StringUtils.rightPad("abc", 2, " "));
assertEquals("abc", StringUtils.rightPad("abc", -1, " "));
assertEquals("abc ", StringUtils.rightPad("abc", 5, null));
assertEquals("abc ", StringUtils.rightPad("abc", 5, ""));
}
//-----------------------------------------------------------------------
@Test
public void testLeftPad_StringInt() {
assertEquals(null, StringUtils.leftPad(null, 5));
assertEquals(" ", StringUtils.leftPad("", 5));
assertEquals(" abc", StringUtils.leftPad("abc", 5));
assertEquals("abc", StringUtils.leftPad("abc", 2));
}
@Test
public void testLeftPad_StringIntChar() {
assertEquals(null, StringUtils.leftPad(null, 5, ' '));
assertEquals(" ", StringUtils.leftPad("", 5, ' '));
assertEquals(" abc", StringUtils.leftPad("abc", 5, ' '));
assertEquals("xxabc", StringUtils.leftPad("abc", 5, 'x'));
assertEquals("\uffff\uffffabc", StringUtils.leftPad("abc", 5, '\uffff'));
assertEquals("abc", StringUtils.leftPad("abc", 2, ' '));
String str = StringUtils.leftPad("aaa", 10000, 'a'); // bigger than pad length
assertEquals(10000, str.length());
assertTrue(StringUtils.containsOnly(str, new char[] {'a'}));
}
@Test
public void testLeftPad_StringIntString() {
assertEquals(null, StringUtils.leftPad(null, 5, "-+"));
assertEquals(null, StringUtils.leftPad(null, 5, null));
assertEquals(" ", StringUtils.leftPad("", 5, " "));
assertEquals("-+-+abc", StringUtils.leftPad("abc", 7, "-+"));
assertEquals("-+~abc", StringUtils.leftPad("abc", 6, "-+~"));
assertEquals("-+abc", StringUtils.leftPad("abc", 5, "-+~"));
assertEquals("abc", StringUtils.leftPad("abc", 2, " "));
assertEquals("abc", StringUtils.leftPad("abc", -1, " "));
assertEquals(" abc", StringUtils.leftPad("abc", 5, null));
assertEquals(" abc", StringUtils.leftPad("abc", 5, ""));
}
@Test
public void testLengthString() {
assertEquals(0, StringUtils.length(null));
assertEquals(0, StringUtils.length(""));
assertEquals(0, StringUtils.length(StringUtils.EMPTY));
assertEquals(1, StringUtils.length("A"));
assertEquals(1, StringUtils.length(" "));
assertEquals(8, StringUtils.length("ABCDEFGH"));
}
@Test
public void testLengthStringBuffer() {
assertEquals(0, StringUtils.length(new StringBuffer("")));
assertEquals(0, StringUtils.length(new StringBuffer(StringUtils.EMPTY)));
assertEquals(1, StringUtils.length(new StringBuffer("A")));
assertEquals(1, StringUtils.length(new StringBuffer(" ")));
assertEquals(8, StringUtils.length(new StringBuffer("ABCDEFGH")));
}
@Test
public void testLengthStringBuilder() {
assertEquals(0, StringUtils.length(new StringBuilder("")));
assertEquals(0, StringUtils.length(new StringBuilder(StringUtils.EMPTY)));
assertEquals(1, StringUtils.length(new StringBuilder("A")));
assertEquals(1, StringUtils.length(new StringBuilder(" ")));
assertEquals(8, StringUtils.length(new StringBuilder("ABCDEFGH")));
}
@Test
public void testLength_CharBuffer() {
assertEquals(0, StringUtils.length(CharBuffer.wrap("")));
assertEquals(1, StringUtils.length(CharBuffer.wrap("A")));
assertEquals(1, StringUtils.length(CharBuffer.wrap(" ")));
assertEquals(8, StringUtils.length(CharBuffer.wrap("ABCDEFGH")));
}
//-----------------------------------------------------------------------
@Test
public void testCenter_StringInt() {
assertEquals(null, StringUtils.center(null, -1));
assertEquals(null, StringUtils.center(null, 4));
assertEquals(" ", StringUtils.center("", 4));
assertEquals("ab", StringUtils.center("ab", 0));
assertEquals("ab", StringUtils.center("ab", -1));
assertEquals("ab", StringUtils.center("ab", 1));
assertEquals(" ", StringUtils.center("", 4));
assertEquals(" ab ", StringUtils.center("ab", 4));
assertEquals("abcd", StringUtils.center("abcd", 2));
assertEquals(" a ", StringUtils.center("a", 4));
assertEquals(" a ", StringUtils.center("a", 5));
}
@Test
public void testCenter_StringIntChar() {
assertEquals(null, StringUtils.center(null, -1, ' '));
assertEquals(null, StringUtils.center(null, 4, ' '));
assertEquals(" ", StringUtils.center("", 4, ' '));
assertEquals("ab", StringUtils.center("ab", 0, ' '));
assertEquals("ab", StringUtils.center("ab", -1, ' '));
assertEquals("ab", StringUtils.center("ab", 1, ' '));
assertEquals(" ", StringUtils.center("", 4, ' '));
assertEquals(" ab ", StringUtils.center("ab", 4, ' '));
assertEquals("abcd", StringUtils.center("abcd", 2, ' '));
assertEquals(" a ", StringUtils.center("a", 4, ' '));
assertEquals(" a ", StringUtils.center("a", 5, ' '));
assertEquals("xxaxx", StringUtils.center("a", 5, 'x'));
}
@Test
public void testCenter_StringIntString() {
assertEquals(null, StringUtils.center(null, 4, null));
assertEquals(null, StringUtils.center(null, -1, " "));
assertEquals(null, StringUtils.center(null, 4, " "));
assertEquals(" ", StringUtils.center("", 4, " "));
assertEquals("ab", StringUtils.center("ab", 0, " "));
assertEquals("ab", StringUtils.center("ab", -1, " "));
assertEquals("ab", StringUtils.center("ab", 1, " "));
assertEquals(" ", StringUtils.center("", 4, " "));
assertEquals(" ab ", StringUtils.center("ab", 4, " "));
assertEquals("abcd", StringUtils.center("abcd", 2, " "));
assertEquals(" a ", StringUtils.center("a", 4, " "));
assertEquals("yayz", StringUtils.center("a", 4, "yz"));
assertEquals("yzyayzy", StringUtils.center("a", 7, "yz"));
assertEquals(" abc ", StringUtils.center("abc", 7, null));
assertEquals(" abc ", StringUtils.center("abc", 7, ""));
}
//-----------------------------------------------------------------------
@Test
public void testReverse_String() {
assertEquals(null, StringUtils.reverse(null) );
assertEquals("", StringUtils.reverse("") );
assertEquals("sdrawkcab", StringUtils.reverse("backwards") );
}
@Test
public void testReverseDelimited_StringChar() {
assertEquals(null, StringUtils.reverseDelimited(null, '.') );
assertEquals("", StringUtils.reverseDelimited("", '.') );
assertEquals("c.b.a", StringUtils.reverseDelimited("a.b.c", '.') );
assertEquals("a b c", StringUtils.reverseDelimited("a b c", '.') );
assertEquals("", StringUtils.reverseDelimited("", '.') );
}
//-----------------------------------------------------------------------
@Test
public void testDefault_String() {
assertEquals("", StringUtils.defaultString(null));
assertEquals("", StringUtils.defaultString(""));
assertEquals("abc", StringUtils.defaultString("abc"));
}
@Test
public void testDefault_StringString() {
assertEquals("NULL", StringUtils.defaultString(null, "NULL"));
assertEquals("", StringUtils.defaultString("", "NULL"));
assertEquals("abc", StringUtils.defaultString("abc", "NULL"));
}
@Test
public void testDefaultIfEmpty_StringString() {
assertEquals("NULL", StringUtils.defaultIfEmpty(null, "NULL"));
assertEquals("NULL", StringUtils.defaultIfEmpty("", "NULL"));
assertEquals("abc", StringUtils.defaultIfEmpty("abc", "NULL"));
assertNull(StringUtils.defaultIfEmpty("", null));
// Tests compatibility for the API return type
String s = StringUtils.defaultIfEmpty("abc", "NULL");
assertEquals("abc", s);
}
@Test
public void testDefaultIfBlank_StringString() {
assertEquals("NULL", StringUtils.defaultIfBlank(null, "NULL"));
assertEquals("NULL", StringUtils.defaultIfBlank("", "NULL"));
assertEquals("NULL", StringUtils.defaultIfBlank(" ", "NULL"));
assertEquals("abc", StringUtils.defaultIfBlank("abc", "NULL"));
assertNull(StringUtils.defaultIfBlank("", null));
// Tests compatibility for the API return type
String s = StringUtils.defaultIfBlank("abc", "NULL");
assertEquals("abc", s);
}
@Test
public void testDefaultIfEmpty_StringBuilders() {
assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuilder(""), new StringBuilder("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL")).toString());
assertNull(StringUtils.defaultIfEmpty(new StringBuilder(""), null));
// Tests compatibility for the API return type
StringBuilder s = StringUtils.defaultIfEmpty(new StringBuilder("abc"), new StringBuilder("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfBlank_StringBuilders() {
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuilder(""), new StringBuilder("NULL")).toString());
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuilder(" "), new StringBuilder("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL")).toString());
assertNull(StringUtils.defaultIfBlank(new StringBuilder(""), null));
// Tests compatibility for the API return type
StringBuilder s = StringUtils.defaultIfBlank(new StringBuilder("abc"), new StringBuilder("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfEmpty_StringBuffers() {
assertEquals("NULL", StringUtils.defaultIfEmpty(new StringBuffer(""), new StringBuffer("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL")).toString());
assertNull(StringUtils.defaultIfEmpty(new StringBuffer(""), null));
// Tests compatibility for the API return type
StringBuffer s = StringUtils.defaultIfEmpty(new StringBuffer("abc"), new StringBuffer("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfBlank_StringBuffers() {
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuffer(""), new StringBuffer("NULL")).toString());
assertEquals("NULL", StringUtils.defaultIfBlank(new StringBuffer(" "), new StringBuffer("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL")).toString());
assertNull(StringUtils.defaultIfBlank(new StringBuffer(""), null));
// Tests compatibility for the API return type
StringBuffer s = StringUtils.defaultIfBlank(new StringBuffer("abc"), new StringBuffer("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfEmpty_CharBuffers() {
assertEquals("NULL", StringUtils.defaultIfEmpty(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString());
assertNull(StringUtils.defaultIfEmpty(CharBuffer.wrap(""), null));
// Tests compatibility for the API return type
CharBuffer s = StringUtils.defaultIfEmpty(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
assertEquals("abc", s.toString());
}
@Test
public void testDefaultIfBlank_CharBuffers() {
assertEquals("NULL", StringUtils.defaultIfBlank(CharBuffer.wrap(""), CharBuffer.wrap("NULL")).toString());
assertEquals("NULL", StringUtils.defaultIfBlank(CharBuffer.wrap(" "), CharBuffer.wrap("NULL")).toString());
assertEquals("abc", StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL")).toString());
assertNull(StringUtils.defaultIfBlank(CharBuffer.wrap(""), null));
// Tests compatibility for the API return type
CharBuffer s = StringUtils.defaultIfBlank(CharBuffer.wrap("abc"), CharBuffer.wrap("NULL"));
assertEquals("abc", s.toString());
}
//-----------------------------------------------------------------------
@Test
public void testAbbreviate_StringInt() {
assertEquals(null, StringUtils.abbreviate(null, 10));
assertEquals("", StringUtils.abbreviate("", 10));
assertEquals("short", StringUtils.abbreviate("short", 10));
assertEquals("Now is ...", StringUtils.abbreviate("Now is the time for all good men to come to the aid of their party.", 10));
String raspberry = "raspberry peach";
assertEquals("raspberry p...", StringUtils.abbreviate(raspberry, 14));
assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 15));
assertEquals("raspberry peach", StringUtils.abbreviate("raspberry peach", 16));
assertEquals("abc...", StringUtils.abbreviate("abcdefg", 6));
assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 7));
assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8));
assertEquals("a...", StringUtils.abbreviate("abcdefg", 4));
assertEquals("", StringUtils.abbreviate("", 4));
try {
@SuppressWarnings("unused")
String res = StringUtils.abbreviate("abc", 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
}
@Test
public void testAbbreviate_StringIntInt() {
assertEquals(null, StringUtils.abbreviate(null, 10, 12));
assertEquals("", StringUtils.abbreviate("", 0, 10));
assertEquals("", StringUtils.abbreviate("", 2, 10));
try {
@SuppressWarnings("unused")
String res = StringUtils.abbreviate("abcdefghij", 0, 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
String res = StringUtils.abbreviate("abcdefghij", 5, 6);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
String raspberry = "raspberry peach";
assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15));
assertEquals(null, StringUtils.abbreviate(null, 7, 14));
assertAbbreviateWithOffset("abcdefg...", -1, 10);
assertAbbreviateWithOffset("abcdefg...", 0, 10);
assertAbbreviateWithOffset("abcdefg...", 1, 10);
assertAbbreviateWithOffset("abcdefg...", 2, 10);
assertAbbreviateWithOffset("abcdefg...", 3, 10);
assertAbbreviateWithOffset("abcdefg...", 4, 10);
assertAbbreviateWithOffset("...fghi...", 5, 10);
assertAbbreviateWithOffset("...ghij...", 6, 10);
assertAbbreviateWithOffset("...hijk...", 7, 10);
assertAbbreviateWithOffset("...ijklmno", 8, 10);
assertAbbreviateWithOffset("...ijklmno", 9, 10);
assertAbbreviateWithOffset("...ijklmno", 10, 10);
assertAbbreviateWithOffset("...ijklmno", 10, 10);
assertAbbreviateWithOffset("...ijklmno", 11, 10);
assertAbbreviateWithOffset("...ijklmno", 12, 10);
assertAbbreviateWithOffset("...ijklmno", 13, 10);
assertAbbreviateWithOffset("...ijklmno", 14, 10);
assertAbbreviateWithOffset("...ijklmno", 15, 10);
assertAbbreviateWithOffset("...ijklmno", 16, 10);
assertAbbreviateWithOffset("...ijklmno", Integer.MAX_VALUE, 10);
}
private void assertAbbreviateWithOffset(String expected, int offset, int maxWidth) {
String abcdefghijklmno = "abcdefghijklmno";
String message = "abbreviate(String,int,int) failed";
String actual = StringUtils.abbreviate(abcdefghijklmno, offset, maxWidth);
if (offset >= 0 && offset < abcdefghijklmno.length()) {
assertTrue(message + " -- should contain offset character",
actual.indexOf((char)('a'+offset)) != -1);
}
assertTrue(message + " -- should not be greater than maxWidth",
actual.length() <= maxWidth);
assertEquals(message, expected, actual);
}
@Test
public void testAbbreviateMiddle() {
// javadoc examples
assertNull( StringUtils.abbreviateMiddle(null, null, 0) );
assertEquals( "abc", StringUtils.abbreviateMiddle("abc", null, 0) );
assertEquals( "abc", StringUtils.abbreviateMiddle("abc", ".", 0) );
assertEquals( "abc", StringUtils.abbreviateMiddle("abc", ".", 3) );
assertEquals( "ab.f", StringUtils.abbreviateMiddle("abcdef", ".", 4) );
// JIRA issue (LANG-405) example (slightly different than actual expected result)
assertEquals(
"A very long text with un...f the text is complete.",
StringUtils.abbreviateMiddle(
"A very long text with unimportant stuff in the middle but interesting start and " +
"end to see if the text is complete.", "...", 50) );
// Test a much longer text :)
String longText = "Start text" + StringUtils.repeat("x", 10000) + "Close text";
assertEquals(
"Start text->Close text",
StringUtils.abbreviateMiddle( longText, "->", 22 ) );
// Test negative length
assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", -1));
// Test boundaries
// Fails to change anything as method ensures first and last char are kept
assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 1));
assertEquals("abc", StringUtils.abbreviateMiddle("abc", ".", 2));
// Test length of n=1
assertEquals("a", StringUtils.abbreviateMiddle("a", ".", 1));
// Test smallest length that can lead to success
assertEquals("a.d", StringUtils.abbreviateMiddle("abcd", ".", 3));
// More from LANG-405
assertEquals("a..f", StringUtils.abbreviateMiddle("abcdef", "..", 4));
assertEquals("ab.ef", StringUtils.abbreviateMiddle("abcdef", ".", 5));
}
//-----------------------------------------------------------------------
@Test
public void testDifference_StringString() {
assertEquals(null, StringUtils.difference(null, null));
assertEquals("", StringUtils.difference("", ""));
assertEquals("abc", StringUtils.difference("", "abc"));
assertEquals("", StringUtils.difference("abc", ""));
assertEquals("i am a robot", StringUtils.difference(null, "i am a robot"));
assertEquals("i am a machine", StringUtils.difference("i am a machine", null));
assertEquals("robot", StringUtils.difference("i am a machine", "i am a robot"));
assertEquals("", StringUtils.difference("abc", "abc"));
assertEquals("you are a robot", StringUtils.difference("i am a robot", "you are a robot"));
}
@Test
public void testDifferenceAt_StringString() {
assertEquals(-1, StringUtils.indexOfDifference(null, null));
assertEquals(0, StringUtils.indexOfDifference(null, "i am a robot"));
assertEquals(-1, StringUtils.indexOfDifference("", ""));
assertEquals(0, StringUtils.indexOfDifference("", "abc"));
assertEquals(0, StringUtils.indexOfDifference("abc", ""));
assertEquals(0, StringUtils.indexOfDifference("i am a machine", null));
assertEquals(7, StringUtils.indexOfDifference("i am a machine", "i am a robot"));
assertEquals(-1, StringUtils.indexOfDifference("foo", "foo"));
assertEquals(0, StringUtils.indexOfDifference("i am a robot", "you are a robot"));
//System.out.println("indexOfDiff: " + StringUtils.indexOfDifference("i am a robot", "not machine"));
}
//-----------------------------------------------------------------------
@Test
public void testGetLevenshteinDistance_StringString() {
assertEquals(0, StringUtils.getLevenshteinDistance("", "") );
assertEquals(1, StringUtils.getLevenshteinDistance("", "a") );
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "") );
assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog") );
assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant") );
assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo") );
assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant") );
assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") );
assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo") );
assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo") );
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance("a", null);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance(null, "a");
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
}
@Test
public void testGetLevenshteinDistance_StringStringInt() {
// empty strings
assertEquals(0, StringUtils.getLevenshteinDistance("", "", 0));
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "", 8));
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "", 7));
assertEquals(-1, StringUtils.getLevenshteinDistance("aaapppp", "", 6));
// unequal strings, zero threshold
assertEquals(-1, StringUtils.getLevenshteinDistance("b", "a", 0));
assertEquals(-1, StringUtils.getLevenshteinDistance("a", "b", 0));
// equal strings
assertEquals(0, StringUtils.getLevenshteinDistance("aa", "aa", 0));
assertEquals(0, StringUtils.getLevenshteinDistance("aa", "aa", 2));
// same length
assertEquals(-1, StringUtils.getLevenshteinDistance("aaa", "bbb", 2));
assertEquals(3, StringUtils.getLevenshteinDistance("aaa", "bbb", 3));
// big stripe
assertEquals(6, StringUtils.getLevenshteinDistance("aaaaaa", "b", 10));
// distance less than threshold
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "b", 8));
assertEquals(3, StringUtils.getLevenshteinDistance("a", "bbb", 4));
// distance equal to threshold
assertEquals(7, StringUtils.getLevenshteinDistance("aaapppp", "b", 7));
assertEquals(3, StringUtils.getLevenshteinDistance("a", "bbb", 3));
// distance greater than threshold
assertEquals(-1, StringUtils.getLevenshteinDistance("a", "bbb", 2));
assertEquals(-1, StringUtils.getLevenshteinDistance("bbb", "a", 2));
assertEquals(-1, StringUtils.getLevenshteinDistance("aaapppp", "b", 6));
// stripe runs off array, strings not similar
assertEquals(-1, StringUtils.getLevenshteinDistance("a", "bbb", 1));
assertEquals(-1, StringUtils.getLevenshteinDistance("bbb", "a", 1));
// stripe runs off array, strings are similar
assertEquals(-1, StringUtils.getLevenshteinDistance("12345", "1234567", 1));
assertEquals(-1, StringUtils.getLevenshteinDistance("1234567", "12345", 1));
// old getLevenshteinDistance test cases
assertEquals(1, StringUtils.getLevenshteinDistance("frog", "fog",1) );
assertEquals(3, StringUtils.getLevenshteinDistance("fly", "ant",3) );
assertEquals(7, StringUtils.getLevenshteinDistance("elephant", "hippo",7) );
assertEquals(-1, StringUtils.getLevenshteinDistance("elephant", "hippo",6) );
assertEquals(7, StringUtils.getLevenshteinDistance("hippo", "elephant",7) );
assertEquals(-1, StringUtils.getLevenshteinDistance("hippo", "elephant",6) );
assertEquals(8, StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz",8) );
assertEquals(8, StringUtils.getLevenshteinDistance("zzzzzzzz", "hippo",8) );
assertEquals(1, StringUtils.getLevenshteinDistance("hello", "hallo",1) );
// exceptions
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance("a", null, 0);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance(null, "a", 0);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
try {
@SuppressWarnings("unused")
int d = StringUtils.getLevenshteinDistance("a", "a", -1);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
// empty
}
}
/**
* A sanity check for {@link StringUtils#EMPTY}.
*/
@Test
public void testEMPTY() {
assertNotNull(StringUtils.EMPTY);
assertEquals("", StringUtils.EMPTY);
assertEquals(0, StringUtils.EMPTY.length());
}
/**
* Test for {@link StringUtils#isAllLowerCase(CharSequence)}.
*/
@Test
public void testIsAllLowerCase() {
assertFalse(StringUtils.isAllLowerCase(null));
assertFalse(StringUtils.isAllLowerCase(StringUtils.EMPTY));
assertTrue(StringUtils.isAllLowerCase("abc"));
assertFalse(StringUtils.isAllLowerCase("abc "));
assertFalse(StringUtils.isAllLowerCase("abC"));
}
/**
* Test for {@link StringUtils#isAllUpperCase(CharSequence)}.
*/
@Test
public void testIsAllUpperCase() {
assertFalse(StringUtils.isAllUpperCase(null));
assertFalse(StringUtils.isAllUpperCase(StringUtils.EMPTY));
assertTrue(StringUtils.isAllUpperCase("ABC"));
assertFalse(StringUtils.isAllUpperCase("ABC "));
assertFalse(StringUtils.isAllUpperCase("aBC"));
}
@Test
public void testRemoveStart() {
// StringUtils.removeStart("", *) = ""
assertNull(StringUtils.removeStart(null, null));
assertNull(StringUtils.removeStart(null, ""));
assertNull(StringUtils.removeStart(null, "a"));
// StringUtils.removeStart(*, null) = *
assertEquals(StringUtils.removeStart("", null), "");
assertEquals(StringUtils.removeStart("", ""), "");
assertEquals(StringUtils.removeStart("", "a"), "");
// All others:
assertEquals(StringUtils.removeStart("www.domain.com", "www."), "domain.com");
assertEquals(StringUtils.removeStart("domain.com", "www."), "domain.com");
assertEquals(StringUtils.removeStart("domain.com", ""), "domain.com");
assertEquals(StringUtils.removeStart("domain.com", null), "domain.com");
}
@Test
public void testRemoveStartIgnoreCase() {
// StringUtils.removeStart("", *) = ""
assertNull("removeStartIgnoreCase(null, null)", StringUtils.removeStartIgnoreCase(null, null));
assertNull("removeStartIgnoreCase(null, \"\")", StringUtils.removeStartIgnoreCase(null, ""));
assertNull("removeStartIgnoreCase(null, \"a\")", StringUtils.removeStartIgnoreCase(null, "a"));
// StringUtils.removeStart(*, null) = *
assertEquals("removeStartIgnoreCase(\"\", null)", StringUtils.removeStartIgnoreCase("", null), "");
assertEquals("removeStartIgnoreCase(\"\", \"\")", StringUtils.removeStartIgnoreCase("", ""), "");
assertEquals("removeStartIgnoreCase(\"\", \"a\")", StringUtils.removeStartIgnoreCase("", "a"), "");
// All others:
assertEquals("removeStartIgnoreCase(\"www.domain.com\", \"www.\")", StringUtils.removeStartIgnoreCase("www.domain.com", "www."), "domain.com");
assertEquals("removeStartIgnoreCase(\"domain.com\", \"www.\")", StringUtils.removeStartIgnoreCase("domain.com", "www."), "domain.com");
assertEquals("removeStartIgnoreCase(\"domain.com\", \"\")", StringUtils.removeStartIgnoreCase("domain.com", ""), "domain.com");
assertEquals("removeStartIgnoreCase(\"domain.com\", null)", StringUtils.removeStartIgnoreCase("domain.com", null), "domain.com");
// Case insensitive:
assertEquals("removeStartIgnoreCase(\"www.domain.com\", \"WWW.\")", StringUtils.removeStartIgnoreCase("www.domain.com", "WWW."), "domain.com");
}
@Test
public void testRemoveEnd() {
// StringUtils.removeEnd("", *) = ""
assertNull(StringUtils.removeEnd(null, null));
assertNull(StringUtils.removeEnd(null, ""));
assertNull(StringUtils.removeEnd(null, "a"));
// StringUtils.removeEnd(*, null) = *
assertEquals(StringUtils.removeEnd("", null), "");
assertEquals(StringUtils.removeEnd("", ""), "");
assertEquals(StringUtils.removeEnd("", "a"), "");
// All others:
assertEquals(StringUtils.removeEnd("www.domain.com.", ".com"), "www.domain.com.");
assertEquals(StringUtils.removeEnd("www.domain.com", ".com"), "www.domain");
assertEquals(StringUtils.removeEnd("www.domain", ".com"), "www.domain");
assertEquals(StringUtils.removeEnd("domain.com", ""), "domain.com");
assertEquals(StringUtils.removeEnd("domain.com", null), "domain.com");
}
@Test
public void testRemoveEndIgnoreCase() {
// StringUtils.removeEndIgnoreCase("", *) = ""
assertNull("removeEndIgnoreCase(null, null)", StringUtils.removeEndIgnoreCase(null, null));
assertNull("removeEndIgnoreCase(null, \"\")", StringUtils.removeEndIgnoreCase(null, ""));
assertNull("removeEndIgnoreCase(null, \"a\")", StringUtils.removeEndIgnoreCase(null, "a"));
// StringUtils.removeEnd(*, null) = *
assertEquals("removeEndIgnoreCase(\"\", null)", StringUtils.removeEndIgnoreCase("", null), "");
assertEquals("removeEndIgnoreCase(\"\", \"\")", StringUtils.removeEndIgnoreCase("", ""), "");
assertEquals("removeEndIgnoreCase(\"\", \"a\")", StringUtils.removeEndIgnoreCase("", "a"), "");
// All others:
assertEquals("removeEndIgnoreCase(\"www.domain.com.\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.com.", ".com"), "www.domain.com.");
assertEquals("removeEndIgnoreCase(\"www.domain.com\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.com", ".com"), "www.domain");
assertEquals("removeEndIgnoreCase(\"www.domain\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain", ".com"), "www.domain");
assertEquals("removeEndIgnoreCase(\"domain.com\", \"\")", StringUtils.removeEndIgnoreCase("domain.com", ""), "domain.com");
assertEquals("removeEndIgnoreCase(\"domain.com\", null)", StringUtils.removeEndIgnoreCase("domain.com", null), "domain.com");
// Case insensitive:
assertEquals("removeEndIgnoreCase(\"www.domain.com\", \".COM\")", StringUtils.removeEndIgnoreCase("www.domain.com", ".COM"), "www.domain");
assertEquals("removeEndIgnoreCase(\"www.domain.COM\", \".com\")", StringUtils.removeEndIgnoreCase("www.domain.COM", ".com"), "www.domain");
}
@Test
public void testRemove_String() {
// StringUtils.remove(null, *) = null
assertEquals(null, StringUtils.remove(null, null));
assertEquals(null, StringUtils.remove(null, ""));
assertEquals(null, StringUtils.remove(null, "a"));
// StringUtils.remove("", *) = ""
assertEquals("", StringUtils.remove("", null));
assertEquals("", StringUtils.remove("", ""));
assertEquals("", StringUtils.remove("", "a"));
// StringUtils.remove(*, null) = *
assertEquals(null, StringUtils.remove(null, null));
assertEquals("", StringUtils.remove("", null));
assertEquals("a", StringUtils.remove("a", null));
// StringUtils.remove(*, "") = *
assertEquals(null, StringUtils.remove(null, ""));
assertEquals("", StringUtils.remove("", ""));
assertEquals("a", StringUtils.remove("a", ""));
// StringUtils.remove("queued", "ue") = "qd"
assertEquals("qd", StringUtils.remove("queued", "ue"));
// StringUtils.remove("queued", "zz") = "queued"
assertEquals("queued", StringUtils.remove("queued", "zz"));
}
@Test
public void testRemove_char() {
// StringUtils.remove(null, *) = null
assertEquals(null, StringUtils.remove(null, 'a'));
assertEquals(null, StringUtils.remove(null, 'a'));
assertEquals(null, StringUtils.remove(null, 'a'));
// StringUtils.remove("", *) = ""
assertEquals("", StringUtils.remove("", 'a'));
assertEquals("", StringUtils.remove("", 'a'));
assertEquals("", StringUtils.remove("", 'a'));
// StringUtils.remove("queued", 'u') = "qeed"
assertEquals("qeed", StringUtils.remove("queued", 'u'));
// StringUtils.remove("queued", 'z') = "queued"
assertEquals("queued", StringUtils.remove("queued", 'z'));
}
@Test
public void testDifferenceAt_StringArray() {
assertEquals(-1, StringUtils.indexOfDifference((String[])null));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {"abc"}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {null, null}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {"", ""}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"", null}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"abc", null, null}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {null, null, "abc"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"", "abc"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"abc", ""}));
assertEquals(-1, StringUtils.indexOfDifference(new String[] {"abc", "abc"}));
assertEquals(1, StringUtils.indexOfDifference(new String[] {"abc", "a"}));
assertEquals(2, StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}));
assertEquals(2, StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}));
assertEquals(0, StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}));
assertEquals(7, StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}));
}
@Test
public void testGetCommonPrefix_StringArray() {
assertEquals("", StringUtils.getCommonPrefix((String[])null));
assertEquals("", StringUtils.getCommonPrefix());
assertEquals("abc", StringUtils.getCommonPrefix("abc"));
assertEquals("", StringUtils.getCommonPrefix(null, null));
assertEquals("", StringUtils.getCommonPrefix("", ""));
assertEquals("", StringUtils.getCommonPrefix("", null));
assertEquals("", StringUtils.getCommonPrefix("abc", null, null));
assertEquals("", StringUtils.getCommonPrefix(null, null, "abc"));
assertEquals("", StringUtils.getCommonPrefix("", "abc"));
assertEquals("", StringUtils.getCommonPrefix("abc", ""));
assertEquals("abc", StringUtils.getCommonPrefix("abc", "abc"));
assertEquals("a", StringUtils.getCommonPrefix("abc", "a"));
assertEquals("ab", StringUtils.getCommonPrefix("ab", "abxyz"));
assertEquals("ab", StringUtils.getCommonPrefix("abcde", "abxyz"));
assertEquals("", StringUtils.getCommonPrefix("abcde", "xyz"));
assertEquals("", StringUtils.getCommonPrefix("xyz", "abcde"));
assertEquals("i am a ", StringUtils.getCommonPrefix("i am a machine", "i am a robot"));
}
@Test
public void testNormalizeSpace() {
assertEquals(null, StringUtils.normalizeSpace(null));
assertEquals("", StringUtils.normalizeSpace(""));
assertEquals("", StringUtils.normalizeSpace(" "));
assertEquals("", StringUtils.normalizeSpace("\t"));
assertEquals("", StringUtils.normalizeSpace("\n"));
assertEquals("", StringUtils.normalizeSpace("\u0009"));
assertEquals("", StringUtils.normalizeSpace("\u000B"));
assertEquals("", StringUtils.normalizeSpace("\u000C"));
assertEquals("", StringUtils.normalizeSpace("\u001C"));
assertEquals("", StringUtils.normalizeSpace("\u001D"));
assertEquals("", StringUtils.normalizeSpace("\u001E"));
assertEquals("", StringUtils.normalizeSpace("\u001F"));
assertEquals("", StringUtils.normalizeSpace("\f"));
assertEquals("", StringUtils.normalizeSpace("\r"));
assertEquals("a", StringUtils.normalizeSpace(" a "));
assertEquals("a b c", StringUtils.normalizeSpace(" a b c "));
assertEquals("a b c", StringUtils.normalizeSpace("a\t\f\r b\u000B c\n"));
}
@Test
public void testLANG666() {
assertEquals("12",StringUtils.stripEnd("120.00", ".0"));
assertEquals("121",StringUtils.stripEnd("121.00", ".0"));
}
// Methods on StringUtils that are immutable in spirit (i.e. calculate the length)
// should take a CharSequence parameter. Methods that are mutable in spirit (i.e. capitalize)
// should take a String or String[] parameter and return String or String[].
// This test enforces that this is done.
@Test
public void testStringUtilsCharSequenceContract() {
Class<StringUtils> c = StringUtils.class;
Method[] methods = c.getMethods();
for (Method m : methods) {
if (m.getReturnType() == String.class || m.getReturnType() == String[].class) {
// Assume this is mutable and ensure the first parameter is not CharSequence.
// It may be String or it may be something else (String[], Object, Object[]) so
// don't actively test for that.
Class<?>[] params = m.getParameterTypes();
if ( params.length > 0 && (params[0] == CharSequence.class || params[0] == CharSequence[].class)) {
fail("The method " + m + " appears to be mutable in spirit and therefore must not accept a CharSequence");
}
} else {
// Assume this is immutable in spirit and ensure the first parameter is not String.
// As above, it may be something other than CharSequence.
Class<?>[] params = m.getParameterTypes();
if ( params.length > 0 && (params[0] == String.class || params[0] == String[].class)) {
fail("The method " + m + " appears to be immutable in spirit and therefore must not accept a String");
}
}
}
}
/**
* Tests {@link StringUtils#toString(byte[], String)}
*
* @throws UnsupportedEncodingException
* @see StringUtils#toString(byte[], String)
*/
@Test
public void testToString() throws UnsupportedEncodingException {
final String expectedString = "The quick brown fox jumped over the lazy dog.";
String encoding = SystemUtils.FILE_ENCODING;
byte[] expectedBytes = expectedString.getBytes(encoding);
// sanity check start
assertArrayEquals(expectedBytes, expectedString.getBytes());
// sanity check end
assertEquals(expectedString, StringUtils.toString(expectedBytes, null));
assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding));
encoding = "UTF-16";
expectedBytes = expectedString.getBytes(encoding);
assertEquals(expectedString, StringUtils.toString(expectedBytes, encoding));
}
@Test
public void testEscapeSurrogatePairs() throws Exception {
assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
// Examples from https://en.wikipedia.org/wiki/UTF-16
assertEquals("\uD800\uDC00", StringEscapeUtils.escapeCsv("\uD800\uDC00"));
assertEquals("\uD834\uDD1E", StringEscapeUtils.escapeCsv("\uD834\uDD1E"));
assertEquals("\uDBFF\uDFFD", StringEscapeUtils.escapeCsv("\uDBFF\uDFFD"));
}
} |
||
@Test
public void testAtan2SpecialCases() {
DerivativeStructure pp =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, +0.0),
new DerivativeStructure(2, 2, 1, +0.0));
Assert.assertEquals(0, pp.getValue(), 1.0e-15);
Assert.assertEquals(+1, FastMath.copySign(1, pp.getValue()), 1.0e-15);
DerivativeStructure pn =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, +0.0),
new DerivativeStructure(2, 2, 1, -0.0));
Assert.assertEquals(FastMath.PI, pn.getValue(), 1.0e-15);
DerivativeStructure np =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, -0.0),
new DerivativeStructure(2, 2, 1, +0.0));
Assert.assertEquals(0, np.getValue(), 1.0e-15);
Assert.assertEquals(-1, FastMath.copySign(1, np.getValue()), 1.0e-15);
DerivativeStructure nn =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, -0.0),
new DerivativeStructure(2, 2, 1, -0.0));
Assert.assertEquals(-FastMath.PI, nn.getValue(), 1.0e-15);
} | org.apache.commons.math3.analysis.differentiation.DerivativeStructureTest::testAtan2SpecialCases | src/test/java/org/apache/commons/math3/analysis/differentiation/DerivativeStructureTest.java | 834 | src/test/java/org/apache/commons/math3/analysis/differentiation/DerivativeStructureTest.java | testAtan2SpecialCases | /*
* 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.analysis.differentiation;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.math3.TestUtils;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.util.ArithmeticUtils;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
/**
* Test for class {@link DerivativeStructure}.
*/
public class DerivativeStructureTest {
@Test(expected=NumberIsTooLargeException.class)
public void testWrongVariableIndex() {
new DerivativeStructure(3, 1, 3, 1.0);
}
@Test(expected=DimensionMismatchException.class)
public void testMissingOrders() {
new DerivativeStructure(3, 1, 0, 1.0).getPartialDerivative(0, 1);
}
@Test(expected=NumberIsTooLargeException.class)
public void testTooLargeOrder() {
new DerivativeStructure(3, 1, 0, 1.0).getPartialDerivative(1, 1, 2);
}
@Test
public void testVariableWithoutDerivative0() {
DerivativeStructure v = new DerivativeStructure(1, 0, 0, 1.0);
Assert.assertEquals(1.0, v.getValue(), 1.0e-15);
}
@Test(expected=NumberIsTooLargeException.class)
public void testVariableWithoutDerivative1() {
DerivativeStructure v = new DerivativeStructure(1, 0, 0, 1.0);
Assert.assertEquals(1.0, v.getPartialDerivative(1), 1.0e-15);
}
@Test
public void testVariable() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0),
1.0, 1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0),
2.0, 0.0, 1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0),
3.0, 0.0, 0.0, 1.0);
}
}
@Test
public void testConstant() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, FastMath.PI),
FastMath.PI, 0.0, 0.0, 0.0);
}
}
@Test
public void testPrimitiveAdd() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).add(5), 6.0, 1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).add(5), 7.0, 0.0, 1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).add(5), 8.0, 0.0, 0.0, 1.0);
}
}
@Test
public void testAdd() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
DerivativeStructure xyz = x.add(y.add(z));
checkF0F1(xyz, x.getValue() + y.getValue() + z.getValue(), 1.0, 1.0, 1.0);
}
}
@Test
public void testPrimitiveSubtract() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).subtract(5), -4.0, 1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).subtract(5), -3.0, 0.0, 1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).subtract(5), -2.0, 0.0, 0.0, 1.0);
}
}
@Test
public void testSubtract() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
DerivativeStructure xyz = x.subtract(y.subtract(z));
checkF0F1(xyz, x.getValue() - (y.getValue() - z.getValue()), 1.0, -1.0, 1.0);
}
}
@Test
public void testPrimitiveMultiply() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).multiply(5), 5.0, 5.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).multiply(5), 10.0, 0.0, 5.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).multiply(5), 15.0, 0.0, 0.0, 5.0);
}
}
@Test
public void testMultiply() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
DerivativeStructure xyz = x.multiply(y.multiply(z));
for (int i = 0; i <= maxOrder; ++i) {
for (int j = 0; j <= maxOrder; ++j) {
for (int k = 0; k <= maxOrder; ++k) {
if (i + j + k <= maxOrder) {
Assert.assertEquals((i == 0 ? x.getValue() : (i == 1 ? 1.0 : 0.0)) *
(j == 0 ? y.getValue() : (j == 1 ? 1.0 : 0.0)) *
(k == 0 ? z.getValue() : (k == 1 ? 1.0 : 0.0)),
xyz.getPartialDerivative(i, j, k),
1.0e-15);
}
}
}
}
}
}
@Test
public void testNegate() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).negate(), -1.0, -1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).negate(), -2.0, 0.0, -1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).negate(), -3.0, 0.0, 0.0, -1.0);
}
}
@Test
public void testReciprocal() {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure r = new DerivativeStructure(1, 6, 0, x).reciprocal();
Assert.assertEquals(1 / x, r.getValue(), 1.0e-15);
for (int i = 1; i < r.getOrder(); ++i) {
double expected = ArithmeticUtils.pow(-1, i) * ArithmeticUtils.factorial(i) /
FastMath.pow(x, i + 1);
Assert.assertEquals(expected, r.getPartialDerivative(i), 1.0e-15 * FastMath.abs(expected));
}
}
}
@Test
public void testPow() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
for (int n = 0; n < 10; ++n) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
List<DerivativeStructure> list = Arrays.asList(x, y, z,
x.add(y).add(z),
x.multiply(y).multiply(z));
if (n == 0) {
for (DerivativeStructure ds : list) {
checkEquals(ds.getField().getOne(), ds.pow(n), 1.0e-15);
}
} else if (n == 1) {
for (DerivativeStructure ds : list) {
checkEquals(ds, ds.pow(n), 1.0e-15);
}
} else {
for (DerivativeStructure ds : list) {
DerivativeStructure p = ds.getField().getOne();
for (int i = 0; i < n; ++i) {
p = p.multiply(ds);
}
checkEquals(p, ds.pow(n), 1.0e-15);
}
}
}
}
}
@Test
public void testExpression() {
double epsilon = 2.5e-13;
for (double x = 0; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(3, 5, 0, x);
for (double y = 0; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(3, 5, 1, y);
for (double z = 0; z >- 2; z -= 0.2) {
DerivativeStructure dsZ = new DerivativeStructure(3, 5, 2, z);
// f(x, y, z) = x + 5 x y - 2 z + (8 z x - y)^3
DerivativeStructure ds =
new DerivativeStructure(1, dsX,
5, dsX.multiply(dsY),
-2, dsZ,
1, new DerivativeStructure(8, dsZ.multiply(dsX),
-1, dsY).pow(3));
DerivativeStructure dsOther =
new DerivativeStructure(1, dsX,
5, dsX.multiply(dsY),
-2, dsZ).add(new DerivativeStructure(8, dsZ.multiply(dsX),
-1, dsY).pow(3));
double f = x + 5 * x * y - 2 * z + FastMath.pow(8 * z * x - y, 3);
Assert.assertEquals(f, ds.getValue(),
FastMath.abs(epsilon * f));
Assert.assertEquals(f, dsOther.getValue(),
FastMath.abs(epsilon * f));
// df/dx = 1 + 5 y + 24 (8 z x - y)^2 z
double dfdx = 1 + 5 * y + 24 * z * FastMath.pow(8 * z * x - y, 2);
Assert.assertEquals(dfdx, ds.getPartialDerivative(1, 0, 0),
FastMath.abs(epsilon * dfdx));
Assert.assertEquals(dfdx, dsOther.getPartialDerivative(1, 0, 0),
FastMath.abs(epsilon * dfdx));
// df/dxdy = 5 + 48 z*(y - 8 z x)
double dfdxdy = 5 + 48 * z * (y - 8 * z * x);
Assert.assertEquals(dfdxdy, ds.getPartialDerivative(1, 1, 0),
FastMath.abs(epsilon * dfdxdy));
Assert.assertEquals(dfdxdy, dsOther.getPartialDerivative(1, 1, 0),
FastMath.abs(epsilon * dfdxdy));
// df/dxdydz = 48 (y - 16 z x)
double dfdxdydz = 48 * (y - 16 * z * x);
Assert.assertEquals(dfdxdydz, ds.getPartialDerivative(1, 1, 1),
FastMath.abs(epsilon * dfdxdydz));
Assert.assertEquals(dfdxdydz, dsOther.getPartialDerivative(1, 1, 1),
FastMath.abs(epsilon * dfdxdydz));
}
}
}
}
@Test
public void testCompositionOneVariableX() {
double epsilon = 1.0e-13;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
for (double y = 0.1; y < 1.2; y += 0.1) {
DerivativeStructure dsY = new DerivativeStructure(1, maxOrder, y);
DerivativeStructure f = dsX.divide(dsY).sqrt();
double f0 = FastMath.sqrt(x / y);
Assert.assertEquals(f0, f.getValue(), FastMath.abs(epsilon * f0));
if (f.getOrder() > 0) {
double f1 = 1 / (2 * FastMath.sqrt(x * y));
Assert.assertEquals(f1, f.getPartialDerivative(1), FastMath.abs(epsilon * f1));
if (f.getOrder() > 1) {
double f2 = -f1 / (2 * x);
Assert.assertEquals(f2, f.getPartialDerivative(2), FastMath.abs(epsilon * f2));
if (f.getOrder() > 2) {
double f3 = (f0 + x / (2 * y * f0)) / (4 * x * x * x);
Assert.assertEquals(f3, f.getPartialDerivative(3), FastMath.abs(epsilon * f3));
}
}
}
}
}
}
}
@Test
public void testTrigo() {
double epsilon = 2.0e-12;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(3, maxOrder, 0, x);
for (double y = 0.1; y < 1.2; y += 0.1) {
DerivativeStructure dsY = new DerivativeStructure(3, maxOrder, 1, y);
for (double z = 0.1; z < 1.2; z += 0.1) {
DerivativeStructure dsZ = new DerivativeStructure(3, maxOrder, 2, z);
DerivativeStructure f = dsX.divide(dsY.cos().add(dsZ.tan())).sin();
double a = FastMath.cos(y) + FastMath.tan(z);
double f0 = FastMath.sin(x / a);
Assert.assertEquals(f0, f.getValue(), FastMath.abs(epsilon * f0));
if (f.getOrder() > 0) {
double dfdx = FastMath.cos(x / a) / a;
Assert.assertEquals(dfdx, f.getPartialDerivative(1, 0, 0), FastMath.abs(epsilon * dfdx));
double dfdy = x * FastMath.sin(y) * dfdx / a;
Assert.assertEquals(dfdy, f.getPartialDerivative(0, 1, 0), FastMath.abs(epsilon * dfdy));
double cz = FastMath.cos(z);
double cz2 = cz * cz;
double dfdz = -x * dfdx / (a * cz2);
Assert.assertEquals(dfdz, f.getPartialDerivative(0, 0, 1), FastMath.abs(epsilon * dfdz));
if (f.getOrder() > 1) {
double df2dx2 = -(f0 / (a * a));
Assert.assertEquals(df2dx2, f.getPartialDerivative(2, 0, 0), FastMath.abs(epsilon * df2dx2));
double df2dy2 = x * FastMath.cos(y) * dfdx / a -
x * x * FastMath.sin(y) * FastMath.sin(y) * f0 / (a * a * a * a) +
2 * FastMath.sin(y) * dfdy / a;
Assert.assertEquals(df2dy2, f.getPartialDerivative(0, 2, 0), FastMath.abs(epsilon * df2dy2));
double c4 = cz2 * cz2;
double df2dz2 = x * (2 * a * (1 - a * cz * FastMath.sin(z)) * dfdx - x * f0 / a ) / (a * a * a * c4);
Assert.assertEquals(df2dz2, f.getPartialDerivative(0, 0, 2), FastMath.abs(epsilon * df2dz2));
double df2dxdy = dfdy / x - x * FastMath.sin(y) * f0 / (a * a * a);
Assert.assertEquals(df2dxdy, f.getPartialDerivative(1, 1, 0), FastMath.abs(epsilon * df2dxdy));
}
}
}
}
}
}
}
@Test
public void testSqrtDefinition() {
double[] epsilon = new double[] { 5.0e-16, 5.0e-16, 2.0e-15, 5.0e-14, 2.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure sqrt1 = dsX.pow(0.5);
DerivativeStructure sqrt2 = dsX.sqrt();
DerivativeStructure zero = sqrt1.subtract(sqrt2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testRootNSingularity() {
for (int n = 2; n < 10; ++n) {
for (int maxOrder = 0; maxOrder < 12; ++maxOrder) {
DerivativeStructure dsZero = new DerivativeStructure(1, maxOrder, 0, 0.0);
DerivativeStructure rootN = dsZero.rootN(n);
Assert.assertEquals(0.0, rootN.getValue(), 1.0e-20);
if (maxOrder > 0) {
Assert.assertTrue(Double.isInfinite(rootN.getPartialDerivative(1)));
Assert.assertTrue(rootN.getPartialDerivative(1) > 0);
for (int order = 2; order <= maxOrder; ++order) {
// the following checks shows a LIMITATION of the current implementation
// we have no way to tell dsZero is a pure linear variable x = 0
// we only say: "dsZero is a structure with value = 0.0,
// first derivative = 1.0, second and higher derivatives = 0.0".
// Function composition rule for second derivatives is:
// d2[f(g(x))]/dx2 = f''(g(x)) * [g'(x)]^2 + f'(g(x)) * g''(x)
// when function f is the nth root and x = 0 we have:
// f(0) = 0, f'(0) = +infinity, f''(0) = -infinity (and higher
// derivatives keep switching between +infinity and -infinity)
// so given that in our case dsZero represents g, we have g(x) = 0,
// g'(x) = 1 and g''(x) = 0
// applying the composition rules gives:
// d2[f(g(x))]/dx2 = f''(g(x)) * [g'(x)]^2 + f'(g(x)) * g''(x)
// = -infinity * 1^2 + +infinity * 0
// = -infinity + NaN
// = NaN
// if we knew dsZero is really the x variable and not the identity
// function applied to x, we would not have computed f'(g(x)) * g''(x)
// and we would have found that the result was -infinity and not NaN
Assert.assertTrue(Double.isNaN(rootN.getPartialDerivative(order)));
}
}
// the following shows that the limitation explained above is NOT a bug...
// if we set up the higher order derivatives for g appropriately, we do
// compute the higher order derivatives of the composition correctly
double[] gDerivatives = new double[ 1 + maxOrder];
gDerivatives[0] = 0.0;
for (int k = 1; k <= maxOrder; ++k) {
gDerivatives[k] = FastMath.pow(-1.0, k + 1);
}
DerivativeStructure correctRoot = new DerivativeStructure(1, maxOrder, gDerivatives).rootN(n);
Assert.assertEquals(0.0, correctRoot.getValue(), 1.0e-20);
if (maxOrder > 0) {
Assert.assertTrue(Double.isInfinite(correctRoot.getPartialDerivative(1)));
Assert.assertTrue(correctRoot.getPartialDerivative(1) > 0);
for (int order = 2; order <= maxOrder; ++order) {
Assert.assertTrue(Double.isInfinite(correctRoot.getPartialDerivative(order)));
if ((order % 2) == 0) {
Assert.assertTrue(correctRoot.getPartialDerivative(order) < 0);
} else {
Assert.assertTrue(correctRoot.getPartialDerivative(order) > 0);
}
}
}
}
}
}
@Test
public void testSqrtPow2() {
double[] epsilon = new double[] { 1.0e-16, 3.0e-16, 2.0e-15, 6.0e-14, 6.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.multiply(dsX).sqrt();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCbrtDefinition() {
double[] epsilon = new double[] { 4.0e-16, 9.0e-16, 6.0e-15, 2.0e-13, 4.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure cbrt1 = dsX.pow(1.0 / 3.0);
DerivativeStructure cbrt2 = dsX.cbrt();
DerivativeStructure zero = cbrt1.subtract(cbrt2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCbrtPow3() {
double[] epsilon = new double[] { 1.0e-16, 5.0e-16, 8.0e-15, 3.0e-13, 4.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.multiply(dsX.multiply(dsX)).cbrt();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testPowReciprocalPow() {
double[] epsilon = new double[] { 2.0e-15, 2.0e-14, 3.0e-13, 8.0e-12, 3.0e-10 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.01) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = 0.1; y < 1.2; y += 0.01) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure rebuiltX = dsX.pow(dsY).pow(dsY.reciprocal());
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n, m), epsilon[n + m]);
}
}
}
}
}
}
}
@Test
public void testHypotDefinition() {
double epsilon = 1.0e-20;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure hypot = DerivativeStructure.hypot(dsY, dsX);
DerivativeStructure ref = dsX.multiply(dsX).add(dsY.multiply(dsY)).sqrt();
DerivativeStructure zero = hypot.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon);
}
}
}
}
}
}
}
@Test
public void testHypotNoOverflow() {
DerivativeStructure dsX = new DerivativeStructure(2, 5, 0, +3.0e250);
DerivativeStructure dsY = new DerivativeStructure(2, 5, 1, -4.0e250);
DerivativeStructure hypot = DerivativeStructure.hypot(dsX, dsY);
Assert.assertEquals(5.0e250, hypot.getValue(), 1.0e235);
Assert.assertEquals(dsX.getValue() / hypot.getValue(), hypot.getPartialDerivative(1, 0), 1.0e-10);
Assert.assertEquals(dsY.getValue() / hypot.getValue(), hypot.getPartialDerivative(0, 1), 1.0e-10);
DerivativeStructure sqrt = dsX.multiply(dsX).add(dsY.multiply(dsY)).sqrt();
Assert.assertTrue(Double.isInfinite(sqrt.getValue()));
}
@Test
public void testPrimitiveRemainder() {
double epsilon = 1.0e-15;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure remainder = dsX.remainder(y);
DerivativeStructure ref = dsX.subtract(x - (x % y));
DerivativeStructure zero = remainder.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon);
}
}
}
}
}
}
}
@Test
public void testRemainder() {
double epsilon = 1.0e-15;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure remainder = dsX.remainder(dsY);
DerivativeStructure ref = dsX.subtract(dsY.multiply((x - (x % y)) / y));
DerivativeStructure zero = remainder.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon);
}
}
}
}
}
}
}
@Test
public void testExp() {
double[] epsilon = new double[] { 1.0e-16, 1.0e-16, 1.0e-16, 1.0e-16, 1.0e-16 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
double refExp = FastMath.exp(x);
DerivativeStructure exp = new DerivativeStructure(1, maxOrder, 0, x).exp();
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(refExp, exp.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testExpm1Definition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure expm11 = dsX.expm1();
DerivativeStructure expm12 = dsX.exp().subtract(dsX.getField().getOne());
DerivativeStructure zero = expm11.subtract(expm12);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon);
}
}
}
}
@Test
public void testLog() {
double[] epsilon = new double[] { 1.0e-16, 1.0e-16, 3.0e-14, 7.0e-13, 3.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure log = new DerivativeStructure(1, maxOrder, 0, x).log();
Assert.assertEquals(FastMath.log(x), log.getValue(), epsilon[0]);
for (int n = 1; n <= maxOrder; ++n) {
double refDer = -ArithmeticUtils.factorial(n - 1) / FastMath.pow(-x, n);
Assert.assertEquals(refDer, log.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLog1pDefinition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure log1p1 = dsX.log1p();
DerivativeStructure log1p2 = dsX.add(dsX.getField().getOne()).log();
DerivativeStructure zero = log1p1.subtract(log1p2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon);
}
}
}
}
@Test
public void testLog10Definition() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 8.0e-15, 3.0e-13, 8.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure log101 = dsX.log10();
DerivativeStructure log102 = dsX.log().divide(FastMath.log(10.0));
DerivativeStructure zero = log101.subtract(log102);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLogExp() {
double[] epsilon = new double[] { 2.0e-16, 2.0e-16, 3.0e-16, 2.0e-15, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.exp().log();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLog1pExpm1() {
double[] epsilon = new double[] { 6.0e-17, 3.0e-16, 5.0e-16, 9.0e-16, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.expm1().log1p();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLog10Power() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 9.0e-16, 6.0e-15, 6.0e-14 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = new DerivativeStructure(1, maxOrder, 10.0).pow(dsX).log10();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testSinCos() {
double epsilon = 5.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure sin = dsX.sin();
DerivativeStructure cos = dsX.cos();
double s = FastMath.sin(x);
double c = FastMath.cos(x);
for (int n = 0; n <= maxOrder; ++n) {
switch (n % 4) {
case 0 :
Assert.assertEquals( s, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals( c, cos.getPartialDerivative(n), epsilon);
break;
case 1 :
Assert.assertEquals( c, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals(-s, cos.getPartialDerivative(n), epsilon);
break;
case 2 :
Assert.assertEquals(-s, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals(-c, cos.getPartialDerivative(n), epsilon);
break;
default :
Assert.assertEquals(-c, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals( s, cos.getPartialDerivative(n), epsilon);
break;
}
}
}
}
}
@Test
public void testSinAsin() {
double[] epsilon = new double[] { 3.0e-16, 5.0e-16, 3.0e-15, 2.0e-14, 4.0e-13 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.sin().asin();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCosAcos() {
double[] epsilon = new double[] { 6.0e-16, 6.0e-15, 2.0e-13, 4.0e-12, 2.0e-10 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.cos().acos();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTanAtan() {
double[] epsilon = new double[] { 6.0e-17, 2.0e-16, 2.0e-15, 4.0e-14, 2.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.tan().atan();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTangentDefinition() {
double[] epsilon = new double[] { 5.0e-16, 2.0e-15, 3.0e-14, 5.0e-13, 2.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure tan1 = dsX.sin().divide(dsX.cos());
DerivativeStructure tan2 = dsX.tan();
DerivativeStructure zero = tan1.subtract(tan2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testAtan2() {
double[] epsilon = new double[] { 5.0e-16, 3.0e-15, 2.2e-14, 1.0e-12, 8.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure atan2 = DerivativeStructure.atan2(dsY, dsX);
DerivativeStructure ref = dsY.divide(dsX).atan();
if (x < 0) {
ref = (y < 0) ? ref.subtract(FastMath.PI) : ref.add(FastMath.PI);
}
DerivativeStructure zero = atan2.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon[n + m]);
}
}
}
}
}
}
}
@Test
public void testAtan2SpecialCases() {
DerivativeStructure pp =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, +0.0),
new DerivativeStructure(2, 2, 1, +0.0));
Assert.assertEquals(0, pp.getValue(), 1.0e-15);
Assert.assertEquals(+1, FastMath.copySign(1, pp.getValue()), 1.0e-15);
DerivativeStructure pn =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, +0.0),
new DerivativeStructure(2, 2, 1, -0.0));
Assert.assertEquals(FastMath.PI, pn.getValue(), 1.0e-15);
DerivativeStructure np =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, -0.0),
new DerivativeStructure(2, 2, 1, +0.0));
Assert.assertEquals(0, np.getValue(), 1.0e-15);
Assert.assertEquals(-1, FastMath.copySign(1, np.getValue()), 1.0e-15);
DerivativeStructure nn =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, -0.0),
new DerivativeStructure(2, 2, 1, -0.0));
Assert.assertEquals(-FastMath.PI, nn.getValue(), 1.0e-15);
}
@Test
public void testSinhDefinition() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 5.0e-16, 2.0e-15, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure sinh1 = dsX.exp().subtract(dsX.exp().reciprocal()).multiply(0.5);
DerivativeStructure sinh2 = dsX.sinh();
DerivativeStructure zero = sinh1.subtract(sinh2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCoshDefinition() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 5.0e-16, 2.0e-15, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure cosh1 = dsX.exp().add(dsX.exp().reciprocal()).multiply(0.5);
DerivativeStructure cosh2 = dsX.cosh();
DerivativeStructure zero = cosh1.subtract(cosh2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTanhDefinition() {
double[] epsilon = new double[] { 3.0e-16, 5.0e-16, 7.0e-16, 3.0e-15, 2.0e-14 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure tanh1 = dsX.exp().subtract(dsX.exp().reciprocal()).divide(dsX.exp().add(dsX.exp().reciprocal()));
DerivativeStructure tanh2 = dsX.tanh();
DerivativeStructure zero = tanh1.subtract(tanh2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testSinhAsinh() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 4.0e-16, 7.0e-16, 3.0e-15, 8.0e-15 };
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.sinh().asinh();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCoshAcosh() {
double[] epsilon = new double[] { 2.0e-15, 1.0e-14, 2.0e-13, 6.0e-12, 3.0e-10, 2.0e-8 };
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.cosh().acosh();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTanhAtanh() {
double[] epsilon = new double[] { 3.0e-16, 2.0e-16, 7.0e-16, 4.0e-15, 3.0e-14, 4.0e-13 };
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.tanh().atanh();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCompositionOneVariableY() {
double epsilon = 1.0e-13;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, x);
for (double y = 0.1; y < 1.2; y += 0.1) {
DerivativeStructure dsY = new DerivativeStructure(1, maxOrder, 0, y);
DerivativeStructure f = dsX.divide(dsY).sqrt();
double f0 = FastMath.sqrt(x / y);
Assert.assertEquals(f0, f.getValue(), FastMath.abs(epsilon * f0));
if (f.getOrder() > 0) {
double f1 = -x / (2 * y * y * f0);
Assert.assertEquals(f1, f.getPartialDerivative(1), FastMath.abs(epsilon * f1));
if (f.getOrder() > 1) {
double f2 = (f0 - x / (4 * y * f0)) / (y * y);
Assert.assertEquals(f2, f.getPartialDerivative(2), FastMath.abs(epsilon * f2));
if (f.getOrder() > 2) {
double f3 = (x / (8 * y * f0) - 2 * f0) / (y * y * y);
Assert.assertEquals(f3, f.getPartialDerivative(3), FastMath.abs(epsilon * f3));
}
}
}
}
}
}
}
@Test
public void testTaylorPolynomial() {
for (double x = 0; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(3, 4, 0, x);
for (double y = 0; y < 1.2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(3, 4, 1, y);
for (double z = 0; z < 1.2; z += 0.2) {
DerivativeStructure dsZ = new DerivativeStructure(3, 4, 2, z);
DerivativeStructure f = dsX.multiply(dsY).add(dsZ).multiply(dsX).multiply(dsY);
for (double dx = -0.2; dx < 0.2; dx += 0.2) {
for (double dy = -0.2; dy < 0.2; dy += 0.1) {
for (double dz = -0.2; dz < 0.2; dz += 0.1) {
double ref = (x + dx) * (y + dy) * ((x + dx) * (y + dy) + (z + dz));
Assert.assertEquals(ref, f.taylor(dx, dy, dz), 2.0e-15);
}
}
}
}
}
}
}
@Test
public void testTaylorAtan2() {
double[] expected = new double[] { 0.214, 0.0241, 0.00422, 6.48e-4, 8.04e-5 };
double x0 = 0.1;
double y0 = -0.3;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x0);
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y0);
DerivativeStructure atan2 = DerivativeStructure.atan2(dsY, dsX);
double maxError = 0;
for (double dx = -0.05; dx < 0.05; dx += 0.001) {
for (double dy = -0.05; dy < 0.05; dy += 0.001) {
double ref = FastMath.atan2(y0 + dy, x0 + dx);
maxError = FastMath.max(maxError, FastMath.abs(ref - atan2.taylor(dx, dy)));
}
}
Assert.assertEquals(0.0, expected[maxOrder] - maxError, 0.01 * expected[maxOrder]);
}
}
@Test
public void testAbs() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(+1.0, minusOne.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusOne = new DerivativeStructure(1, 1, 0, +1.0);
Assert.assertEquals(+1.0, plusOne.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, plusOne.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure minusZero = new DerivativeStructure(1, 1, 0, -0.0);
Assert.assertEquals(+0.0, minusZero.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusZero.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusZero = new DerivativeStructure(1, 1, 0, +0.0);
Assert.assertEquals(+0.0, plusZero.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, plusZero.abs().getPartialDerivative(1), 1.0e-15);
}
@Test
public void testSignum() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(-1.0, minusOne.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals( 0.0, minusOne.signum().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusOne = new DerivativeStructure(1, 1, 0, +1.0);
Assert.assertEquals(+1.0, plusOne.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals( 0.0, plusOne.signum().getPartialDerivative(1), 1.0e-15);
DerivativeStructure minusZero = new DerivativeStructure(1, 1, 0, -0.0);
Assert.assertEquals(-0.0, minusZero.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertTrue(Double.doubleToLongBits(minusZero.signum().getValue()) < 0);
Assert.assertEquals( 0.0, minusZero.signum().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusZero = new DerivativeStructure(1, 1, 0, +0.0);
Assert.assertEquals(+0.0, plusZero.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertTrue(Double.doubleToLongBits(plusZero.signum().getValue()) == 0);
Assert.assertEquals( 0.0, plusZero.signum().getPartialDerivative(1), 1.0e-15);
}
@Test
public void testCeilFloorRintLong() {
DerivativeStructure x = new DerivativeStructure(1, 1, 0, -1.5);
Assert.assertEquals(-1.5, x.getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, x.getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, x.ceil().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+0.0, x.ceil().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-2.0, x.floor().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+0.0, x.floor().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-2.0, x.rint().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+0.0, x.rint().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-2.0, x.subtract(x.getField().getOne()).rint().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1l, x.round());
}
@Test
public void testCopySign() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(+1.0, minusOne.copySign(+1.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(+1.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(-1.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(-1.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(+0.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(+0.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(-0.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(-0.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(Double.NaN).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(Double.NaN).getPartialDerivative(1), 1.0e-15);
}
@Test
public void testToDegreesDefinition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
Assert.assertEquals(FastMath.toDegrees(x), dsX.toDegrees().getValue(), epsilon);
for (int n = 1; n <= maxOrder; ++n) {
if (n == 1) {
Assert.assertEquals(180 / FastMath.PI, dsX.toDegrees().getPartialDerivative(1), epsilon);
} else {
Assert.assertEquals(0.0, dsX.toDegrees().getPartialDerivative(n), epsilon);
}
}
}
}
}
@Test
public void testToRadiansDefinition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
Assert.assertEquals(FastMath.toRadians(x), dsX.toRadians().getValue(), epsilon);
for (int n = 1; n <= maxOrder; ++n) {
if (n == 1) {
Assert.assertEquals(FastMath.PI / 180, dsX.toRadians().getPartialDerivative(1), epsilon);
} else {
Assert.assertEquals(0.0, dsX.toRadians().getPartialDerivative(n), epsilon);
}
}
}
}
}
@Test
public void testDegRad() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.toDegrees().toRadians();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon);
}
}
}
}
@Test(expected=DimensionMismatchException.class)
public void testComposeMismatchedDimensions() {
new DerivativeStructure(1, 3, 0, 1.2).compose(new double[3]);
}
@Test
public void testCompose() {
double[] epsilon = new double[] { 1.0e-20, 5.0e-14, 2.0e-13, 3.0e-13, 2.0e-13, 1.0e-20 };
PolynomialFunction poly =
new PolynomialFunction(new double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 });
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
PolynomialFunction[] p = new PolynomialFunction[maxOrder + 1];
p[0] = poly;
for (int i = 1; i <= maxOrder; ++i) {
p[i] = p[i - 1].polynomialDerivative();
}
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure dsY1 = dsX.getField().getZero();
for (int i = poly.degree(); i >= 0; --i) {
dsY1 = dsY1.multiply(dsX).add(poly.getCoefficients()[i]);
}
double[] f = new double[maxOrder + 1];
for (int i = 0; i < f.length; ++i) {
f[i] = p[i].value(x);
}
DerivativeStructure dsY2 = dsX.compose(f);
DerivativeStructure zero = dsY1.subtract(dsY2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testField() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
checkF0F1(x.getField().getZero(), 0.0, 0.0, 0.0, 0.0);
checkF0F1(x.getField().getOne(), 1.0, 0.0, 0.0, 0.0);
Assert.assertEquals(maxOrder, x.getField().getZero().getOrder());
Assert.assertEquals(3, x.getField().getZero().getFreeParameters());
Assert.assertEquals(DerivativeStructure.class, x.getField().getRuntimeClass());
}
}
@Test
public void testOneParameterConstructor() {
double x = 1.2;
double cos = FastMath.cos(x);
double sin = FastMath.sin(x);
DerivativeStructure yRef = new DerivativeStructure(1, 4, 0, x).cos();
try {
new DerivativeStructure(1, 4, 0.0, 0.0);
Assert.fail("an exception should have been thrown");
} catch (DimensionMismatchException dme) {
// expected
} catch (Exception e) {
Assert.fail("wrong exceptionc caught " + e.getClass().getName());
}
double[] derivatives = new double[] { cos, -sin, -cos, sin, cos };
DerivativeStructure y = new DerivativeStructure(1, 4, derivatives);
checkEquals(yRef, y, 1.0e-15);
TestUtils.assertEquals(derivatives, y.getAllDerivatives(), 1.0e-15);
}
@Test
public void testOneOrderConstructor() {
double x = 1.2;
double y = 2.4;
double z = 12.5;
DerivativeStructure xRef = new DerivativeStructure(3, 1, 0, x);
DerivativeStructure yRef = new DerivativeStructure(3, 1, 1, y);
DerivativeStructure zRef = new DerivativeStructure(3, 1, 2, z);
try {
new DerivativeStructure(3, 1, x + y - z, 1.0, 1.0);
Assert.fail("an exception should have been thrown");
} catch (DimensionMismatchException dme) {
// expected
} catch (Exception e) {
Assert.fail("wrong exceptionc caught " + e.getClass().getName());
}
double[] derivatives = new double[] { x + y - z, 1.0, 1.0, -1.0 };
DerivativeStructure t = new DerivativeStructure(3, 1, derivatives);
checkEquals(xRef.add(yRef.subtract(zRef)), t, 1.0e-15);
TestUtils.assertEquals(derivatives, xRef.add(yRef.subtract(zRef)).getAllDerivatives(), 1.0e-15);
}
@Test
public void testSerialization() {
DerivativeStructure a = new DerivativeStructure(3, 2, 0, 1.3);
DerivativeStructure b = (DerivativeStructure) TestUtils.serializeAndRecover(a);
Assert.assertEquals(a.getFreeParameters(), b.getFreeParameters());
Assert.assertEquals(a.getOrder(), b.getOrder());
checkEquals(a, b, 1.0e-15);
}
private void checkF0F1(DerivativeStructure ds, double value, double...derivatives) {
// check dimension
Assert.assertEquals(derivatives.length, ds.getFreeParameters());
// check value, directly and also as 0th order derivative
Assert.assertEquals(value, ds.getValue(), 1.0e-15);
Assert.assertEquals(value, ds.getPartialDerivative(new int[ds.getFreeParameters()]), 1.0e-15);
// check first order derivatives
for (int i = 0; i < derivatives.length; ++i) {
int[] orders = new int[derivatives.length];
orders[i] = 1;
Assert.assertEquals(derivatives[i], ds.getPartialDerivative(orders), 1.0e-15);
}
}
private void checkEquals(DerivativeStructure ds1, DerivativeStructure ds2, double epsilon) {
// check dimension
Assert.assertEquals(ds1.getFreeParameters(), ds2.getFreeParameters());
Assert.assertEquals(ds1.getOrder(), ds2.getOrder());
int[] derivatives = new int[ds1.getFreeParameters()];
int sum = 0;
while (true) {
if (sum <= ds1.getOrder()) {
Assert.assertEquals(ds1.getPartialDerivative(derivatives),
ds2.getPartialDerivative(derivatives),
epsilon);
}
boolean increment = true;
sum = 0;
for (int i = derivatives.length - 1; i >= 0; --i) {
if (increment) {
if (derivatives[i] == ds1.getOrder()) {
derivatives[i] = 0;
} else {
derivatives[i]++;
increment = false;
}
}
sum += derivatives[i];
}
if (increment) {
return;
}
}
}
} | // You are a professional Java test case writer, please create a test case named `testAtan2SpecialCases` for the issue `Math-MATH-935`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-935
//
// ## Issue-Title:
// DerivativeStructure.atan2(y,x) does not handle special cases properly
//
// ## Issue-Description:
//
// The four special cases +/-0 for both x and y should give the same values as Math.atan2 and FastMath.atan2. However, they give NaN for the value in all cases.
//
//
//
//
//
@Test
public void testAtan2SpecialCases() {
| 834 | 10 | 809 | src/test/java/org/apache/commons/math3/analysis/differentiation/DerivativeStructureTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-935
## Issue-Title:
DerivativeStructure.atan2(y,x) does not handle special cases properly
## Issue-Description:
The four special cases +/-0 for both x and y should give the same values as Math.atan2 and FastMath.atan2. However, they give NaN for the value in all cases.
```
You are a professional Java test case writer, please create a test case named `testAtan2SpecialCases` for the issue `Math-MATH-935`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testAtan2SpecialCases() {
```
| 809 | [
"org.apache.commons.math3.analysis.differentiation.DSCompiler"
] | 578470b3dff8b94489beaf9a3cd089f444b5873e7f01f8b168fe833c2a9bac63 | @Test
public void testAtan2SpecialCases() | // You are a professional Java test case writer, please create a test case named `testAtan2SpecialCases` for the issue `Math-MATH-935`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-935
//
// ## Issue-Title:
// DerivativeStructure.atan2(y,x) does not handle special cases properly
//
// ## Issue-Description:
//
// The four special cases +/-0 for both x and y should give the same values as Math.atan2 and FastMath.atan2. However, they give NaN for the value in all cases.
//
//
//
//
//
| 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.analysis.differentiation;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.math3.TestUtils;
import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.util.ArithmeticUtils;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
/**
* Test for class {@link DerivativeStructure}.
*/
public class DerivativeStructureTest {
@Test(expected=NumberIsTooLargeException.class)
public void testWrongVariableIndex() {
new DerivativeStructure(3, 1, 3, 1.0);
}
@Test(expected=DimensionMismatchException.class)
public void testMissingOrders() {
new DerivativeStructure(3, 1, 0, 1.0).getPartialDerivative(0, 1);
}
@Test(expected=NumberIsTooLargeException.class)
public void testTooLargeOrder() {
new DerivativeStructure(3, 1, 0, 1.0).getPartialDerivative(1, 1, 2);
}
@Test
public void testVariableWithoutDerivative0() {
DerivativeStructure v = new DerivativeStructure(1, 0, 0, 1.0);
Assert.assertEquals(1.0, v.getValue(), 1.0e-15);
}
@Test(expected=NumberIsTooLargeException.class)
public void testVariableWithoutDerivative1() {
DerivativeStructure v = new DerivativeStructure(1, 0, 0, 1.0);
Assert.assertEquals(1.0, v.getPartialDerivative(1), 1.0e-15);
}
@Test
public void testVariable() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0),
1.0, 1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0),
2.0, 0.0, 1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0),
3.0, 0.0, 0.0, 1.0);
}
}
@Test
public void testConstant() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, FastMath.PI),
FastMath.PI, 0.0, 0.0, 0.0);
}
}
@Test
public void testPrimitiveAdd() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).add(5), 6.0, 1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).add(5), 7.0, 0.0, 1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).add(5), 8.0, 0.0, 0.0, 1.0);
}
}
@Test
public void testAdd() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
DerivativeStructure xyz = x.add(y.add(z));
checkF0F1(xyz, x.getValue() + y.getValue() + z.getValue(), 1.0, 1.0, 1.0);
}
}
@Test
public void testPrimitiveSubtract() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).subtract(5), -4.0, 1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).subtract(5), -3.0, 0.0, 1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).subtract(5), -2.0, 0.0, 0.0, 1.0);
}
}
@Test
public void testSubtract() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
DerivativeStructure xyz = x.subtract(y.subtract(z));
checkF0F1(xyz, x.getValue() - (y.getValue() - z.getValue()), 1.0, -1.0, 1.0);
}
}
@Test
public void testPrimitiveMultiply() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).multiply(5), 5.0, 5.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).multiply(5), 10.0, 0.0, 5.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).multiply(5), 15.0, 0.0, 0.0, 5.0);
}
}
@Test
public void testMultiply() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
DerivativeStructure xyz = x.multiply(y.multiply(z));
for (int i = 0; i <= maxOrder; ++i) {
for (int j = 0; j <= maxOrder; ++j) {
for (int k = 0; k <= maxOrder; ++k) {
if (i + j + k <= maxOrder) {
Assert.assertEquals((i == 0 ? x.getValue() : (i == 1 ? 1.0 : 0.0)) *
(j == 0 ? y.getValue() : (j == 1 ? 1.0 : 0.0)) *
(k == 0 ? z.getValue() : (k == 1 ? 1.0 : 0.0)),
xyz.getPartialDerivative(i, j, k),
1.0e-15);
}
}
}
}
}
}
@Test
public void testNegate() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
checkF0F1(new DerivativeStructure(3, maxOrder, 0, 1.0).negate(), -1.0, -1.0, 0.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 1, 2.0).negate(), -2.0, 0.0, -1.0, 0.0);
checkF0F1(new DerivativeStructure(3, maxOrder, 2, 3.0).negate(), -3.0, 0.0, 0.0, -1.0);
}
}
@Test
public void testReciprocal() {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure r = new DerivativeStructure(1, 6, 0, x).reciprocal();
Assert.assertEquals(1 / x, r.getValue(), 1.0e-15);
for (int i = 1; i < r.getOrder(); ++i) {
double expected = ArithmeticUtils.pow(-1, i) * ArithmeticUtils.factorial(i) /
FastMath.pow(x, i + 1);
Assert.assertEquals(expected, r.getPartialDerivative(i), 1.0e-15 * FastMath.abs(expected));
}
}
}
@Test
public void testPow() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
for (int n = 0; n < 10; ++n) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
DerivativeStructure y = new DerivativeStructure(3, maxOrder, 1, 2.0);
DerivativeStructure z = new DerivativeStructure(3, maxOrder, 2, 3.0);
List<DerivativeStructure> list = Arrays.asList(x, y, z,
x.add(y).add(z),
x.multiply(y).multiply(z));
if (n == 0) {
for (DerivativeStructure ds : list) {
checkEquals(ds.getField().getOne(), ds.pow(n), 1.0e-15);
}
} else if (n == 1) {
for (DerivativeStructure ds : list) {
checkEquals(ds, ds.pow(n), 1.0e-15);
}
} else {
for (DerivativeStructure ds : list) {
DerivativeStructure p = ds.getField().getOne();
for (int i = 0; i < n; ++i) {
p = p.multiply(ds);
}
checkEquals(p, ds.pow(n), 1.0e-15);
}
}
}
}
}
@Test
public void testExpression() {
double epsilon = 2.5e-13;
for (double x = 0; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(3, 5, 0, x);
for (double y = 0; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(3, 5, 1, y);
for (double z = 0; z >- 2; z -= 0.2) {
DerivativeStructure dsZ = new DerivativeStructure(3, 5, 2, z);
// f(x, y, z) = x + 5 x y - 2 z + (8 z x - y)^3
DerivativeStructure ds =
new DerivativeStructure(1, dsX,
5, dsX.multiply(dsY),
-2, dsZ,
1, new DerivativeStructure(8, dsZ.multiply(dsX),
-1, dsY).pow(3));
DerivativeStructure dsOther =
new DerivativeStructure(1, dsX,
5, dsX.multiply(dsY),
-2, dsZ).add(new DerivativeStructure(8, dsZ.multiply(dsX),
-1, dsY).pow(3));
double f = x + 5 * x * y - 2 * z + FastMath.pow(8 * z * x - y, 3);
Assert.assertEquals(f, ds.getValue(),
FastMath.abs(epsilon * f));
Assert.assertEquals(f, dsOther.getValue(),
FastMath.abs(epsilon * f));
// df/dx = 1 + 5 y + 24 (8 z x - y)^2 z
double dfdx = 1 + 5 * y + 24 * z * FastMath.pow(8 * z * x - y, 2);
Assert.assertEquals(dfdx, ds.getPartialDerivative(1, 0, 0),
FastMath.abs(epsilon * dfdx));
Assert.assertEquals(dfdx, dsOther.getPartialDerivative(1, 0, 0),
FastMath.abs(epsilon * dfdx));
// df/dxdy = 5 + 48 z*(y - 8 z x)
double dfdxdy = 5 + 48 * z * (y - 8 * z * x);
Assert.assertEquals(dfdxdy, ds.getPartialDerivative(1, 1, 0),
FastMath.abs(epsilon * dfdxdy));
Assert.assertEquals(dfdxdy, dsOther.getPartialDerivative(1, 1, 0),
FastMath.abs(epsilon * dfdxdy));
// df/dxdydz = 48 (y - 16 z x)
double dfdxdydz = 48 * (y - 16 * z * x);
Assert.assertEquals(dfdxdydz, ds.getPartialDerivative(1, 1, 1),
FastMath.abs(epsilon * dfdxdydz));
Assert.assertEquals(dfdxdydz, dsOther.getPartialDerivative(1, 1, 1),
FastMath.abs(epsilon * dfdxdydz));
}
}
}
}
@Test
public void testCompositionOneVariableX() {
double epsilon = 1.0e-13;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
for (double y = 0.1; y < 1.2; y += 0.1) {
DerivativeStructure dsY = new DerivativeStructure(1, maxOrder, y);
DerivativeStructure f = dsX.divide(dsY).sqrt();
double f0 = FastMath.sqrt(x / y);
Assert.assertEquals(f0, f.getValue(), FastMath.abs(epsilon * f0));
if (f.getOrder() > 0) {
double f1 = 1 / (2 * FastMath.sqrt(x * y));
Assert.assertEquals(f1, f.getPartialDerivative(1), FastMath.abs(epsilon * f1));
if (f.getOrder() > 1) {
double f2 = -f1 / (2 * x);
Assert.assertEquals(f2, f.getPartialDerivative(2), FastMath.abs(epsilon * f2));
if (f.getOrder() > 2) {
double f3 = (f0 + x / (2 * y * f0)) / (4 * x * x * x);
Assert.assertEquals(f3, f.getPartialDerivative(3), FastMath.abs(epsilon * f3));
}
}
}
}
}
}
}
@Test
public void testTrigo() {
double epsilon = 2.0e-12;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(3, maxOrder, 0, x);
for (double y = 0.1; y < 1.2; y += 0.1) {
DerivativeStructure dsY = new DerivativeStructure(3, maxOrder, 1, y);
for (double z = 0.1; z < 1.2; z += 0.1) {
DerivativeStructure dsZ = new DerivativeStructure(3, maxOrder, 2, z);
DerivativeStructure f = dsX.divide(dsY.cos().add(dsZ.tan())).sin();
double a = FastMath.cos(y) + FastMath.tan(z);
double f0 = FastMath.sin(x / a);
Assert.assertEquals(f0, f.getValue(), FastMath.abs(epsilon * f0));
if (f.getOrder() > 0) {
double dfdx = FastMath.cos(x / a) / a;
Assert.assertEquals(dfdx, f.getPartialDerivative(1, 0, 0), FastMath.abs(epsilon * dfdx));
double dfdy = x * FastMath.sin(y) * dfdx / a;
Assert.assertEquals(dfdy, f.getPartialDerivative(0, 1, 0), FastMath.abs(epsilon * dfdy));
double cz = FastMath.cos(z);
double cz2 = cz * cz;
double dfdz = -x * dfdx / (a * cz2);
Assert.assertEquals(dfdz, f.getPartialDerivative(0, 0, 1), FastMath.abs(epsilon * dfdz));
if (f.getOrder() > 1) {
double df2dx2 = -(f0 / (a * a));
Assert.assertEquals(df2dx2, f.getPartialDerivative(2, 0, 0), FastMath.abs(epsilon * df2dx2));
double df2dy2 = x * FastMath.cos(y) * dfdx / a -
x * x * FastMath.sin(y) * FastMath.sin(y) * f0 / (a * a * a * a) +
2 * FastMath.sin(y) * dfdy / a;
Assert.assertEquals(df2dy2, f.getPartialDerivative(0, 2, 0), FastMath.abs(epsilon * df2dy2));
double c4 = cz2 * cz2;
double df2dz2 = x * (2 * a * (1 - a * cz * FastMath.sin(z)) * dfdx - x * f0 / a ) / (a * a * a * c4);
Assert.assertEquals(df2dz2, f.getPartialDerivative(0, 0, 2), FastMath.abs(epsilon * df2dz2));
double df2dxdy = dfdy / x - x * FastMath.sin(y) * f0 / (a * a * a);
Assert.assertEquals(df2dxdy, f.getPartialDerivative(1, 1, 0), FastMath.abs(epsilon * df2dxdy));
}
}
}
}
}
}
}
@Test
public void testSqrtDefinition() {
double[] epsilon = new double[] { 5.0e-16, 5.0e-16, 2.0e-15, 5.0e-14, 2.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure sqrt1 = dsX.pow(0.5);
DerivativeStructure sqrt2 = dsX.sqrt();
DerivativeStructure zero = sqrt1.subtract(sqrt2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testRootNSingularity() {
for (int n = 2; n < 10; ++n) {
for (int maxOrder = 0; maxOrder < 12; ++maxOrder) {
DerivativeStructure dsZero = new DerivativeStructure(1, maxOrder, 0, 0.0);
DerivativeStructure rootN = dsZero.rootN(n);
Assert.assertEquals(0.0, rootN.getValue(), 1.0e-20);
if (maxOrder > 0) {
Assert.assertTrue(Double.isInfinite(rootN.getPartialDerivative(1)));
Assert.assertTrue(rootN.getPartialDerivative(1) > 0);
for (int order = 2; order <= maxOrder; ++order) {
// the following checks shows a LIMITATION of the current implementation
// we have no way to tell dsZero is a pure linear variable x = 0
// we only say: "dsZero is a structure with value = 0.0,
// first derivative = 1.0, second and higher derivatives = 0.0".
// Function composition rule for second derivatives is:
// d2[f(g(x))]/dx2 = f''(g(x)) * [g'(x)]^2 + f'(g(x)) * g''(x)
// when function f is the nth root and x = 0 we have:
// f(0) = 0, f'(0) = +infinity, f''(0) = -infinity (and higher
// derivatives keep switching between +infinity and -infinity)
// so given that in our case dsZero represents g, we have g(x) = 0,
// g'(x) = 1 and g''(x) = 0
// applying the composition rules gives:
// d2[f(g(x))]/dx2 = f''(g(x)) * [g'(x)]^2 + f'(g(x)) * g''(x)
// = -infinity * 1^2 + +infinity * 0
// = -infinity + NaN
// = NaN
// if we knew dsZero is really the x variable and not the identity
// function applied to x, we would not have computed f'(g(x)) * g''(x)
// and we would have found that the result was -infinity and not NaN
Assert.assertTrue(Double.isNaN(rootN.getPartialDerivative(order)));
}
}
// the following shows that the limitation explained above is NOT a bug...
// if we set up the higher order derivatives for g appropriately, we do
// compute the higher order derivatives of the composition correctly
double[] gDerivatives = new double[ 1 + maxOrder];
gDerivatives[0] = 0.0;
for (int k = 1; k <= maxOrder; ++k) {
gDerivatives[k] = FastMath.pow(-1.0, k + 1);
}
DerivativeStructure correctRoot = new DerivativeStructure(1, maxOrder, gDerivatives).rootN(n);
Assert.assertEquals(0.0, correctRoot.getValue(), 1.0e-20);
if (maxOrder > 0) {
Assert.assertTrue(Double.isInfinite(correctRoot.getPartialDerivative(1)));
Assert.assertTrue(correctRoot.getPartialDerivative(1) > 0);
for (int order = 2; order <= maxOrder; ++order) {
Assert.assertTrue(Double.isInfinite(correctRoot.getPartialDerivative(order)));
if ((order % 2) == 0) {
Assert.assertTrue(correctRoot.getPartialDerivative(order) < 0);
} else {
Assert.assertTrue(correctRoot.getPartialDerivative(order) > 0);
}
}
}
}
}
}
@Test
public void testSqrtPow2() {
double[] epsilon = new double[] { 1.0e-16, 3.0e-16, 2.0e-15, 6.0e-14, 6.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.multiply(dsX).sqrt();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCbrtDefinition() {
double[] epsilon = new double[] { 4.0e-16, 9.0e-16, 6.0e-15, 2.0e-13, 4.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure cbrt1 = dsX.pow(1.0 / 3.0);
DerivativeStructure cbrt2 = dsX.cbrt();
DerivativeStructure zero = cbrt1.subtract(cbrt2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCbrtPow3() {
double[] epsilon = new double[] { 1.0e-16, 5.0e-16, 8.0e-15, 3.0e-13, 4.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.multiply(dsX.multiply(dsX)).cbrt();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testPowReciprocalPow() {
double[] epsilon = new double[] { 2.0e-15, 2.0e-14, 3.0e-13, 8.0e-12, 3.0e-10 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.01) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = 0.1; y < 1.2; y += 0.01) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure rebuiltX = dsX.pow(dsY).pow(dsY.reciprocal());
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n, m), epsilon[n + m]);
}
}
}
}
}
}
}
@Test
public void testHypotDefinition() {
double epsilon = 1.0e-20;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure hypot = DerivativeStructure.hypot(dsY, dsX);
DerivativeStructure ref = dsX.multiply(dsX).add(dsY.multiply(dsY)).sqrt();
DerivativeStructure zero = hypot.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon);
}
}
}
}
}
}
}
@Test
public void testHypotNoOverflow() {
DerivativeStructure dsX = new DerivativeStructure(2, 5, 0, +3.0e250);
DerivativeStructure dsY = new DerivativeStructure(2, 5, 1, -4.0e250);
DerivativeStructure hypot = DerivativeStructure.hypot(dsX, dsY);
Assert.assertEquals(5.0e250, hypot.getValue(), 1.0e235);
Assert.assertEquals(dsX.getValue() / hypot.getValue(), hypot.getPartialDerivative(1, 0), 1.0e-10);
Assert.assertEquals(dsY.getValue() / hypot.getValue(), hypot.getPartialDerivative(0, 1), 1.0e-10);
DerivativeStructure sqrt = dsX.multiply(dsX).add(dsY.multiply(dsY)).sqrt();
Assert.assertTrue(Double.isInfinite(sqrt.getValue()));
}
@Test
public void testPrimitiveRemainder() {
double epsilon = 1.0e-15;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure remainder = dsX.remainder(y);
DerivativeStructure ref = dsX.subtract(x - (x % y));
DerivativeStructure zero = remainder.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon);
}
}
}
}
}
}
}
@Test
public void testRemainder() {
double epsilon = 1.0e-15;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure remainder = dsX.remainder(dsY);
DerivativeStructure ref = dsX.subtract(dsY.multiply((x - (x % y)) / y));
DerivativeStructure zero = remainder.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon);
}
}
}
}
}
}
}
@Test
public void testExp() {
double[] epsilon = new double[] { 1.0e-16, 1.0e-16, 1.0e-16, 1.0e-16, 1.0e-16 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
double refExp = FastMath.exp(x);
DerivativeStructure exp = new DerivativeStructure(1, maxOrder, 0, x).exp();
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(refExp, exp.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testExpm1Definition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure expm11 = dsX.expm1();
DerivativeStructure expm12 = dsX.exp().subtract(dsX.getField().getOne());
DerivativeStructure zero = expm11.subtract(expm12);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon);
}
}
}
}
@Test
public void testLog() {
double[] epsilon = new double[] { 1.0e-16, 1.0e-16, 3.0e-14, 7.0e-13, 3.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure log = new DerivativeStructure(1, maxOrder, 0, x).log();
Assert.assertEquals(FastMath.log(x), log.getValue(), epsilon[0]);
for (int n = 1; n <= maxOrder; ++n) {
double refDer = -ArithmeticUtils.factorial(n - 1) / FastMath.pow(-x, n);
Assert.assertEquals(refDer, log.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLog1pDefinition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure log1p1 = dsX.log1p();
DerivativeStructure log1p2 = dsX.add(dsX.getField().getOne()).log();
DerivativeStructure zero = log1p1.subtract(log1p2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon);
}
}
}
}
@Test
public void testLog10Definition() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 8.0e-15, 3.0e-13, 8.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure log101 = dsX.log10();
DerivativeStructure log102 = dsX.log().divide(FastMath.log(10.0));
DerivativeStructure zero = log101.subtract(log102);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLogExp() {
double[] epsilon = new double[] { 2.0e-16, 2.0e-16, 3.0e-16, 2.0e-15, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.exp().log();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLog1pExpm1() {
double[] epsilon = new double[] { 6.0e-17, 3.0e-16, 5.0e-16, 9.0e-16, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.expm1().log1p();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testLog10Power() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 9.0e-16, 6.0e-15, 6.0e-14 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = new DerivativeStructure(1, maxOrder, 10.0).pow(dsX).log10();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testSinCos() {
double epsilon = 5.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure sin = dsX.sin();
DerivativeStructure cos = dsX.cos();
double s = FastMath.sin(x);
double c = FastMath.cos(x);
for (int n = 0; n <= maxOrder; ++n) {
switch (n % 4) {
case 0 :
Assert.assertEquals( s, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals( c, cos.getPartialDerivative(n), epsilon);
break;
case 1 :
Assert.assertEquals( c, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals(-s, cos.getPartialDerivative(n), epsilon);
break;
case 2 :
Assert.assertEquals(-s, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals(-c, cos.getPartialDerivative(n), epsilon);
break;
default :
Assert.assertEquals(-c, sin.getPartialDerivative(n), epsilon);
Assert.assertEquals( s, cos.getPartialDerivative(n), epsilon);
break;
}
}
}
}
}
@Test
public void testSinAsin() {
double[] epsilon = new double[] { 3.0e-16, 5.0e-16, 3.0e-15, 2.0e-14, 4.0e-13 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.sin().asin();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCosAcos() {
double[] epsilon = new double[] { 6.0e-16, 6.0e-15, 2.0e-13, 4.0e-12, 2.0e-10 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.cos().acos();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTanAtan() {
double[] epsilon = new double[] { 6.0e-17, 2.0e-16, 2.0e-15, 4.0e-14, 2.0e-12 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.tan().atan();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTangentDefinition() {
double[] epsilon = new double[] { 5.0e-16, 2.0e-15, 3.0e-14, 5.0e-13, 2.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure tan1 = dsX.sin().divide(dsX.cos());
DerivativeStructure tan2 = dsX.tan();
DerivativeStructure zero = tan1.subtract(tan2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testAtan2() {
double[] epsilon = new double[] { 5.0e-16, 3.0e-15, 2.2e-14, 1.0e-12, 8.0e-11 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = -1.7; x < 2; x += 0.2) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x);
for (double y = -1.7; y < 2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y);
DerivativeStructure atan2 = DerivativeStructure.atan2(dsY, dsX);
DerivativeStructure ref = dsY.divide(dsX).atan();
if (x < 0) {
ref = (y < 0) ? ref.subtract(FastMath.PI) : ref.add(FastMath.PI);
}
DerivativeStructure zero = atan2.subtract(ref);
for (int n = 0; n <= maxOrder; ++n) {
for (int m = 0; m <= maxOrder; ++m) {
if (n + m <= maxOrder) {
Assert.assertEquals(0, zero.getPartialDerivative(n, m), epsilon[n + m]);
}
}
}
}
}
}
}
@Test
public void testAtan2SpecialCases() {
DerivativeStructure pp =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, +0.0),
new DerivativeStructure(2, 2, 1, +0.0));
Assert.assertEquals(0, pp.getValue(), 1.0e-15);
Assert.assertEquals(+1, FastMath.copySign(1, pp.getValue()), 1.0e-15);
DerivativeStructure pn =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, +0.0),
new DerivativeStructure(2, 2, 1, -0.0));
Assert.assertEquals(FastMath.PI, pn.getValue(), 1.0e-15);
DerivativeStructure np =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, -0.0),
new DerivativeStructure(2, 2, 1, +0.0));
Assert.assertEquals(0, np.getValue(), 1.0e-15);
Assert.assertEquals(-1, FastMath.copySign(1, np.getValue()), 1.0e-15);
DerivativeStructure nn =
DerivativeStructure.atan2(new DerivativeStructure(2, 2, 1, -0.0),
new DerivativeStructure(2, 2, 1, -0.0));
Assert.assertEquals(-FastMath.PI, nn.getValue(), 1.0e-15);
}
@Test
public void testSinhDefinition() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 5.0e-16, 2.0e-15, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure sinh1 = dsX.exp().subtract(dsX.exp().reciprocal()).multiply(0.5);
DerivativeStructure sinh2 = dsX.sinh();
DerivativeStructure zero = sinh1.subtract(sinh2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCoshDefinition() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 5.0e-16, 2.0e-15, 6.0e-15 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure cosh1 = dsX.exp().add(dsX.exp().reciprocal()).multiply(0.5);
DerivativeStructure cosh2 = dsX.cosh();
DerivativeStructure zero = cosh1.subtract(cosh2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTanhDefinition() {
double[] epsilon = new double[] { 3.0e-16, 5.0e-16, 7.0e-16, 3.0e-15, 2.0e-14 };
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure tanh1 = dsX.exp().subtract(dsX.exp().reciprocal()).divide(dsX.exp().add(dsX.exp().reciprocal()));
DerivativeStructure tanh2 = dsX.tanh();
DerivativeStructure zero = tanh1.subtract(tanh2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testSinhAsinh() {
double[] epsilon = new double[] { 3.0e-16, 3.0e-16, 4.0e-16, 7.0e-16, 3.0e-15, 8.0e-15 };
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.sinh().asinh();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCoshAcosh() {
double[] epsilon = new double[] { 2.0e-15, 1.0e-14, 2.0e-13, 6.0e-12, 3.0e-10, 2.0e-8 };
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.cosh().acosh();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testTanhAtanh() {
double[] epsilon = new double[] { 3.0e-16, 2.0e-16, 7.0e-16, 4.0e-15, 3.0e-14, 4.0e-13 };
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.tanh().atanh();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testCompositionOneVariableY() {
double epsilon = 1.0e-13;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, x);
for (double y = 0.1; y < 1.2; y += 0.1) {
DerivativeStructure dsY = new DerivativeStructure(1, maxOrder, 0, y);
DerivativeStructure f = dsX.divide(dsY).sqrt();
double f0 = FastMath.sqrt(x / y);
Assert.assertEquals(f0, f.getValue(), FastMath.abs(epsilon * f0));
if (f.getOrder() > 0) {
double f1 = -x / (2 * y * y * f0);
Assert.assertEquals(f1, f.getPartialDerivative(1), FastMath.abs(epsilon * f1));
if (f.getOrder() > 1) {
double f2 = (f0 - x / (4 * y * f0)) / (y * y);
Assert.assertEquals(f2, f.getPartialDerivative(2), FastMath.abs(epsilon * f2));
if (f.getOrder() > 2) {
double f3 = (x / (8 * y * f0) - 2 * f0) / (y * y * y);
Assert.assertEquals(f3, f.getPartialDerivative(3), FastMath.abs(epsilon * f3));
}
}
}
}
}
}
}
@Test
public void testTaylorPolynomial() {
for (double x = 0; x < 1.2; x += 0.1) {
DerivativeStructure dsX = new DerivativeStructure(3, 4, 0, x);
for (double y = 0; y < 1.2; y += 0.2) {
DerivativeStructure dsY = new DerivativeStructure(3, 4, 1, y);
for (double z = 0; z < 1.2; z += 0.2) {
DerivativeStructure dsZ = new DerivativeStructure(3, 4, 2, z);
DerivativeStructure f = dsX.multiply(dsY).add(dsZ).multiply(dsX).multiply(dsY);
for (double dx = -0.2; dx < 0.2; dx += 0.2) {
for (double dy = -0.2; dy < 0.2; dy += 0.1) {
for (double dz = -0.2; dz < 0.2; dz += 0.1) {
double ref = (x + dx) * (y + dy) * ((x + dx) * (y + dy) + (z + dz));
Assert.assertEquals(ref, f.taylor(dx, dy, dz), 2.0e-15);
}
}
}
}
}
}
}
@Test
public void testTaylorAtan2() {
double[] expected = new double[] { 0.214, 0.0241, 0.00422, 6.48e-4, 8.04e-5 };
double x0 = 0.1;
double y0 = -0.3;
for (int maxOrder = 0; maxOrder < 5; ++maxOrder) {
DerivativeStructure dsX = new DerivativeStructure(2, maxOrder, 0, x0);
DerivativeStructure dsY = new DerivativeStructure(2, maxOrder, 1, y0);
DerivativeStructure atan2 = DerivativeStructure.atan2(dsY, dsX);
double maxError = 0;
for (double dx = -0.05; dx < 0.05; dx += 0.001) {
for (double dy = -0.05; dy < 0.05; dy += 0.001) {
double ref = FastMath.atan2(y0 + dy, x0 + dx);
maxError = FastMath.max(maxError, FastMath.abs(ref - atan2.taylor(dx, dy)));
}
}
Assert.assertEquals(0.0, expected[maxOrder] - maxError, 0.01 * expected[maxOrder]);
}
}
@Test
public void testAbs() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(+1.0, minusOne.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusOne = new DerivativeStructure(1, 1, 0, +1.0);
Assert.assertEquals(+1.0, plusOne.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, plusOne.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure minusZero = new DerivativeStructure(1, 1, 0, -0.0);
Assert.assertEquals(+0.0, minusZero.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusZero.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusZero = new DerivativeStructure(1, 1, 0, +0.0);
Assert.assertEquals(+0.0, plusZero.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, plusZero.abs().getPartialDerivative(1), 1.0e-15);
}
@Test
public void testSignum() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(-1.0, minusOne.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals( 0.0, minusOne.signum().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusOne = new DerivativeStructure(1, 1, 0, +1.0);
Assert.assertEquals(+1.0, plusOne.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals( 0.0, plusOne.signum().getPartialDerivative(1), 1.0e-15);
DerivativeStructure minusZero = new DerivativeStructure(1, 1, 0, -0.0);
Assert.assertEquals(-0.0, minusZero.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertTrue(Double.doubleToLongBits(minusZero.signum().getValue()) < 0);
Assert.assertEquals( 0.0, minusZero.signum().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusZero = new DerivativeStructure(1, 1, 0, +0.0);
Assert.assertEquals(+0.0, plusZero.signum().getPartialDerivative(0), 1.0e-15);
Assert.assertTrue(Double.doubleToLongBits(plusZero.signum().getValue()) == 0);
Assert.assertEquals( 0.0, plusZero.signum().getPartialDerivative(1), 1.0e-15);
}
@Test
public void testCeilFloorRintLong() {
DerivativeStructure x = new DerivativeStructure(1, 1, 0, -1.5);
Assert.assertEquals(-1.5, x.getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, x.getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, x.ceil().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+0.0, x.ceil().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-2.0, x.floor().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+0.0, x.floor().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-2.0, x.rint().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+0.0, x.rint().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-2.0, x.subtract(x.getField().getOne()).rint().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1l, x.round());
}
@Test
public void testCopySign() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(+1.0, minusOne.copySign(+1.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(+1.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(-1.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(-1.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(+0.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(+0.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(-0.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(-0.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(Double.NaN).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(Double.NaN).getPartialDerivative(1), 1.0e-15);
}
@Test
public void testToDegreesDefinition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
Assert.assertEquals(FastMath.toDegrees(x), dsX.toDegrees().getValue(), epsilon);
for (int n = 1; n <= maxOrder; ++n) {
if (n == 1) {
Assert.assertEquals(180 / FastMath.PI, dsX.toDegrees().getPartialDerivative(1), epsilon);
} else {
Assert.assertEquals(0.0, dsX.toDegrees().getPartialDerivative(n), epsilon);
}
}
}
}
}
@Test
public void testToRadiansDefinition() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
Assert.assertEquals(FastMath.toRadians(x), dsX.toRadians().getValue(), epsilon);
for (int n = 1; n <= maxOrder; ++n) {
if (n == 1) {
Assert.assertEquals(FastMath.PI / 180, dsX.toRadians().getPartialDerivative(1), epsilon);
} else {
Assert.assertEquals(0.0, dsX.toRadians().getPartialDerivative(n), epsilon);
}
}
}
}
}
@Test
public void testDegRad() {
double epsilon = 3.0e-16;
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure rebuiltX = dsX.toDegrees().toRadians();
DerivativeStructure zero = rebuiltX.subtract(dsX);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon);
}
}
}
}
@Test(expected=DimensionMismatchException.class)
public void testComposeMismatchedDimensions() {
new DerivativeStructure(1, 3, 0, 1.2).compose(new double[3]);
}
@Test
public void testCompose() {
double[] epsilon = new double[] { 1.0e-20, 5.0e-14, 2.0e-13, 3.0e-13, 2.0e-13, 1.0e-20 };
PolynomialFunction poly =
new PolynomialFunction(new double[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 });
for (int maxOrder = 0; maxOrder < 6; ++maxOrder) {
PolynomialFunction[] p = new PolynomialFunction[maxOrder + 1];
p[0] = poly;
for (int i = 1; i <= maxOrder; ++i) {
p[i] = p[i - 1].polynomialDerivative();
}
for (double x = 0.1; x < 1.2; x += 0.001) {
DerivativeStructure dsX = new DerivativeStructure(1, maxOrder, 0, x);
DerivativeStructure dsY1 = dsX.getField().getZero();
for (int i = poly.degree(); i >= 0; --i) {
dsY1 = dsY1.multiply(dsX).add(poly.getCoefficients()[i]);
}
double[] f = new double[maxOrder + 1];
for (int i = 0; i < f.length; ++i) {
f[i] = p[i].value(x);
}
DerivativeStructure dsY2 = dsX.compose(f);
DerivativeStructure zero = dsY1.subtract(dsY2);
for (int n = 0; n <= maxOrder; ++n) {
Assert.assertEquals(0.0, zero.getPartialDerivative(n), epsilon[n]);
}
}
}
}
@Test
public void testField() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {
DerivativeStructure x = new DerivativeStructure(3, maxOrder, 0, 1.0);
checkF0F1(x.getField().getZero(), 0.0, 0.0, 0.0, 0.0);
checkF0F1(x.getField().getOne(), 1.0, 0.0, 0.0, 0.0);
Assert.assertEquals(maxOrder, x.getField().getZero().getOrder());
Assert.assertEquals(3, x.getField().getZero().getFreeParameters());
Assert.assertEquals(DerivativeStructure.class, x.getField().getRuntimeClass());
}
}
@Test
public void testOneParameterConstructor() {
double x = 1.2;
double cos = FastMath.cos(x);
double sin = FastMath.sin(x);
DerivativeStructure yRef = new DerivativeStructure(1, 4, 0, x).cos();
try {
new DerivativeStructure(1, 4, 0.0, 0.0);
Assert.fail("an exception should have been thrown");
} catch (DimensionMismatchException dme) {
// expected
} catch (Exception e) {
Assert.fail("wrong exceptionc caught " + e.getClass().getName());
}
double[] derivatives = new double[] { cos, -sin, -cos, sin, cos };
DerivativeStructure y = new DerivativeStructure(1, 4, derivatives);
checkEquals(yRef, y, 1.0e-15);
TestUtils.assertEquals(derivatives, y.getAllDerivatives(), 1.0e-15);
}
@Test
public void testOneOrderConstructor() {
double x = 1.2;
double y = 2.4;
double z = 12.5;
DerivativeStructure xRef = new DerivativeStructure(3, 1, 0, x);
DerivativeStructure yRef = new DerivativeStructure(3, 1, 1, y);
DerivativeStructure zRef = new DerivativeStructure(3, 1, 2, z);
try {
new DerivativeStructure(3, 1, x + y - z, 1.0, 1.0);
Assert.fail("an exception should have been thrown");
} catch (DimensionMismatchException dme) {
// expected
} catch (Exception e) {
Assert.fail("wrong exceptionc caught " + e.getClass().getName());
}
double[] derivatives = new double[] { x + y - z, 1.0, 1.0, -1.0 };
DerivativeStructure t = new DerivativeStructure(3, 1, derivatives);
checkEquals(xRef.add(yRef.subtract(zRef)), t, 1.0e-15);
TestUtils.assertEquals(derivatives, xRef.add(yRef.subtract(zRef)).getAllDerivatives(), 1.0e-15);
}
@Test
public void testSerialization() {
DerivativeStructure a = new DerivativeStructure(3, 2, 0, 1.3);
DerivativeStructure b = (DerivativeStructure) TestUtils.serializeAndRecover(a);
Assert.assertEquals(a.getFreeParameters(), b.getFreeParameters());
Assert.assertEquals(a.getOrder(), b.getOrder());
checkEquals(a, b, 1.0e-15);
}
private void checkF0F1(DerivativeStructure ds, double value, double...derivatives) {
// check dimension
Assert.assertEquals(derivatives.length, ds.getFreeParameters());
// check value, directly and also as 0th order derivative
Assert.assertEquals(value, ds.getValue(), 1.0e-15);
Assert.assertEquals(value, ds.getPartialDerivative(new int[ds.getFreeParameters()]), 1.0e-15);
// check first order derivatives
for (int i = 0; i < derivatives.length; ++i) {
int[] orders = new int[derivatives.length];
orders[i] = 1;
Assert.assertEquals(derivatives[i], ds.getPartialDerivative(orders), 1.0e-15);
}
}
private void checkEquals(DerivativeStructure ds1, DerivativeStructure ds2, double epsilon) {
// check dimension
Assert.assertEquals(ds1.getFreeParameters(), ds2.getFreeParameters());
Assert.assertEquals(ds1.getOrder(), ds2.getOrder());
int[] derivatives = new int[ds1.getFreeParameters()];
int sum = 0;
while (true) {
if (sum <= ds1.getOrder()) {
Assert.assertEquals(ds1.getPartialDerivative(derivatives),
ds2.getPartialDerivative(derivatives),
epsilon);
}
boolean increment = true;
sum = 0;
for (int i = derivatives.length - 1; i >= 0; --i) {
if (increment) {
if (derivatives[i] == ds1.getOrder()) {
derivatives[i] = 0;
} else {
derivatives[i]++;
increment = false;
}
}
sum += derivatives[i];
}
if (increment) {
return;
}
}
}
} |
||
public void testEndMb() throws EncoderException {
String[][] data = {{"mb", "M111111111"}, {"mbmb", "MPM1111111"}};
this.checkEncodings(data);
} | org.apache.commons.codec.language.CaverphoneTest::testEndMb | src/test/org/apache/commons/codec/language/CaverphoneTest.java | 335 | src/test/org/apache/commons/codec/language/CaverphoneTest.java | testEndMb | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec.language;
import junit.framework.Assert;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringEncoder;
import org.apache.commons.codec.StringEncoderAbstractTest;
/**
* @author Apache Software Foundation
* @version $Id$
*/
public class CaverphoneTest extends StringEncoderAbstractTest {
public CaverphoneTest(String name) {
super(name);
}
protected StringEncoder createStringEncoder() {
return new Caverphone();
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* AT11111111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedCommonCodeAT11111111() throws EncoderException {
this.checkEncodingVariations("AT11111111", new String[]{
"add",
"aid",
"at",
"art",
"eat",
"earth",
"head",
"hit",
"hot",
"hold",
"hard",
"heart",
"it",
"out",
"old"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedExamples() throws EncoderException {
String[][] data = {{"Stevenson", "STFNSN1111"}, {"Peter", "PTA1111111"}};
this.checkEncodings(data);
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomNameKLN1111111() throws EncoderException {
this.checkEncodingVariations("KLN1111111", new String[]{
"Cailean",
"Calan",
"Calen",
"Callahan",
"Callan",
"Callean",
"Carleen",
"Carlen",
"Carlene",
"Carlin",
"Carline",
"Carlyn",
"Carlynn",
"Carlynne",
"Charlean",
"Charleen",
"Charlene",
"Charline",
"Cherlyn",
"Chirlin",
"Clein",
"Cleon",
"Cline",
"Cohleen",
"Colan",
"Coleen",
"Colene",
"Colin",
"Colleen",
"Collen",
"Collin",
"Colline",
"Colon",
"Cullan",
"Cullen",
"Cullin",
"Gaelan",
"Galan",
"Galen",
"Garlan",
"Garlen",
"Gaulin",
"Gayleen",
"Gaylene",
"Giliane",
"Gillan",
"Gillian",
"Glen",
"Glenn",
"Glyn",
"Glynn",
"Gollin",
"Gorlin",
"Kalin",
"Karlan",
"Karleen",
"Karlen",
"Karlene",
"Karlin",
"Karlyn",
"Kaylyn",
"Keelin",
"Kellen",
"Kellene",
"Kellyann",
"Kellyn",
"Khalin",
"Kilan",
"Kilian",
"Killen",
"Killian",
"Killion",
"Klein",
"Kleon",
"Kline",
"Koerlin",
"Kylen",
"Kylynn",
"Quillan",
"Quillon",
"Qulllon",
"Xylon"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomNameTN11111111() throws EncoderException {
this.checkEncodingVariations("TN11111111", new String[]{
"Dan",
"Dane",
"Dann",
"Darn",
"Daune",
"Dawn",
"Ddene",
"Dean",
"Deane",
"Deanne",
"DeeAnn",
"Deeann",
"Deeanne",
"Deeyn",
"Den",
"Dene",
"Denn",
"Deonne",
"Diahann",
"Dian",
"Diane",
"Diann",
"Dianne",
"Diannne",
"Dine",
"Dion",
"Dione",
"Dionne",
"Doane",
"Doehne",
"Don",
"Donn",
"Doone",
"Dorn",
"Down",
"Downe",
"Duane",
"Dun",
"Dunn",
"Duyne",
"Dyan",
"Dyane",
"Dyann",
"Dyanne",
"Dyun",
"Tan",
"Tann",
"Teahan",
"Ten",
"Tenn",
"Terhune",
"Thain",
"Thaine",
"Thane",
"Thanh",
"Thayne",
"Theone",
"Thin",
"Thorn",
"Thorne",
"Thun",
"Thynne",
"Tien",
"Tine",
"Tjon",
"Town",
"Towne",
"Turne",
"Tyne"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomNameTTA1111111() throws EncoderException {
this.checkEncodingVariations("TTA1111111", new String[]{
"Darda",
"Datha",
"Dedie",
"Deedee",
"Deerdre",
"Deidre",
"Deirdre",
"Detta",
"Didi",
"Didier",
"Dido",
"Dierdre",
"Dieter",
"Dita",
"Ditter",
"Dodi",
"Dodie",
"Dody",
"Doherty",
"Dorthea",
"Dorthy",
"Doti",
"Dotti",
"Dottie",
"Dotty",
"Doty",
"Doughty",
"Douty",
"Dowdell",
"Duthie",
"Tada",
"Taddeo",
"Tadeo",
"Tadio",
"Tati",
"Teador",
"Tedda",
"Tedder",
"Teddi",
"Teddie",
"Teddy",
"Tedi",
"Tedie",
"Teeter",
"Teodoor",
"Teodor",
"Terti",
"Theda",
"Theodor",
"Theodore",
"Theta",
"Thilda",
"Thordia",
"Tilda",
"Tildi",
"Tildie",
"Tildy",
"Tita",
"Tito",
"Tjader",
"Toddie",
"Toddy",
"Torto",
"Tuddor",
"Tudor",
"Turtle",
"Tuttle",
"Tutto"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomWords() throws EncoderException {
this.checkEncodingVariations("RTA1111111", new String[]{"rather", "ready", "writer"});
this.checkEncoding("SSA1111111", "social");
this.checkEncodingVariations("APA1111111", new String[]{"able", "appear"});
}
public void testEndMb() throws EncoderException {
String[][] data = {{"mb", "M111111111"}, {"mbmb", "MPM1111111"}};
this.checkEncodings(data);
}
// Caverphone Revisited
public void testIsCaverphoneEquals() {
Caverphone caverphone = new Caverphone();
Assert.assertFalse("Caverphone encodings should not be equal", caverphone.isCaverphoneEqual("Peter", "Stevenson"));
Assert.assertTrue("Caverphone encodings should be equal", caverphone.isCaverphoneEqual("Peter", "Peady"));
}
public void testSpecificationExamples() throws EncoderException {
String[][] data = {
{"Peter", "PTA1111111"},
{"ready", "RTA1111111"},
{"social", "SSA1111111"},
{"able", "APA1111111"},
{"Tedder", "TTA1111111"},
{"Karleen", "KLN1111111"},
{"Dyun", "TN11111111"}};
this.checkEncodings(data);
}
} | // You are a professional Java test case writer, please create a test case named `testEndMb` for the issue `Codec-CODEC-117`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-117
//
// ## Issue-Title:
// Caverphone encodes names starting and ending with "mb" incorrectly.
//
// ## Issue-Description:
//
// Caverphone encode names starting and ending with "mb" incorrectly.
//
//
// According to the spec:
//
// "If the name ends with mb make it m2".
//
//
// This has been coded as:
//
// "If the name *starts* with mb make it m2".
//
//
//
//
//
public void testEndMb() throws EncoderException {
| 335 | 10 | 332 | src/test/org/apache/commons/codec/language/CaverphoneTest.java | src/test | ```markdown
## Issue-ID: Codec-CODEC-117
## Issue-Title:
Caverphone encodes names starting and ending with "mb" incorrectly.
## Issue-Description:
Caverphone encode names starting and ending with "mb" incorrectly.
According to the spec:
"If the name ends with mb make it m2".
This has been coded as:
"If the name *starts* with mb make it m2".
```
You are a professional Java test case writer, please create a test case named `testEndMb` for the issue `Codec-CODEC-117`, utilizing the provided issue report information and the following function signature.
```java
public void testEndMb() throws EncoderException {
```
| 332 | [
"org.apache.commons.codec.language.Caverphone"
] | 57e35541ebaebcf95bc4f523bfaa41aec18ea4c87366e4a7507bf84639084f4a | public void testEndMb() throws EncoderException | // You are a professional Java test case writer, please create a test case named `testEndMb` for the issue `Codec-CODEC-117`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-117
//
// ## Issue-Title:
// Caverphone encodes names starting and ending with "mb" incorrectly.
//
// ## Issue-Description:
//
// Caverphone encode names starting and ending with "mb" incorrectly.
//
//
// According to the spec:
//
// "If the name ends with mb make it m2".
//
//
// This has been coded as:
//
// "If the name *starts* with mb make it m2".
//
//
//
//
//
| Codec | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.codec.language;
import junit.framework.Assert;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringEncoder;
import org.apache.commons.codec.StringEncoderAbstractTest;
/**
* @author Apache Software Foundation
* @version $Id$
*/
public class CaverphoneTest extends StringEncoderAbstractTest {
public CaverphoneTest(String name) {
super(name);
}
protected StringEncoder createStringEncoder() {
return new Caverphone();
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* AT11111111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedCommonCodeAT11111111() throws EncoderException {
this.checkEncodingVariations("AT11111111", new String[]{
"add",
"aid",
"at",
"art",
"eat",
"earth",
"head",
"hit",
"hot",
"hold",
"hard",
"heart",
"it",
"out",
"old"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedExamples() throws EncoderException {
String[][] data = {{"Stevenson", "STFNSN1111"}, {"Peter", "PTA1111111"}};
this.checkEncodings(data);
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomNameKLN1111111() throws EncoderException {
this.checkEncodingVariations("KLN1111111", new String[]{
"Cailean",
"Calan",
"Calen",
"Callahan",
"Callan",
"Callean",
"Carleen",
"Carlen",
"Carlene",
"Carlin",
"Carline",
"Carlyn",
"Carlynn",
"Carlynne",
"Charlean",
"Charleen",
"Charlene",
"Charline",
"Cherlyn",
"Chirlin",
"Clein",
"Cleon",
"Cline",
"Cohleen",
"Colan",
"Coleen",
"Colene",
"Colin",
"Colleen",
"Collen",
"Collin",
"Colline",
"Colon",
"Cullan",
"Cullen",
"Cullin",
"Gaelan",
"Galan",
"Galen",
"Garlan",
"Garlen",
"Gaulin",
"Gayleen",
"Gaylene",
"Giliane",
"Gillan",
"Gillian",
"Glen",
"Glenn",
"Glyn",
"Glynn",
"Gollin",
"Gorlin",
"Kalin",
"Karlan",
"Karleen",
"Karlen",
"Karlene",
"Karlin",
"Karlyn",
"Kaylyn",
"Keelin",
"Kellen",
"Kellene",
"Kellyann",
"Kellyn",
"Khalin",
"Kilan",
"Kilian",
"Killen",
"Killian",
"Killion",
"Klein",
"Kleon",
"Kline",
"Koerlin",
"Kylen",
"Kylynn",
"Quillan",
"Quillon",
"Qulllon",
"Xylon"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomNameTN11111111() throws EncoderException {
this.checkEncodingVariations("TN11111111", new String[]{
"Dan",
"Dane",
"Dann",
"Darn",
"Daune",
"Dawn",
"Ddene",
"Dean",
"Deane",
"Deanne",
"DeeAnn",
"Deeann",
"Deeanne",
"Deeyn",
"Den",
"Dene",
"Denn",
"Deonne",
"Diahann",
"Dian",
"Diane",
"Diann",
"Dianne",
"Diannne",
"Dine",
"Dion",
"Dione",
"Dionne",
"Doane",
"Doehne",
"Don",
"Donn",
"Doone",
"Dorn",
"Down",
"Downe",
"Duane",
"Dun",
"Dunn",
"Duyne",
"Dyan",
"Dyane",
"Dyann",
"Dyanne",
"Dyun",
"Tan",
"Tann",
"Teahan",
"Ten",
"Tenn",
"Terhune",
"Thain",
"Thaine",
"Thane",
"Thanh",
"Thayne",
"Theone",
"Thin",
"Thorn",
"Thorne",
"Thun",
"Thynne",
"Tien",
"Tine",
"Tjon",
"Town",
"Towne",
"Turne",
"Tyne"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomNameTTA1111111() throws EncoderException {
this.checkEncodingVariations("TTA1111111", new String[]{
"Darda",
"Datha",
"Dedie",
"Deedee",
"Deerdre",
"Deidre",
"Deirdre",
"Detta",
"Didi",
"Didier",
"Dido",
"Dierdre",
"Dieter",
"Dita",
"Ditter",
"Dodi",
"Dodie",
"Dody",
"Doherty",
"Dorthea",
"Dorthy",
"Doti",
"Dotti",
"Dottie",
"Dotty",
"Doty",
"Doughty",
"Douty",
"Dowdell",
"Duthie",
"Tada",
"Taddeo",
"Tadeo",
"Tadio",
"Tati",
"Teador",
"Tedda",
"Tedder",
"Teddi",
"Teddie",
"Teddy",
"Tedi",
"Tedie",
"Teeter",
"Teodoor",
"Teodor",
"Terti",
"Theda",
"Theodor",
"Theodore",
"Theta",
"Thilda",
"Thordia",
"Tilda",
"Tildi",
"Tildie",
"Tildy",
"Tita",
"Tito",
"Tjader",
"Toddie",
"Toddy",
"Torto",
"Tuddor",
"Tudor",
"Turtle",
"Tuttle",
"Tutto"});
}
/**
* See http://caversham.otago.ac.nz/files/working/ctp150804.pdf
*
* @throws EncoderException
*/
public void testDavidHoodRevisitedRandomWords() throws EncoderException {
this.checkEncodingVariations("RTA1111111", new String[]{"rather", "ready", "writer"});
this.checkEncoding("SSA1111111", "social");
this.checkEncodingVariations("APA1111111", new String[]{"able", "appear"});
}
public void testEndMb() throws EncoderException {
String[][] data = {{"mb", "M111111111"}, {"mbmb", "MPM1111111"}};
this.checkEncodings(data);
}
// Caverphone Revisited
public void testIsCaverphoneEquals() {
Caverphone caverphone = new Caverphone();
Assert.assertFalse("Caverphone encodings should not be equal", caverphone.isCaverphoneEqual("Peter", "Stevenson"));
Assert.assertTrue("Caverphone encodings should be equal", caverphone.isCaverphoneEqual("Peter", "Peady"));
}
public void testSpecificationExamples() throws EncoderException {
String[][] data = {
{"Peter", "PTA1111111"},
{"ready", "RTA1111111"},
{"social", "SSA1111111"},
{"able", "APA1111111"},
{"Tedder", "TTA1111111"},
{"Karleen", "KLN1111111"},
{"Dyun", "TN11111111"}};
this.checkEncodings(data);
}
} |
||
public void testWithEmptyStringAsNullObject1533() throws Exception
{
ObjectMapper mapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
AsPropertyWrapper wrapper = mapper.readValue("{ \"value\": \"\" }", AsPropertyWrapper.class);
assertNull(wrapper.value);
} | com.fasterxml.jackson.databind.jsontype.TestPolymorphicWithDefaultImpl::testWithEmptyStringAsNullObject1533 | src/test/java/com/fasterxml/jackson/databind/jsontype/TestPolymorphicWithDefaultImpl.java | 275 | src/test/java/com/fasterxml/jackson/databind/jsontype/TestPolymorphicWithDefaultImpl.java | testWithEmptyStringAsNullObject1533 | package com.fasterxml.jackson.databind.jsontype;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.NoClass;
/**
* Unit tests related to specialized handling of "default implementation"
* ({@link JsonTypeInfo#defaultImpl}), as well as related
* cases that allow non-default settings (such as missing type id).
*/
public class TestPolymorphicWithDefaultImpl extends BaseMapTest
{
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = LegacyInter.class)
@JsonSubTypes(value = {@JsonSubTypes.Type(name = "mine", value = MyInter.class)})
public static interface Inter { }
public static class MyInter implements Inter {
@JsonProperty("blah") public List<String> blah;
}
public static class LegacyInter extends MyInter
{
@JsonCreator
LegacyInter(Object obj)
{
if (obj instanceof List) {
blah = new ArrayList<String>();
for (Object o : (List<?>) obj) {
blah.add(o.toString());
}
}
else if (obj instanceof String) {
blah = Arrays.asList(((String) obj).split(","));
}
else {
throw new IllegalArgumentException("Unknown type: " + obj.getClass());
}
}
}
/**
* Note: <code>NoClass</code> here has special meaning, of mapping invalid
* types into null instances.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = NoClass.class)
public static class DefaultWithNoClass { }
/**
* Also another variant to verify that from 2.5 on, can use non-deprecated
* value for the same.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = Void.class)
public static class DefaultWithVoidAsDefault { }
// and then one with no defaultImpl nor listed subtypes
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
abstract static class MysteryPolymorphic { }
// [databind#511] types
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes(@JsonSubTypes.Type(name="sub1", value = BadSub1.class))
public static class BadItem {}
public static class BadSub1 extends BadItem {
public String a ;
}
public static class Good {
public List<GoodItem> many;
}
public static class Bad {
public List<BadItem> many;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@JsonSubTypes.Type(name="sub1", value = GoodSub1.class),
@JsonSubTypes.Type(name="sub2", value = GoodSub2.class) })
public static class GoodItem {}
public static class GoodSub1 extends GoodItem {
public String a;
}
public static class GoodSub2 extends GoodItem {
public String b;
}
// for [databind#656]
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT, defaultImpl=ImplFor656.class)
static abstract class BaseFor656 { }
static class ImplFor656 extends BaseFor656 {
public int a;
}
static class CallRecord {
public float version;
public String application;
public Item item;
public Item item2;
public CallRecord() {}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({@JsonSubTypes.Type(value = Event.class, name = "event")})
@JsonIgnoreProperties(ignoreUnknown=true)
public interface Item { }
static class Event implements Item {
public String location;
public Event() {}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY,
property = "clazz")
abstract static class BaseClass { }
static class BaseWrapper {
public BaseClass value;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type")
static class AsProperty {
}
static class AsPropertyWrapper {
public AsProperty value;
}
/*
/**********************************************************
/* Unit tests, deserialization
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDeserializationWithObject() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("{\"type\": \"mine\", \"blah\": [\"a\", \"b\", \"c\"]}");
assertTrue(inter instanceof MyInter);
assertFalse(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c"), ((MyInter) inter).blah);
}
public void testDeserializationWithString() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("\"a,b,c,d\"");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArray() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\", \"c\", \"d\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArrayOfSize2() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b"), ((MyInter) inter).blah);
}
// [databind#148]
public void testDefaultAsNoClass() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// same, with 2.5 and Void.class
public void testDefaultAsVoid() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// [databind#148]
public void testBadTypeAsNull() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
Object ob = mapper.readValue("{}", MysteryPolymorphic.class);
assertNull(ob);
ob = mapper.readValue("{ \"whatever\":13}", MysteryPolymorphic.class);
assertNull(ob);
}
// [databind#511]
public void testInvalidTypeId511() throws Exception {
ObjectReader reader = MAPPER.reader().without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES
);
String json = "{\"many\":[{\"sub1\":{\"a\":\"foo\"}},{\"sub2\":{\"b\":\"bar\"}}]}" ;
Good goodResult = reader.forType(Good.class).readValue(json) ;
assertNotNull(goodResult) ;
Bad badResult = reader.forType(Bad.class).readValue(json);
assertNotNull(badResult);
}
// [databind#656]
public void testDefaultImplWithObjectWrapper() throws Exception
{
BaseFor656 value = MAPPER.readValue(aposToQuotes("{'foobar':{'a':3}}"), BaseFor656.class);
assertNotNull(value);
assertEquals(ImplFor656.class, value.getClass());
assertEquals(3, ((ImplFor656) value).a);
}
public void testUnknownTypeIDRecovery() throws Exception
{
ObjectReader reader = MAPPER.readerFor(CallRecord.class).without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
String json = aposToQuotes("{'version':0.0,'application':'123',"
+"'item':{'type':'xevent','location':'location1'},"
+"'item2':{'type':'event','location':'location1'}}");
// can't read item2 - which is valid
CallRecord r = reader.readValue(json);
assertNull(r.item);
assertNotNull(r.item2);
json = aposToQuotes("{'item':{'type':'xevent','location':'location1'}, 'version':0.0,'application':'123'}");
CallRecord r3 = reader.readValue(json);
assertNull(r3.item);
assertEquals("123", r3.application);
}
public void testUnknownClassAsSubtype() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
BaseWrapper w = mapper.readValue(aposToQuotes
("{'value':{'clazz':'com.foobar.Nothing'}}'"),
BaseWrapper.class);
assertNotNull(w);
assertNull(w.value);
}
public void testWithoutEmptyStringAsNullObject1533() throws Exception
{
ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
try {
mapper.readValue("{ \"value\": \"\" }", AsPropertyWrapper.class);
fail("Expected " + JsonMappingException.class);
} catch (JsonMappingException e) {
// expected
}
}
public void testWithEmptyStringAsNullObject1533() throws Exception
{
ObjectMapper mapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
AsPropertyWrapper wrapper = mapper.readValue("{ \"value\": \"\" }", AsPropertyWrapper.class);
assertNull(wrapper.value);
}
/*
/**********************************************************
/* Unit tests, serialization
/**********************************************************
*/
/*
public void testDontWriteIfDefaultImpl() throws Exception {
String json = MAPPER.writeValueAsString(new MyInter());
assertEquals("{\"blah\":null}", json);
}
*/
} | // You are a professional Java test case writer, please create a test case named `testWithEmptyStringAsNullObject1533` for the issue `JacksonDatabind-1533`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1533
//
// ## Issue-Title:
// AsPropertyTypeDeserializer ignores DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
//
// ## Issue-Description:
// The `AsPropertyTypeDeserializer` implementation does not respect the `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` feature. When deserializing an empty String it throws `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` instead of creating a null Object.
//
//
//
//
public void testWithEmptyStringAsNullObject1533() throws Exception {
| 275 | 74 | 270 | src/test/java/com/fasterxml/jackson/databind/jsontype/TestPolymorphicWithDefaultImpl.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1533
## Issue-Title:
AsPropertyTypeDeserializer ignores DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
## Issue-Description:
The `AsPropertyTypeDeserializer` implementation does not respect the `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` feature. When deserializing an empty String it throws `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` instead of creating a null Object.
```
You are a professional Java test case writer, please create a test case named `testWithEmptyStringAsNullObject1533` for the issue `JacksonDatabind-1533`, utilizing the provided issue report information and the following function signature.
```java
public void testWithEmptyStringAsNullObject1533() throws Exception {
```
| 270 | [
"com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer"
] | 589a5076ccce122a7f12dbdff4e2fd70924da2e35b596fd76f11d42cfb2ca7b0 | public void testWithEmptyStringAsNullObject1533() throws Exception
| // You are a professional Java test case writer, please create a test case named `testWithEmptyStringAsNullObject1533` for the issue `JacksonDatabind-1533`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1533
//
// ## Issue-Title:
// AsPropertyTypeDeserializer ignores DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
//
// ## Issue-Description:
// The `AsPropertyTypeDeserializer` implementation does not respect the `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` feature. When deserializing an empty String it throws `DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT` instead of creating a null Object.
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.jsontype;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.NoClass;
/**
* Unit tests related to specialized handling of "default implementation"
* ({@link JsonTypeInfo#defaultImpl}), as well as related
* cases that allow non-default settings (such as missing type id).
*/
public class TestPolymorphicWithDefaultImpl extends BaseMapTest
{
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = LegacyInter.class)
@JsonSubTypes(value = {@JsonSubTypes.Type(name = "mine", value = MyInter.class)})
public static interface Inter { }
public static class MyInter implements Inter {
@JsonProperty("blah") public List<String> blah;
}
public static class LegacyInter extends MyInter
{
@JsonCreator
LegacyInter(Object obj)
{
if (obj instanceof List) {
blah = new ArrayList<String>();
for (Object o : (List<?>) obj) {
blah.add(o.toString());
}
}
else if (obj instanceof String) {
blah = Arrays.asList(((String) obj).split(","));
}
else {
throw new IllegalArgumentException("Unknown type: " + obj.getClass());
}
}
}
/**
* Note: <code>NoClass</code> here has special meaning, of mapping invalid
* types into null instances.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = NoClass.class)
public static class DefaultWithNoClass { }
/**
* Also another variant to verify that from 2.5 on, can use non-deprecated
* value for the same.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = Void.class)
public static class DefaultWithVoidAsDefault { }
// and then one with no defaultImpl nor listed subtypes
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
abstract static class MysteryPolymorphic { }
// [databind#511] types
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes(@JsonSubTypes.Type(name="sub1", value = BadSub1.class))
public static class BadItem {}
public static class BadSub1 extends BadItem {
public String a ;
}
public static class Good {
public List<GoodItem> many;
}
public static class Bad {
public List<BadItem> many;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@JsonSubTypes.Type(name="sub1", value = GoodSub1.class),
@JsonSubTypes.Type(name="sub2", value = GoodSub2.class) })
public static class GoodItem {}
public static class GoodSub1 extends GoodItem {
public String a;
}
public static class GoodSub2 extends GoodItem {
public String b;
}
// for [databind#656]
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT, defaultImpl=ImplFor656.class)
static abstract class BaseFor656 { }
static class ImplFor656 extends BaseFor656 {
public int a;
}
static class CallRecord {
public float version;
public String application;
public Item item;
public Item item2;
public CallRecord() {}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({@JsonSubTypes.Type(value = Event.class, name = "event")})
@JsonIgnoreProperties(ignoreUnknown=true)
public interface Item { }
static class Event implements Item {
public String location;
public Event() {}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY,
property = "clazz")
abstract static class BaseClass { }
static class BaseWrapper {
public BaseClass value;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type")
static class AsProperty {
}
static class AsPropertyWrapper {
public AsProperty value;
}
/*
/**********************************************************
/* Unit tests, deserialization
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDeserializationWithObject() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("{\"type\": \"mine\", \"blah\": [\"a\", \"b\", \"c\"]}");
assertTrue(inter instanceof MyInter);
assertFalse(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c"), ((MyInter) inter).blah);
}
public void testDeserializationWithString() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("\"a,b,c,d\"");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArray() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\", \"c\", \"d\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArrayOfSize2() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b"), ((MyInter) inter).blah);
}
// [databind#148]
public void testDefaultAsNoClass() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// same, with 2.5 and Void.class
public void testDefaultAsVoid() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// [databind#148]
public void testBadTypeAsNull() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
Object ob = mapper.readValue("{}", MysteryPolymorphic.class);
assertNull(ob);
ob = mapper.readValue("{ \"whatever\":13}", MysteryPolymorphic.class);
assertNull(ob);
}
// [databind#511]
public void testInvalidTypeId511() throws Exception {
ObjectReader reader = MAPPER.reader().without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES
);
String json = "{\"many\":[{\"sub1\":{\"a\":\"foo\"}},{\"sub2\":{\"b\":\"bar\"}}]}" ;
Good goodResult = reader.forType(Good.class).readValue(json) ;
assertNotNull(goodResult) ;
Bad badResult = reader.forType(Bad.class).readValue(json);
assertNotNull(badResult);
}
// [databind#656]
public void testDefaultImplWithObjectWrapper() throws Exception
{
BaseFor656 value = MAPPER.readValue(aposToQuotes("{'foobar':{'a':3}}"), BaseFor656.class);
assertNotNull(value);
assertEquals(ImplFor656.class, value.getClass());
assertEquals(3, ((ImplFor656) value).a);
}
public void testUnknownTypeIDRecovery() throws Exception
{
ObjectReader reader = MAPPER.readerFor(CallRecord.class).without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
String json = aposToQuotes("{'version':0.0,'application':'123',"
+"'item':{'type':'xevent','location':'location1'},"
+"'item2':{'type':'event','location':'location1'}}");
// can't read item2 - which is valid
CallRecord r = reader.readValue(json);
assertNull(r.item);
assertNotNull(r.item2);
json = aposToQuotes("{'item':{'type':'xevent','location':'location1'}, 'version':0.0,'application':'123'}");
CallRecord r3 = reader.readValue(json);
assertNull(r3.item);
assertEquals("123", r3.application);
}
public void testUnknownClassAsSubtype() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
BaseWrapper w = mapper.readValue(aposToQuotes
("{'value':{'clazz':'com.foobar.Nothing'}}'"),
BaseWrapper.class);
assertNotNull(w);
assertNull(w.value);
}
public void testWithoutEmptyStringAsNullObject1533() throws Exception
{
ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
try {
mapper.readValue("{ \"value\": \"\" }", AsPropertyWrapper.class);
fail("Expected " + JsonMappingException.class);
} catch (JsonMappingException e) {
// expected
}
}
public void testWithEmptyStringAsNullObject1533() throws Exception
{
ObjectMapper mapper = new ObjectMapper().enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
AsPropertyWrapper wrapper = mapper.readValue("{ \"value\": \"\" }", AsPropertyWrapper.class);
assertNull(wrapper.value);
}
/*
/**********************************************************
/* Unit tests, serialization
/**********************************************************
*/
/*
public void testDontWriteIfDefaultImpl() throws Exception {
String json = MAPPER.writeValueAsString(new MyInter());
assertEquals("{\"blah\":null}", json);
}
*/
} |
||
public void testGlobalCatch() throws Exception {
testSame(
"try {" +
" throw Error();" +
"} catch (e) {" +
" console.log(e.name)" +
"}");
} | com.google.javascript.jscomp.CheckGlobalNamesTest::testGlobalCatch | test/com/google/javascript/jscomp/CheckGlobalNamesTest.java | 346 | test/com/google/javascript/jscomp/CheckGlobalNamesTest.java | testGlobalCatch | /*
* 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;
import static com.google.javascript.jscomp.CheckGlobalNames.NAME_DEFINED_LATE_WARNING;
import static com.google.javascript.jscomp.CheckGlobalNames.UNDEFINED_NAME_WARNING;
import static com.google.javascript.jscomp.CheckGlobalNames.STRICT_MODULE_DEP_QNAME;
import com.google.javascript.rhino.Node;
/**
* Tests for {@code CheckGlobalNames.java}.
*
* @author nicksantos@google.com (Nick Santos)
*/
public class CheckGlobalNamesTest extends CompilerTestCase {
private boolean injectNamespace = false;
public CheckGlobalNamesTest() {
super("function alert() {}" +
"/** @constructor */ function Object(){}" +
"Object.prototype.hasOwnProperty = function() {};" +
"/** @constructor */ function Function(){}" +
"Function.prototype.call = function() {};");
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
final CheckGlobalNames checkGlobalNames = new CheckGlobalNames(
compiler, CheckLevel.WARNING);
if (injectNamespace) {
return new CompilerPass() {
@Override
public void process(Node externs, Node js) {
checkGlobalNames.injectNamespace(
new GlobalNamespace(compiler, externs, js))
.process(externs, js);
}
};
} else {
return checkGlobalNames;
}
}
@Override
public void setUp() {
injectNamespace = false;
STRICT_MODULE_DEP_QNAME.level = CheckLevel.WARNING;
}
private static final String GET_NAMES =
"var a = {get d() {return 1}}; a.b = 3; a.c = {get e() {return 5}};";
private static final String SET_NAMES =
"var a = {set d(x) {}}; a.b = 3; a.c = {set e(y) {}};";
private static final String NAMES = "var a = {d: 1}; a.b = 3; a.c = {e: 5};";
public void testRefToDefinedProperties1() {
testSame(NAMES + "alert(a.b); alert(a.c.e);");
testSame(GET_NAMES + "alert(a.b); alert(a.c.e);");
testSame(SET_NAMES + "alert(a.b); alert(a.c.e);");
}
public void testRefToDefinedProperties2() {
testSame(NAMES + "a.x={}; alert(a.c);");
testSame(GET_NAMES + "a.x={}; alert(a.c);");
testSame(SET_NAMES + "a.x={}; alert(a.c);");
}
public void testRefToDefinedProperties3() {
testSame(NAMES + "alert(a.d);");
testSame(GET_NAMES + "alert(a.d);");
testSame(SET_NAMES + "alert(a.d);");
}
public void testRefToMethod1() {
testSame("function foo() {}; foo.call();");
}
public void testRefToMethod2() {
testSame("function foo() {}; foo.call.call();");
}
public void testCallUndefinedFunctionGivesNoWaring() {
// We don't bother checking undeclared variables--there's another
// pass that does this already.
testSame("foo();");
}
public void testRefToPropertyOfAliasedName() {
// this is OK, because "a" was aliased
testSame(NAMES + "alert(a); alert(a.x);");
}
public void testRefToUndefinedProperty1() {
testSame(NAMES + "alert(a.x);", UNDEFINED_NAME_WARNING);
}
public void testRefToUndefinedProperty2() {
testSame(NAMES + "a.x();", UNDEFINED_NAME_WARNING);
}
public void testRefToUndefinedProperty3() {
testSame(NAMES + "alert(a.c.x);", UNDEFINED_NAME_WARNING);
testSame(GET_NAMES + "alert(a.c.x);", UNDEFINED_NAME_WARNING);
testSame(SET_NAMES + "alert(a.c.x);", UNDEFINED_NAME_WARNING);
}
public void testRefToUndefinedProperty4() {
testSame(NAMES + "alert(a.d.x);");
testSame(GET_NAMES + "alert(a.d.x);");
testSame(SET_NAMES + "alert(a.d.x);");
}
public void testRefToDescendantOfUndefinedProperty1() {
testSame(NAMES + "var c = a.x.b;", UNDEFINED_NAME_WARNING);
}
public void testRefToDescendantOfUndefinedProperty2() {
testSame(NAMES + "a.x.b();", UNDEFINED_NAME_WARNING);
}
public void testRefToDescendantOfUndefinedProperty3() {
testSame(NAMES + "a.x.b = 3;", UNDEFINED_NAME_WARNING);
}
public void testUndefinedPrototypeMethodRefGivesNoWarning() {
testSame("function Foo() {} var a = new Foo(); a.bar();");
}
public void testComplexPropAssignGivesNoWarning() {
testSame("var a = {}; var b = a.b = 3;");
}
public void testTypedefGivesNoWarning() {
testSame("var a = {}; /** @typedef {number} */ a.b;");
}
public void testRefToDescendantOfUndefinedPropertyGivesCorrectWarning() {
testSame("", NAMES + "a.x.b = 3;", UNDEFINED_NAME_WARNING,
UNDEFINED_NAME_WARNING.format("a.x"));
}
public void testNamespaceInjection() {
injectNamespace = true;
testSame(NAMES + "var c = a.x.b;", UNDEFINED_NAME_WARNING);
}
public void testSuppressionOfUndefinedNamesWarning() {
testSame(new String[] {
NAMES +
"/** @constructor */ function Foo() { };" +
"/** @suppress {undefinedNames} */" +
"Foo.prototype.bar = function() {" +
" alert(a.x);" +
" alert(a.x.b());" +
" a.x();" +
" var c = a.x.b;" +
" var c = a.x.b();" +
" a.x.b();" +
" a.x.b = 3;" +
"};",
});
}
public void testNoWarningForSimpleVarModuleDep1() {
testSame(createModuleChain(
NAMES,
"var c = a;"
));
}
public void testNoWarningForSimpleVarModuleDep2() {
testSame(createModuleChain(
"var c = a;",
NAMES
));
}
public void testNoWarningForGoodModuleDep1() {
testSame(createModuleChain(
NAMES,
"var c = a.b;"
));
}
public void testBadModuleDep1() {
testSame(createModuleChain(
"var c = a.b;",
NAMES
), STRICT_MODULE_DEP_QNAME);
}
public void testBadModuleDep2() {
testSame(createModuleStar(
NAMES,
"a.xxx = 3;",
"var x = a.xxx;"
), STRICT_MODULE_DEP_QNAME);
}
public void testSelfModuleDep() {
testSame(createModuleChain(
NAMES + "var c = a.b;"
));
}
public void testUndefinedModuleDep1() {
testSame(createModuleChain(
"var c = a.xxx;",
NAMES
), UNDEFINED_NAME_WARNING);
}
public void testLateDefinedName1() {
testSame("x.y = {}; var x = {};", NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName2() {
testSame("var x = {}; x.y.z = {}; x.y = {};", NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName3() {
testSame("var x = {}; x.y.z = {}; x.y = {z: {}};",
NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName4() {
testSame("var x = {}; x.y.z.bar = {}; x.y = {z: {}};",
NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName5() {
testSame("var x = {}; /** @typedef {number} */ x.y.z; x.y = {};",
NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName6() {
testSame(
"var x = {}; x.y.prototype.z = 3;" +
"/** @constructor */ x.y = function() {};",
NAME_DEFINED_LATE_WARNING);
}
public void testOkLateDefinedName1() {
testSame("function f() { x.y = {}; } var x = {};");
}
public void testOkLateDefinedName2() {
testSame("var x = {}; function f() { x.y.z = {}; } x.y = {};");
}
public void testPathologicalCaseThatsOkAnyway() {
testSame(
"var x = {};" +
"switch (x) { " +
" default: x.y.z = {}; " +
" case (x.y = {}): break;" +
"}", NAME_DEFINED_LATE_WARNING);
}
public void testOkGlobalDeclExpr() {
testSame("var x = {}; /** @type {string} */ x.foo;");
}
public void testBadInterfacePropRef() {
testSame(
"/** @interface */ function F() {}" +
"F.bar();",
UNDEFINED_NAME_WARNING);
}
public void testInterfaceFunctionPropRef() {
testSame(
"/** @interface */ function F() {}" +
"F.call(); F.hasOwnProperty('z');");
}
public void testObjectPrototypeProperties() {
testSame("var x = {}; var y = x.hasOwnProperty('z');");
}
public void testCustomObjectPrototypeProperties() {
testSame("Object.prototype.seal = function() {};" +
"var x = {}; x.seal();");
}
public void testFunctionPrototypeProperties() {
testSame("var x = {}; var y = x.hasOwnProperty('z');");
}
public void testIndirectlyDeclaredProperties() {
testSame(
"Function.prototype.inherits = function(ctor) {" +
" this.superClass_ = ctor;" +
"};" +
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor */ function SubFoo() {}" +
"SubFoo.inherits(Foo);" +
"SubFoo.superClass_.bar();");
}
public void testGoogInheritsAlias() {
testSame(
"Function.prototype.inherits = function(ctor) {" +
" this.superClass_ = ctor;" +
"};" +
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor */ function SubFoo() {}" +
"SubFoo.inherits(Foo);" +
"SubFoo.superClass_.bar();");
}
public void testGoogInheritsAlias2() {
testSame(
CompilerTypeTestCase.CLOSURE_DEFS +
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor */ function SubFoo() {}" +
"goog.inherits(SubFoo, Foo);" +
"SubFoo.superClazz();",
UNDEFINED_NAME_WARNING);
}
public void testGlobalCatch() throws Exception {
testSame(
"try {" +
" throw Error();" +
"} catch (e) {" +
" console.log(e.name)" +
"}");
}
} | // You are a professional Java test case writer, please create a test case named `testGlobalCatch` for the issue `Closure-1070`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-1070
//
// ## Issue-Title:
// catch(e) yields JSC_UNDEFINED_NAME warning when e is used in catch in advanced mode
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. set closure for advanced compilation
// 2. compile this:
// // ==ClosureCompiler==
// // @compilation\_level ADVANCED\_OPTIMIZATIONS
// // @output\_file\_name default.js
// // ==/ClosureCompiler==
//
// try {
// var x = 5;
// }
// catch(e) {
// var s = "FAIL" + e.name + ": "+ e.message;
// }
//
// **What is the expected output? What do you see instead?**
// I expect no warning or error for this. Instead I see this:
//
// JSC\_UNREACHABLE\_CODE: unreachable code at line 4 character 0
// catch(e) {
// ^
// JSC\_UNDEFINED\_NAME: e is never defined at line 5 character 17
// var s = "FAIL" + e.name + ": "+ e.message;
// ^
// JSC\_UNDEFINED\_NAME: e is never defined at line 5 character 32
// var s = "FAIL" + e.name + ": "+ e.message;
// ^
// In my case I'm especially complaining about the JSC\_UNDEFINED\_NAME warning... Also it seems the unreachable complaint isn't right, but i'm not sure.
//
// **What version of the product are you using? On what operating system?**
// I'm using this url: http://closure-compiler.appspot.com/home
// using chrome browser on windows: Version 28.0.1500.95 m
// ... but this is a server side error from what I see...
//
// **Please provide any additional information below.**
//
//
public void testGlobalCatch() throws Exception {
| 346 | 119 | 339 | test/com/google/javascript/jscomp/CheckGlobalNamesTest.java | test | ```markdown
## Issue-ID: Closure-1070
## Issue-Title:
catch(e) yields JSC_UNDEFINED_NAME warning when e is used in catch in advanced mode
## Issue-Description:
**What steps will reproduce the problem?**
1. set closure for advanced compilation
2. compile this:
// ==ClosureCompiler==
// @compilation\_level ADVANCED\_OPTIMIZATIONS
// @output\_file\_name default.js
// ==/ClosureCompiler==
try {
var x = 5;
}
catch(e) {
var s = "FAIL" + e.name + ": "+ e.message;
}
**What is the expected output? What do you see instead?**
I expect no warning or error for this. Instead I see this:
JSC\_UNREACHABLE\_CODE: unreachable code at line 4 character 0
catch(e) {
^
JSC\_UNDEFINED\_NAME: e is never defined at line 5 character 17
var s = "FAIL" + e.name + ": "+ e.message;
^
JSC\_UNDEFINED\_NAME: e is never defined at line 5 character 32
var s = "FAIL" + e.name + ": "+ e.message;
^
In my case I'm especially complaining about the JSC\_UNDEFINED\_NAME warning... Also it seems the unreachable complaint isn't right, but i'm not sure.
**What version of the product are you using? On what operating system?**
I'm using this url: http://closure-compiler.appspot.com/home
using chrome browser on windows: Version 28.0.1500.95 m
... but this is a server side error from what I see...
**Please provide any additional information below.**
```
You are a professional Java test case writer, please create a test case named `testGlobalCatch` for the issue `Closure-1070`, utilizing the provided issue report information and the following function signature.
```java
public void testGlobalCatch() throws Exception {
```
| 339 | [
"com.google.javascript.jscomp.GlobalNamespace"
] | 590497092ae462bd85c1eb327ef0ba90e4f3f80f4ee994b8389a8f72ea5272f6 | public void testGlobalCatch() throws Exception | // You are a professional Java test case writer, please create a test case named `testGlobalCatch` for the issue `Closure-1070`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-1070
//
// ## Issue-Title:
// catch(e) yields JSC_UNDEFINED_NAME warning when e is used in catch in advanced mode
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. set closure for advanced compilation
// 2. compile this:
// // ==ClosureCompiler==
// // @compilation\_level ADVANCED\_OPTIMIZATIONS
// // @output\_file\_name default.js
// // ==/ClosureCompiler==
//
// try {
// var x = 5;
// }
// catch(e) {
// var s = "FAIL" + e.name + ": "+ e.message;
// }
//
// **What is the expected output? What do you see instead?**
// I expect no warning or error for this. Instead I see this:
//
// JSC\_UNREACHABLE\_CODE: unreachable code at line 4 character 0
// catch(e) {
// ^
// JSC\_UNDEFINED\_NAME: e is never defined at line 5 character 17
// var s = "FAIL" + e.name + ": "+ e.message;
// ^
// JSC\_UNDEFINED\_NAME: e is never defined at line 5 character 32
// var s = "FAIL" + e.name + ": "+ e.message;
// ^
// In my case I'm especially complaining about the JSC\_UNDEFINED\_NAME warning... Also it seems the unreachable complaint isn't right, but i'm not sure.
//
// **What version of the product are you using? On what operating system?**
// I'm using this url: http://closure-compiler.appspot.com/home
// using chrome browser on windows: Version 28.0.1500.95 m
// ... but this is a server side error from what I see...
//
// **Please provide any additional information below.**
//
//
| 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;
import static com.google.javascript.jscomp.CheckGlobalNames.NAME_DEFINED_LATE_WARNING;
import static com.google.javascript.jscomp.CheckGlobalNames.UNDEFINED_NAME_WARNING;
import static com.google.javascript.jscomp.CheckGlobalNames.STRICT_MODULE_DEP_QNAME;
import com.google.javascript.rhino.Node;
/**
* Tests for {@code CheckGlobalNames.java}.
*
* @author nicksantos@google.com (Nick Santos)
*/
public class CheckGlobalNamesTest extends CompilerTestCase {
private boolean injectNamespace = false;
public CheckGlobalNamesTest() {
super("function alert() {}" +
"/** @constructor */ function Object(){}" +
"Object.prototype.hasOwnProperty = function() {};" +
"/** @constructor */ function Function(){}" +
"Function.prototype.call = function() {};");
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
final CheckGlobalNames checkGlobalNames = new CheckGlobalNames(
compiler, CheckLevel.WARNING);
if (injectNamespace) {
return new CompilerPass() {
@Override
public void process(Node externs, Node js) {
checkGlobalNames.injectNamespace(
new GlobalNamespace(compiler, externs, js))
.process(externs, js);
}
};
} else {
return checkGlobalNames;
}
}
@Override
public void setUp() {
injectNamespace = false;
STRICT_MODULE_DEP_QNAME.level = CheckLevel.WARNING;
}
private static final String GET_NAMES =
"var a = {get d() {return 1}}; a.b = 3; a.c = {get e() {return 5}};";
private static final String SET_NAMES =
"var a = {set d(x) {}}; a.b = 3; a.c = {set e(y) {}};";
private static final String NAMES = "var a = {d: 1}; a.b = 3; a.c = {e: 5};";
public void testRefToDefinedProperties1() {
testSame(NAMES + "alert(a.b); alert(a.c.e);");
testSame(GET_NAMES + "alert(a.b); alert(a.c.e);");
testSame(SET_NAMES + "alert(a.b); alert(a.c.e);");
}
public void testRefToDefinedProperties2() {
testSame(NAMES + "a.x={}; alert(a.c);");
testSame(GET_NAMES + "a.x={}; alert(a.c);");
testSame(SET_NAMES + "a.x={}; alert(a.c);");
}
public void testRefToDefinedProperties3() {
testSame(NAMES + "alert(a.d);");
testSame(GET_NAMES + "alert(a.d);");
testSame(SET_NAMES + "alert(a.d);");
}
public void testRefToMethod1() {
testSame("function foo() {}; foo.call();");
}
public void testRefToMethod2() {
testSame("function foo() {}; foo.call.call();");
}
public void testCallUndefinedFunctionGivesNoWaring() {
// We don't bother checking undeclared variables--there's another
// pass that does this already.
testSame("foo();");
}
public void testRefToPropertyOfAliasedName() {
// this is OK, because "a" was aliased
testSame(NAMES + "alert(a); alert(a.x);");
}
public void testRefToUndefinedProperty1() {
testSame(NAMES + "alert(a.x);", UNDEFINED_NAME_WARNING);
}
public void testRefToUndefinedProperty2() {
testSame(NAMES + "a.x();", UNDEFINED_NAME_WARNING);
}
public void testRefToUndefinedProperty3() {
testSame(NAMES + "alert(a.c.x);", UNDEFINED_NAME_WARNING);
testSame(GET_NAMES + "alert(a.c.x);", UNDEFINED_NAME_WARNING);
testSame(SET_NAMES + "alert(a.c.x);", UNDEFINED_NAME_WARNING);
}
public void testRefToUndefinedProperty4() {
testSame(NAMES + "alert(a.d.x);");
testSame(GET_NAMES + "alert(a.d.x);");
testSame(SET_NAMES + "alert(a.d.x);");
}
public void testRefToDescendantOfUndefinedProperty1() {
testSame(NAMES + "var c = a.x.b;", UNDEFINED_NAME_WARNING);
}
public void testRefToDescendantOfUndefinedProperty2() {
testSame(NAMES + "a.x.b();", UNDEFINED_NAME_WARNING);
}
public void testRefToDescendantOfUndefinedProperty3() {
testSame(NAMES + "a.x.b = 3;", UNDEFINED_NAME_WARNING);
}
public void testUndefinedPrototypeMethodRefGivesNoWarning() {
testSame("function Foo() {} var a = new Foo(); a.bar();");
}
public void testComplexPropAssignGivesNoWarning() {
testSame("var a = {}; var b = a.b = 3;");
}
public void testTypedefGivesNoWarning() {
testSame("var a = {}; /** @typedef {number} */ a.b;");
}
public void testRefToDescendantOfUndefinedPropertyGivesCorrectWarning() {
testSame("", NAMES + "a.x.b = 3;", UNDEFINED_NAME_WARNING,
UNDEFINED_NAME_WARNING.format("a.x"));
}
public void testNamespaceInjection() {
injectNamespace = true;
testSame(NAMES + "var c = a.x.b;", UNDEFINED_NAME_WARNING);
}
public void testSuppressionOfUndefinedNamesWarning() {
testSame(new String[] {
NAMES +
"/** @constructor */ function Foo() { };" +
"/** @suppress {undefinedNames} */" +
"Foo.prototype.bar = function() {" +
" alert(a.x);" +
" alert(a.x.b());" +
" a.x();" +
" var c = a.x.b;" +
" var c = a.x.b();" +
" a.x.b();" +
" a.x.b = 3;" +
"};",
});
}
public void testNoWarningForSimpleVarModuleDep1() {
testSame(createModuleChain(
NAMES,
"var c = a;"
));
}
public void testNoWarningForSimpleVarModuleDep2() {
testSame(createModuleChain(
"var c = a;",
NAMES
));
}
public void testNoWarningForGoodModuleDep1() {
testSame(createModuleChain(
NAMES,
"var c = a.b;"
));
}
public void testBadModuleDep1() {
testSame(createModuleChain(
"var c = a.b;",
NAMES
), STRICT_MODULE_DEP_QNAME);
}
public void testBadModuleDep2() {
testSame(createModuleStar(
NAMES,
"a.xxx = 3;",
"var x = a.xxx;"
), STRICT_MODULE_DEP_QNAME);
}
public void testSelfModuleDep() {
testSame(createModuleChain(
NAMES + "var c = a.b;"
));
}
public void testUndefinedModuleDep1() {
testSame(createModuleChain(
"var c = a.xxx;",
NAMES
), UNDEFINED_NAME_WARNING);
}
public void testLateDefinedName1() {
testSame("x.y = {}; var x = {};", NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName2() {
testSame("var x = {}; x.y.z = {}; x.y = {};", NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName3() {
testSame("var x = {}; x.y.z = {}; x.y = {z: {}};",
NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName4() {
testSame("var x = {}; x.y.z.bar = {}; x.y = {z: {}};",
NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName5() {
testSame("var x = {}; /** @typedef {number} */ x.y.z; x.y = {};",
NAME_DEFINED_LATE_WARNING);
}
public void testLateDefinedName6() {
testSame(
"var x = {}; x.y.prototype.z = 3;" +
"/** @constructor */ x.y = function() {};",
NAME_DEFINED_LATE_WARNING);
}
public void testOkLateDefinedName1() {
testSame("function f() { x.y = {}; } var x = {};");
}
public void testOkLateDefinedName2() {
testSame("var x = {}; function f() { x.y.z = {}; } x.y = {};");
}
public void testPathologicalCaseThatsOkAnyway() {
testSame(
"var x = {};" +
"switch (x) { " +
" default: x.y.z = {}; " +
" case (x.y = {}): break;" +
"}", NAME_DEFINED_LATE_WARNING);
}
public void testOkGlobalDeclExpr() {
testSame("var x = {}; /** @type {string} */ x.foo;");
}
public void testBadInterfacePropRef() {
testSame(
"/** @interface */ function F() {}" +
"F.bar();",
UNDEFINED_NAME_WARNING);
}
public void testInterfaceFunctionPropRef() {
testSame(
"/** @interface */ function F() {}" +
"F.call(); F.hasOwnProperty('z');");
}
public void testObjectPrototypeProperties() {
testSame("var x = {}; var y = x.hasOwnProperty('z');");
}
public void testCustomObjectPrototypeProperties() {
testSame("Object.prototype.seal = function() {};" +
"var x = {}; x.seal();");
}
public void testFunctionPrototypeProperties() {
testSame("var x = {}; var y = x.hasOwnProperty('z');");
}
public void testIndirectlyDeclaredProperties() {
testSame(
"Function.prototype.inherits = function(ctor) {" +
" this.superClass_ = ctor;" +
"};" +
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor */ function SubFoo() {}" +
"SubFoo.inherits(Foo);" +
"SubFoo.superClass_.bar();");
}
public void testGoogInheritsAlias() {
testSame(
"Function.prototype.inherits = function(ctor) {" +
" this.superClass_ = ctor;" +
"};" +
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor */ function SubFoo() {}" +
"SubFoo.inherits(Foo);" +
"SubFoo.superClass_.bar();");
}
public void testGoogInheritsAlias2() {
testSame(
CompilerTypeTestCase.CLOSURE_DEFS +
"/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor */ function SubFoo() {}" +
"goog.inherits(SubFoo, Foo);" +
"SubFoo.superClazz();",
UNDEFINED_NAME_WARNING);
}
public void testGlobalCatch() throws Exception {
testSame(
"try {" +
" throw Error();" +
"} catch (e) {" +
" console.log(e.name)" +
"}");
}
} |
||
public void testGoogIsArray2() throws Exception {
testClosureFunction("goog.isArray",
ALL_TYPE,
ARRAY_TYPE,
ALL_TYPE);
} | com.google.javascript.jscomp.ClosureReverseAbstractInterpreterTest::testGoogIsArray2 | test/com/google/javascript/jscomp/ClosureReverseAbstractInterpreterTest.java | 209 | test/com/google/javascript/jscomp/ClosureReverseAbstractInterpreterTest.java | testGoogIsArray2 | /*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.testing.Asserts;
public class ClosureReverseAbstractInterpreterTest extends
CompilerTypeTestCase {
public void testGoogIsDef1() throws Exception {
testClosureFunction("goog.isDef",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
VOID_TYPE);
}
public void testGoogIsDef2() throws Exception {
testClosureFunction("goog.isDef",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
NO_TYPE);
}
public void testGoogIsDef3() throws Exception {
testClosureFunction("goog.isDef",
ALL_TYPE,
createUnionType(OBJECT_NUMBER_STRING_BOOLEAN,NULL_TYPE),
VOID_TYPE);
}
public void testGoogIsDef4() throws Exception {
testClosureFunction("goog.isDef",
UNKNOWN_TYPE,
UNKNOWN_TYPE, // TODO(johnlenz): should be CHECKED_UNKNOWN_TYPE
UNKNOWN_TYPE);
}
public void testGoogIsNull1() throws Exception {
testClosureFunction("goog.isNull",
createOptionalType(NUMBER_TYPE),
NO_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsNull2() throws Exception {
testClosureFunction("goog.isNull",
createNullableType(NUMBER_TYPE),
NULL_TYPE,
NUMBER_TYPE);
}
public void testGoogIsNull3() throws Exception {
testClosureFunction("goog.isNull",
ALL_TYPE,
NULL_TYPE,
createUnionType(OBJECT_NUMBER_STRING_BOOLEAN, VOID_TYPE));
}
public void testGoogIsNull4() throws Exception {
testClosureFunction("goog.isNull",
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE); // TODO(johnlenz): this should be CHECK_UNKNOWN
}
public void testGoogIsDefAndNotNull1() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
VOID_TYPE);
}
public void testGoogIsDefAndNotNull2() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
NULL_TYPE);
}
public void testGoogIsDefAndNotNull3() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(createNullableType(NUMBER_TYPE)),
NUMBER_TYPE,
NULL_VOID);
}
public void testGoogIsDefAndNotNull4() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
ALL_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN,
NULL_VOID);
}
public void testGoogIsDefAndNotNull5() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
UNKNOWN_TYPE,
UNKNOWN_TYPE, // TODO(johnlenz): this should be "CHECKED_UNKNOWN"
UNKNOWN_TYPE);
}
public void testGoogIsString1() throws Exception {
testClosureFunction("goog.isString",
createNullableType(STRING_TYPE),
STRING_TYPE,
NULL_TYPE);
}
public void testGoogIsString2() throws Exception {
testClosureFunction("goog.isString",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE));
}
public void testGoogIsBoolean1() throws Exception {
testClosureFunction("goog.isBoolean",
createNullableType(BOOLEAN_TYPE),
BOOLEAN_TYPE,
NULL_TYPE);
}
public void testGoogIsBoolean2() throws Exception {
testClosureFunction("goog.isBoolean",
createUnionType(BOOLEAN_TYPE, STRING_TYPE, NO_OBJECT_TYPE),
BOOLEAN_TYPE,
createUnionType(STRING_TYPE, NO_OBJECT_TYPE));
}
public void testGoogIsBoolean3() throws Exception {
testClosureFunction("goog.isBoolean",
ALL_TYPE,
BOOLEAN_TYPE,
ALL_TYPE); // TODO(johnlenz): this should be:
// {Object|number|string|null|void}
}
public void testGoogIsBoolean4() throws Exception {
testClosureFunction("goog.isBoolean",
UNKNOWN_TYPE,
BOOLEAN_TYPE,
CHECKED_UNKNOWN_TYPE);
}
public void testGoogIsNumber() throws Exception {
testClosureFunction("goog.isNumber",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction() throws Exception {
testClosureFunction("goog.isFunction",
createNullableType(OBJECT_FUNCTION_TYPE),
OBJECT_FUNCTION_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction2() throws Exception {
testClosureFunction("goog.isFunction",
OBJECT_NUMBER_STRING_BOOLEAN,
U2U_CONSTRUCTOR_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN);
}
public void testGoogIsFunction3() throws Exception {
testClosureFunction("goog.isFunction",
createUnionType(U2U_CONSTRUCTOR_TYPE, NUMBER_STRING_BOOLEAN),
U2U_CONSTRUCTOR_TYPE,
NUMBER_STRING_BOOLEAN);
}
public void testGoogIsFunctionOnNull() throws Exception {
testClosureFunction("goog.isFunction",
null,
U2U_CONSTRUCTOR_TYPE,
null);
}
public void testGoogIsArray1() throws Exception {
testClosureFunction("goog.isArray",
OBJECT_TYPE,
ARRAY_TYPE,
OBJECT_TYPE);
}
public void testGoogIsArray2() throws Exception {
testClosureFunction("goog.isArray",
ALL_TYPE,
ARRAY_TYPE,
ALL_TYPE);
}
public void testGoogIsArray3() throws Exception {
testClosureFunction("goog.isArray",
UNKNOWN_TYPE,
CHECKED_UNKNOWN_TYPE,
CHECKED_UNKNOWN_TYPE);
}
public void testGoogIsArray4() throws Exception {
testClosureFunction("goog.isArray",
createUnionType(ARRAY_TYPE, NULL_TYPE),
ARRAY_TYPE,
NULL_TYPE);
}
public void testGoogIsArrayOnNull() throws Exception {
testClosureFunction("goog.isArray",
null,
ARRAY_TYPE,
null);
}
public void testGoogIsObjectOnNull() throws Exception {
testClosureFunction("goog.isObject",
null,
OBJECT_TYPE,
null);
}
public void testGoogIsObject1() throws Exception {
testClosureFunction("goog.isObject",
ALL_TYPE,
NO_OBJECT_TYPE,
createUnionType(NUMBER_STRING_BOOLEAN, NULL_TYPE, VOID_TYPE));
}
public void testGoogIsObject2() throws Exception {
testClosureFunction("goog.isObject",
createUnionType(OBJECT_TYPE, NUMBER_STRING_BOOLEAN),
OBJECT_TYPE,
NUMBER_STRING_BOOLEAN);
}
public void testGoogIsObject3() throws Exception {
testClosureFunction("goog.isObject",
createUnionType(
OBJECT_TYPE, NUMBER_STRING_BOOLEAN, NULL_TYPE, VOID_TYPE),
OBJECT_TYPE,
createUnionType(NUMBER_STRING_BOOLEAN, NULL_TYPE, VOID_TYPE));
}
public void testGoogIsObject4() throws Exception {
testClosureFunction("goog.isObject",
UNKNOWN_TYPE,
NO_OBJECT_TYPE, // ? Should this be CHECKED_UNKNOWN?
CHECKED_UNKNOWN_TYPE);
}
private void testClosureFunction(String function, JSType type,
JSType trueType, JSType falseType) {
// function(a) where a : type
Node n = compiler.parseTestCode("var a; " + function + "(a)");
Node call = n.getLastChild().getLastChild();
Node name = call.getLastChild();
Scope scope = new SyntacticScopeCreator(compiler).createScope(n, null);
FlowScope flowScope = LinkedFlowScope.createEntryLattice(scope);
assertEquals(Token.CALL, call.getType());
assertEquals(Token.NAME, name.getType());
GoogleCodingConvention convention = new GoogleCodingConvention();
flowScope.inferSlotType("a", type);
ClosureReverseAbstractInterpreter rai =
new ClosureReverseAbstractInterpreter(convention, registry);
// trueScope
Asserts.assertTypeEquals(
trueType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, true)
.getSlot("a").getType());
// falseScope
Asserts.assertTypeEquals(
falseType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, false)
.getSlot("a").getType());
}
} | // You are a professional Java test case writer, please create a test case named `testGoogIsArray2` for the issue `Closure-1114`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-1114
//
// ## Issue-Title:
// goog.isArray doesn't hint compiler
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// **1.**
//
// /\*\*
// \* @param {\*} object
// \* @return {\*}
// \*/
// var test = function(object) {
// if (goog.isArray(object)) {
// /\*\* @type {Array} \*/ var x = object;
// return x;
// }
// };
//
// 2. ADVANCED\_OPTIMIZATIONS
//
// **What is the expected output? What do you see instead?**
//
// ERROR - initializing variable
// found : \*
// required: (Array|null)
// /\*\* @type {Array} \*/ var x = object;
// ^
// **What version of the product are you using? On what operating system?**
//
// Closure Compiler (http://code.google.com/closure/compiler)
// Version: v20130411-90-g4e19b4e
// Built on: 2013/06/03 12:07
//
// **Please provide any additional information below.**
//
// goog.is\* is supposed to help the compiler to check which type we're dealing with.
//
//
public void testGoogIsArray2() throws Exception {
| 209 | 111 | 204 | test/com/google/javascript/jscomp/ClosureReverseAbstractInterpreterTest.java | test | ```markdown
## Issue-ID: Closure-1114
## Issue-Title:
goog.isArray doesn't hint compiler
## Issue-Description:
**What steps will reproduce the problem?**
**1.**
/\*\*
\* @param {\*} object
\* @return {\*}
\*/
var test = function(object) {
if (goog.isArray(object)) {
/\*\* @type {Array} \*/ var x = object;
return x;
}
};
2. ADVANCED\_OPTIMIZATIONS
**What is the expected output? What do you see instead?**
ERROR - initializing variable
found : \*
required: (Array|null)
/\*\* @type {Array} \*/ var x = object;
^
**What version of the product are you using? On what operating system?**
Closure Compiler (http://code.google.com/closure/compiler)
Version: v20130411-90-g4e19b4e
Built on: 2013/06/03 12:07
**Please provide any additional information below.**
goog.is\* is supposed to help the compiler to check which type we're dealing with.
```
You are a professional Java test case writer, please create a test case named `testGoogIsArray2` for the issue `Closure-1114`, utilizing the provided issue report information and the following function signature.
```java
public void testGoogIsArray2() throws Exception {
```
| 204 | [
"com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter"
] | 5940b8046addbff658ebf141af34fed3de1ffe4aba47f8184c8cf612f40bddd4 | public void testGoogIsArray2() throws Exception | // You are a professional Java test case writer, please create a test case named `testGoogIsArray2` for the issue `Closure-1114`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-1114
//
// ## Issue-Title:
// goog.isArray doesn't hint compiler
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// **1.**
//
// /\*\*
// \* @param {\*} object
// \* @return {\*}
// \*/
// var test = function(object) {
// if (goog.isArray(object)) {
// /\*\* @type {Array} \*/ var x = object;
// return x;
// }
// };
//
// 2. ADVANCED\_OPTIMIZATIONS
//
// **What is the expected output? What do you see instead?**
//
// ERROR - initializing variable
// found : \*
// required: (Array|null)
// /\*\* @type {Array} \*/ var x = object;
// ^
// **What version of the product are you using? On what operating system?**
//
// Closure Compiler (http://code.google.com/closure/compiler)
// Version: v20130411-90-g4e19b4e
// Built on: 2013/06/03 12:07
//
// **Please provide any additional information below.**
//
// goog.is\* is supposed to help the compiler to check which type we're dealing with.
//
//
| Closure | /*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.testing.Asserts;
public class ClosureReverseAbstractInterpreterTest extends
CompilerTypeTestCase {
public void testGoogIsDef1() throws Exception {
testClosureFunction("goog.isDef",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
VOID_TYPE);
}
public void testGoogIsDef2() throws Exception {
testClosureFunction("goog.isDef",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
NO_TYPE);
}
public void testGoogIsDef3() throws Exception {
testClosureFunction("goog.isDef",
ALL_TYPE,
createUnionType(OBJECT_NUMBER_STRING_BOOLEAN,NULL_TYPE),
VOID_TYPE);
}
public void testGoogIsDef4() throws Exception {
testClosureFunction("goog.isDef",
UNKNOWN_TYPE,
UNKNOWN_TYPE, // TODO(johnlenz): should be CHECKED_UNKNOWN_TYPE
UNKNOWN_TYPE);
}
public void testGoogIsNull1() throws Exception {
testClosureFunction("goog.isNull",
createOptionalType(NUMBER_TYPE),
NO_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsNull2() throws Exception {
testClosureFunction("goog.isNull",
createNullableType(NUMBER_TYPE),
NULL_TYPE,
NUMBER_TYPE);
}
public void testGoogIsNull3() throws Exception {
testClosureFunction("goog.isNull",
ALL_TYPE,
NULL_TYPE,
createUnionType(OBJECT_NUMBER_STRING_BOOLEAN, VOID_TYPE));
}
public void testGoogIsNull4() throws Exception {
testClosureFunction("goog.isNull",
UNKNOWN_TYPE,
UNKNOWN_TYPE,
UNKNOWN_TYPE); // TODO(johnlenz): this should be CHECK_UNKNOWN
}
public void testGoogIsDefAndNotNull1() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
VOID_TYPE);
}
public void testGoogIsDefAndNotNull2() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
NULL_TYPE);
}
public void testGoogIsDefAndNotNull3() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(createNullableType(NUMBER_TYPE)),
NUMBER_TYPE,
NULL_VOID);
}
public void testGoogIsDefAndNotNull4() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
ALL_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN,
NULL_VOID);
}
public void testGoogIsDefAndNotNull5() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
UNKNOWN_TYPE,
UNKNOWN_TYPE, // TODO(johnlenz): this should be "CHECKED_UNKNOWN"
UNKNOWN_TYPE);
}
public void testGoogIsString1() throws Exception {
testClosureFunction("goog.isString",
createNullableType(STRING_TYPE),
STRING_TYPE,
NULL_TYPE);
}
public void testGoogIsString2() throws Exception {
testClosureFunction("goog.isString",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE));
}
public void testGoogIsBoolean1() throws Exception {
testClosureFunction("goog.isBoolean",
createNullableType(BOOLEAN_TYPE),
BOOLEAN_TYPE,
NULL_TYPE);
}
public void testGoogIsBoolean2() throws Exception {
testClosureFunction("goog.isBoolean",
createUnionType(BOOLEAN_TYPE, STRING_TYPE, NO_OBJECT_TYPE),
BOOLEAN_TYPE,
createUnionType(STRING_TYPE, NO_OBJECT_TYPE));
}
public void testGoogIsBoolean3() throws Exception {
testClosureFunction("goog.isBoolean",
ALL_TYPE,
BOOLEAN_TYPE,
ALL_TYPE); // TODO(johnlenz): this should be:
// {Object|number|string|null|void}
}
public void testGoogIsBoolean4() throws Exception {
testClosureFunction("goog.isBoolean",
UNKNOWN_TYPE,
BOOLEAN_TYPE,
CHECKED_UNKNOWN_TYPE);
}
public void testGoogIsNumber() throws Exception {
testClosureFunction("goog.isNumber",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction() throws Exception {
testClosureFunction("goog.isFunction",
createNullableType(OBJECT_FUNCTION_TYPE),
OBJECT_FUNCTION_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction2() throws Exception {
testClosureFunction("goog.isFunction",
OBJECT_NUMBER_STRING_BOOLEAN,
U2U_CONSTRUCTOR_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN);
}
public void testGoogIsFunction3() throws Exception {
testClosureFunction("goog.isFunction",
createUnionType(U2U_CONSTRUCTOR_TYPE, NUMBER_STRING_BOOLEAN),
U2U_CONSTRUCTOR_TYPE,
NUMBER_STRING_BOOLEAN);
}
public void testGoogIsFunctionOnNull() throws Exception {
testClosureFunction("goog.isFunction",
null,
U2U_CONSTRUCTOR_TYPE,
null);
}
public void testGoogIsArray1() throws Exception {
testClosureFunction("goog.isArray",
OBJECT_TYPE,
ARRAY_TYPE,
OBJECT_TYPE);
}
public void testGoogIsArray2() throws Exception {
testClosureFunction("goog.isArray",
ALL_TYPE,
ARRAY_TYPE,
ALL_TYPE);
}
public void testGoogIsArray3() throws Exception {
testClosureFunction("goog.isArray",
UNKNOWN_TYPE,
CHECKED_UNKNOWN_TYPE,
CHECKED_UNKNOWN_TYPE);
}
public void testGoogIsArray4() throws Exception {
testClosureFunction("goog.isArray",
createUnionType(ARRAY_TYPE, NULL_TYPE),
ARRAY_TYPE,
NULL_TYPE);
}
public void testGoogIsArrayOnNull() throws Exception {
testClosureFunction("goog.isArray",
null,
ARRAY_TYPE,
null);
}
public void testGoogIsObjectOnNull() throws Exception {
testClosureFunction("goog.isObject",
null,
OBJECT_TYPE,
null);
}
public void testGoogIsObject1() throws Exception {
testClosureFunction("goog.isObject",
ALL_TYPE,
NO_OBJECT_TYPE,
createUnionType(NUMBER_STRING_BOOLEAN, NULL_TYPE, VOID_TYPE));
}
public void testGoogIsObject2() throws Exception {
testClosureFunction("goog.isObject",
createUnionType(OBJECT_TYPE, NUMBER_STRING_BOOLEAN),
OBJECT_TYPE,
NUMBER_STRING_BOOLEAN);
}
public void testGoogIsObject3() throws Exception {
testClosureFunction("goog.isObject",
createUnionType(
OBJECT_TYPE, NUMBER_STRING_BOOLEAN, NULL_TYPE, VOID_TYPE),
OBJECT_TYPE,
createUnionType(NUMBER_STRING_BOOLEAN, NULL_TYPE, VOID_TYPE));
}
public void testGoogIsObject4() throws Exception {
testClosureFunction("goog.isObject",
UNKNOWN_TYPE,
NO_OBJECT_TYPE, // ? Should this be CHECKED_UNKNOWN?
CHECKED_UNKNOWN_TYPE);
}
private void testClosureFunction(String function, JSType type,
JSType trueType, JSType falseType) {
// function(a) where a : type
Node n = compiler.parseTestCode("var a; " + function + "(a)");
Node call = n.getLastChild().getLastChild();
Node name = call.getLastChild();
Scope scope = new SyntacticScopeCreator(compiler).createScope(n, null);
FlowScope flowScope = LinkedFlowScope.createEntryLattice(scope);
assertEquals(Token.CALL, call.getType());
assertEquals(Token.NAME, name.getType());
GoogleCodingConvention convention = new GoogleCodingConvention();
flowScope.inferSlotType("a", type);
ClosureReverseAbstractInterpreter rai =
new ClosureReverseAbstractInterpreter(convention, registry);
// trueScope
Asserts.assertTypeEquals(
trueType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, true)
.getSlot("a").getType());
// falseScope
Asserts.assertTypeEquals(
falseType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, false)
.getSlot("a").getType());
}
} |
||
public void testUnionOfVariableAndNode() throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(
new InputSource(new StringReader(
"<MAIN><A/><A/></MAIN>")));
JXPathContext context = JXPathContext.newContext(doc);
context.getVariables().declareVariable("var", "varValue");
int sz = 0;
for (Iterator ptrs = context.iteratePointers("$var | /MAIN/A"); ptrs.hasNext(); sz++) {
ptrs.next();
}
assertEquals(3, sz);
} | org.apache.commons.jxpath.ri.compiler.VariableTest::testUnionOfVariableAndNode | src/test/org/apache/commons/jxpath/ri/compiler/VariableTest.java | 289 | src/test/org/apache/commons/jxpath/ri/compiler/VariableTest.java | testUnionOfVariableAndNode | /*
* 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 java.io.StringReader;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.Variables;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Test basic functionality of JXPath - infoset types,
* operations.
*
* @author Dmitri Plotnikov
* @version $Revision$ $Date$
*/
public class VariableTest extends JXPathTestCase {
private JXPathContext context;
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public VariableTest(String name) {
super(name);
}
public void setUp() {
if (context == null) {
context = JXPathContext.newContext(null);
context.setFactory(new VariableFactory());
Variables vars = context.getVariables();
vars.declareVariable("a", new Double(1));
vars.declareVariable("b", new Double(1));
vars.declareVariable("c", null);
vars.declareVariable("d", new String[] { "a", "b" });
vars.declareVariable("integer", new Integer(1));
vars.declareVariable("nan", new Double(Double.NaN));
vars.declareVariable("x", null);
}
}
public void testVariables() {
// Variables
assertXPathValueAndPointer(context, "$a", new Double(1), "$a");
}
public void testVariablesInExpressions() {
assertXPathValue(context, "$a = $b", Boolean.TRUE);
assertXPathValue(context, "$a = $nan", Boolean.FALSE);
assertXPathValue(context, "$a + 1", new Double(2));
assertXPathValue(context, "$c", null);
assertXPathValue(context, "$d[2]", "b");
}
public void testInvalidVariableName() {
boolean exception = false;
try {
context.getValue("$none");
}
catch (Exception ex) {
exception = true;
}
assertTrue(
"Evaluating '$none', expected exception - did not get it",
exception);
exception = false;
try {
context.setValue("$none", new Integer(1));
}
catch (Exception ex) {
exception = true;
}
assertTrue(
"Setting '$none = 1', expected exception - did not get it",
exception);
}
public void testNestedContext() {
JXPathContext nestedContext = JXPathContext.newContext(context, null);
assertXPathValue(nestedContext, "$a", new Double(1));
}
public void testSetValue() {
assertXPathSetValue(context, "$x", new Integer(1));
}
public void testCreatePathDeclareVariable() {
// Calls factory.declareVariable("string")
assertXPathCreatePath(context, "$string", null, "$string");
}
public void testCreatePathAndSetValueDeclareVariable() {
// Calls factory.declareVariable("string")
assertXPathCreatePathAndSetValue(
context,
"$string",
"Value",
"$string");
}
public void testCreatePathDeclareVariableSetCollectionElement() {
// Calls factory.declareVariable("stringArray").
// The factory needs to create a collection
assertXPathCreatePath(
context,
"$stringArray[2]",
"",
"$stringArray[2]");
// See if the factory populated the first element as well
assertEquals(
"Created <" + "$stringArray[1]" + ">",
"Value1",
context.getValue("$stringArray[1]"));
}
public void testCreateAndSetValuePathDeclareVariableSetCollectionElement() {
// Calls factory.declareVariable("stringArray").
// The factory needs to create a collection
assertXPathCreatePathAndSetValue(
context,
"$stringArray[2]",
"Value2",
"$stringArray[2]");
// See if the factory populated the first element as well
assertEquals(
"Created <" + "$stringArray[1]" + ">",
"Value1",
context.getValue("$stringArray[1]"));
}
public void testCreatePathExpandCollection() {
context.getVariables().declareVariable(
"array",
new String[] { "Value1" });
// Does not involve factory at all - just expands the collection
assertXPathCreatePath(context, "$array[2]", "", "$array[2]");
// Make sure it is still the same array
assertEquals(
"Created <" + "$array[1]" + ">",
"Value1",
context.getValue("$array[1]"));
}
public void testCreatePathAndSetValueExpandCollection() {
context.getVariables().declareVariable(
"array",
new String[] { "Value1" });
// Does not involve factory at all - just expands the collection
assertXPathCreatePathAndSetValue(
context,
"$array[2]",
"Value2",
"$array[2]");
// Make sure it is still the same array
assertEquals(
"Created <" + "$array[1]" + ">",
"Value1",
context.getValue("$array[1]"));
}
public void testCreatePathDeclareVariableSetProperty() {
// Calls factory.declareVariable("test").
// The factory should create a TestBean
assertXPathCreatePath(
context,
"$test/boolean",
Boolean.FALSE,
"$test/boolean");
}
public void testCreatePathAndSetValueDeclareVariableSetProperty() {
// Calls factory.declareVariable("test").
// The factory should create a TestBean
assertXPathCreatePathAndSetValue(
context,
"$test/boolean",
Boolean.TRUE,
"$test/boolean");
}
public void testCreatePathDeclareVariableSetCollectionElementProperty() {
// Calls factory.declareVariable("testArray").
// The factory should create a collection of TestBeans.
// Then calls factory.createObject(..., collection, "testArray", 1).
// That one should produce an instance of TestBean and
// put it in the collection at index 1.
assertXPathCreatePath(
context,
"$testArray[2]/boolean",
Boolean.FALSE,
"$testArray[2]/boolean");
}
public void testCreatePathAndSetValueDeclVarSetCollectionElementProperty() {
// Calls factory.declareVariable("testArray").
// The factory should create a collection of TestBeans.
// Then calls factory.createObject(..., collection, "testArray", 1).
// That one should produce an instance of TestBean and
// put it in the collection at index 1.
assertXPathCreatePathAndSetValue(
context,
"$testArray[2]/boolean",
Boolean.TRUE,
"$testArray[2]/boolean");
}
public void testRemovePathUndeclareVariable() {
// Undeclare variable
context.getVariables().declareVariable("temp", "temp");
context.removePath("$temp");
assertTrue(
"Undeclare variable",
!context.getVariables().isDeclaredVariable("temp"));
}
public void testRemovePathArrayElement() {
// Remove array element - reassigns the new array to the var
context.getVariables().declareVariable(
"temp",
new String[] { "temp1", "temp2" });
context.removePath("$temp[1]");
assertEquals(
"Remove array element",
"temp2",
context.getValue("$temp[1]"));
}
public void testRemovePathCollectionElement() {
// Remove list element - does not create a new list
context.getVariables().declareVariable("temp", list("temp1", "temp2"));
context.removePath("$temp[1]");
assertEquals(
"Remove collection element",
"temp2",
context.getValue("$temp[1]"));
}
public void testUnionOfVariableAndNode() throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(
new InputSource(new StringReader(
"<MAIN><A/><A/></MAIN>")));
JXPathContext context = JXPathContext.newContext(doc);
context.getVariables().declareVariable("var", "varValue");
int sz = 0;
for (Iterator ptrs = context.iteratePointers("$var | /MAIN/A"); ptrs.hasNext(); sz++) {
ptrs.next();
}
assertEquals(3, sz);
}
} | // You are a professional Java test case writer, please create a test case named `testUnionOfVariableAndNode` for the issue `JxPath-JXPATH-89`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-89
//
// ## Issue-Title:
// Cannot compare pointers that do not belong to the same tree
//
// ## Issue-Description:
//
// For XPath "$var | /MAIN/A" exception is thrown:
//
//
// org.apache.commons.jxpath.JXPathException: Cannot compare pointers that do not belong to the same tree: '$var' and ''
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:665)
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareTo(NodePointer.java:639)
//
// at java.util.Arrays.mergeSort(Arrays.java:1152)
//
// at java.util.Arrays.sort(Arrays.java:1079)
//
// at java.util.Collections.sort(Collections.java:113)
//
// at org.apache.commons.jxpath.ri.EvalContext.constructIterator(EvalContext.java:176)
//
// at org.apache.commons.jxpath.ri.EvalContext.hasNext(EvalContext.java:100)
//
// at org.apache.commons.jxpath.JXPathContext.selectNodes(JXPathContext.java:648)
//
// at org.apache.commons.jxpath.ri.model.VariablePointerTestCase.testUnionOfVariableAndNode(VariablePointerTestCase.java:76)
//
//
//
//
//
public void testUnionOfVariableAndNode() throws Exception {
| 289 | 5 | 276 | src/test/org/apache/commons/jxpath/ri/compiler/VariableTest.java | src/test | ```markdown
## Issue-ID: JxPath-JXPATH-89
## Issue-Title:
Cannot compare pointers that do not belong to the same tree
## Issue-Description:
For XPath "$var | /MAIN/A" exception is thrown:
org.apache.commons.jxpath.JXPathException: Cannot compare pointers that do not belong to the same tree: '$var' and ''
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:665)
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
at org.apache.commons.jxpath.ri.model.NodePointer.compareTo(NodePointer.java:639)
at java.util.Arrays.mergeSort(Arrays.java:1152)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:113)
at org.apache.commons.jxpath.ri.EvalContext.constructIterator(EvalContext.java:176)
at org.apache.commons.jxpath.ri.EvalContext.hasNext(EvalContext.java:100)
at org.apache.commons.jxpath.JXPathContext.selectNodes(JXPathContext.java:648)
at org.apache.commons.jxpath.ri.model.VariablePointerTestCase.testUnionOfVariableAndNode(VariablePointerTestCase.java:76)
```
You are a professional Java test case writer, please create a test case named `testUnionOfVariableAndNode` for the issue `JxPath-JXPATH-89`, utilizing the provided issue report information and the following function signature.
```java
public void testUnionOfVariableAndNode() throws Exception {
```
| 276 | [
"org.apache.commons.jxpath.ri.model.NodePointer"
] | 59acc5ec8cfbf8b1767269e892ab4d4538dd16c65fceebe48ca02423a160e856 | public void testUnionOfVariableAndNode() throws Exception | // You are a professional Java test case writer, please create a test case named `testUnionOfVariableAndNode` for the issue `JxPath-JXPATH-89`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-89
//
// ## Issue-Title:
// Cannot compare pointers that do not belong to the same tree
//
// ## Issue-Description:
//
// For XPath "$var | /MAIN/A" exception is thrown:
//
//
// org.apache.commons.jxpath.JXPathException: Cannot compare pointers that do not belong to the same tree: '$var' and ''
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:665)
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
//
// at org.apache.commons.jxpath.ri.model.NodePointer.compareTo(NodePointer.java:639)
//
// at java.util.Arrays.mergeSort(Arrays.java:1152)
//
// at java.util.Arrays.sort(Arrays.java:1079)
//
// at java.util.Collections.sort(Collections.java:113)
//
// at org.apache.commons.jxpath.ri.EvalContext.constructIterator(EvalContext.java:176)
//
// at org.apache.commons.jxpath.ri.EvalContext.hasNext(EvalContext.java:100)
//
// at org.apache.commons.jxpath.JXPathContext.selectNodes(JXPathContext.java:648)
//
// at org.apache.commons.jxpath.ri.model.VariablePointerTestCase.testUnionOfVariableAndNode(VariablePointerTestCase.java:76)
//
//
//
//
//
| 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 java.io.StringReader;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.Variables;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Test basic functionality of JXPath - infoset types,
* operations.
*
* @author Dmitri Plotnikov
* @version $Revision$ $Date$
*/
public class VariableTest extends JXPathTestCase {
private JXPathContext context;
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public VariableTest(String name) {
super(name);
}
public void setUp() {
if (context == null) {
context = JXPathContext.newContext(null);
context.setFactory(new VariableFactory());
Variables vars = context.getVariables();
vars.declareVariable("a", new Double(1));
vars.declareVariable("b", new Double(1));
vars.declareVariable("c", null);
vars.declareVariable("d", new String[] { "a", "b" });
vars.declareVariable("integer", new Integer(1));
vars.declareVariable("nan", new Double(Double.NaN));
vars.declareVariable("x", null);
}
}
public void testVariables() {
// Variables
assertXPathValueAndPointer(context, "$a", new Double(1), "$a");
}
public void testVariablesInExpressions() {
assertXPathValue(context, "$a = $b", Boolean.TRUE);
assertXPathValue(context, "$a = $nan", Boolean.FALSE);
assertXPathValue(context, "$a + 1", new Double(2));
assertXPathValue(context, "$c", null);
assertXPathValue(context, "$d[2]", "b");
}
public void testInvalidVariableName() {
boolean exception = false;
try {
context.getValue("$none");
}
catch (Exception ex) {
exception = true;
}
assertTrue(
"Evaluating '$none', expected exception - did not get it",
exception);
exception = false;
try {
context.setValue("$none", new Integer(1));
}
catch (Exception ex) {
exception = true;
}
assertTrue(
"Setting '$none = 1', expected exception - did not get it",
exception);
}
public void testNestedContext() {
JXPathContext nestedContext = JXPathContext.newContext(context, null);
assertXPathValue(nestedContext, "$a", new Double(1));
}
public void testSetValue() {
assertXPathSetValue(context, "$x", new Integer(1));
}
public void testCreatePathDeclareVariable() {
// Calls factory.declareVariable("string")
assertXPathCreatePath(context, "$string", null, "$string");
}
public void testCreatePathAndSetValueDeclareVariable() {
// Calls factory.declareVariable("string")
assertXPathCreatePathAndSetValue(
context,
"$string",
"Value",
"$string");
}
public void testCreatePathDeclareVariableSetCollectionElement() {
// Calls factory.declareVariable("stringArray").
// The factory needs to create a collection
assertXPathCreatePath(
context,
"$stringArray[2]",
"",
"$stringArray[2]");
// See if the factory populated the first element as well
assertEquals(
"Created <" + "$stringArray[1]" + ">",
"Value1",
context.getValue("$stringArray[1]"));
}
public void testCreateAndSetValuePathDeclareVariableSetCollectionElement() {
// Calls factory.declareVariable("stringArray").
// The factory needs to create a collection
assertXPathCreatePathAndSetValue(
context,
"$stringArray[2]",
"Value2",
"$stringArray[2]");
// See if the factory populated the first element as well
assertEquals(
"Created <" + "$stringArray[1]" + ">",
"Value1",
context.getValue("$stringArray[1]"));
}
public void testCreatePathExpandCollection() {
context.getVariables().declareVariable(
"array",
new String[] { "Value1" });
// Does not involve factory at all - just expands the collection
assertXPathCreatePath(context, "$array[2]", "", "$array[2]");
// Make sure it is still the same array
assertEquals(
"Created <" + "$array[1]" + ">",
"Value1",
context.getValue("$array[1]"));
}
public void testCreatePathAndSetValueExpandCollection() {
context.getVariables().declareVariable(
"array",
new String[] { "Value1" });
// Does not involve factory at all - just expands the collection
assertXPathCreatePathAndSetValue(
context,
"$array[2]",
"Value2",
"$array[2]");
// Make sure it is still the same array
assertEquals(
"Created <" + "$array[1]" + ">",
"Value1",
context.getValue("$array[1]"));
}
public void testCreatePathDeclareVariableSetProperty() {
// Calls factory.declareVariable("test").
// The factory should create a TestBean
assertXPathCreatePath(
context,
"$test/boolean",
Boolean.FALSE,
"$test/boolean");
}
public void testCreatePathAndSetValueDeclareVariableSetProperty() {
// Calls factory.declareVariable("test").
// The factory should create a TestBean
assertXPathCreatePathAndSetValue(
context,
"$test/boolean",
Boolean.TRUE,
"$test/boolean");
}
public void testCreatePathDeclareVariableSetCollectionElementProperty() {
// Calls factory.declareVariable("testArray").
// The factory should create a collection of TestBeans.
// Then calls factory.createObject(..., collection, "testArray", 1).
// That one should produce an instance of TestBean and
// put it in the collection at index 1.
assertXPathCreatePath(
context,
"$testArray[2]/boolean",
Boolean.FALSE,
"$testArray[2]/boolean");
}
public void testCreatePathAndSetValueDeclVarSetCollectionElementProperty() {
// Calls factory.declareVariable("testArray").
// The factory should create a collection of TestBeans.
// Then calls factory.createObject(..., collection, "testArray", 1).
// That one should produce an instance of TestBean and
// put it in the collection at index 1.
assertXPathCreatePathAndSetValue(
context,
"$testArray[2]/boolean",
Boolean.TRUE,
"$testArray[2]/boolean");
}
public void testRemovePathUndeclareVariable() {
// Undeclare variable
context.getVariables().declareVariable("temp", "temp");
context.removePath("$temp");
assertTrue(
"Undeclare variable",
!context.getVariables().isDeclaredVariable("temp"));
}
public void testRemovePathArrayElement() {
// Remove array element - reassigns the new array to the var
context.getVariables().declareVariable(
"temp",
new String[] { "temp1", "temp2" });
context.removePath("$temp[1]");
assertEquals(
"Remove array element",
"temp2",
context.getValue("$temp[1]"));
}
public void testRemovePathCollectionElement() {
// Remove list element - does not create a new list
context.getVariables().declareVariable("temp", list("temp1", "temp2"));
context.removePath("$temp[1]");
assertEquals(
"Remove collection element",
"temp2",
context.getValue("$temp[1]"));
}
public void testUnionOfVariableAndNode() throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(
new InputSource(new StringReader(
"<MAIN><A/><A/></MAIN>")));
JXPathContext context = JXPathContext.newContext(doc);
context.getVariables().declareVariable("var", "varValue");
int sz = 0;
for (Iterator ptrs = context.iteratePointers("$var | /MAIN/A"); ptrs.hasNext(); sz++) {
ptrs.next();
}
assertEquals(3, sz);
}
} |
||
public void testBinaryAsEmbeddedObject() throws Exception
{
JsonGenerator g;
StringWriter sw = new StringWriter();
g = JSON_F.createGenerator(sw);
g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
g.close();
assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), sw.toString());
ByteArrayOutputStream bytes = new ByteArrayOutputStream(100);
g = JSON_F.createGenerator(bytes);
g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
g.close();
assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), bytes.toString("UTF-8"));
} | com.fasterxml.jackson.core.base64.Base64GenerationTest::testBinaryAsEmbeddedObject | src/test/java/com/fasterxml/jackson/core/base64/Base64GenerationTest.java | 108 | src/test/java/com/fasterxml/jackson/core/base64/Base64GenerationTest.java | testBinaryAsEmbeddedObject | package com.fasterxml.jackson.core.base64;
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.testsupport.ThrottledInputStream;
public class Base64GenerationTest
extends com.fasterxml.jackson.core.BaseTest
{
/* The usual sample input string, from Thomas Hobbes's "Leviathan"
* (via Wikipedia)
*/
private final static String WIKIPEDIA_BASE64_TEXT = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
private final static byte[] WIKIPEDIA_BASE64_AS_BYTES;
static {
try {
WIKIPEDIA_BASE64_AS_BYTES = WIKIPEDIA_BASE64_TEXT.getBytes("US-ASCII");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final String WIKIPEDIA_BASE64_ENCODED =
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
+"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
+"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
+"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
+"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
;
private final static Base64Variant[] VARIANTS = {
Base64Variants.MIME,
Base64Variants.MIME_NO_LINEFEEDS,
Base64Variants.MODIFIED_FOR_URL,
Base64Variants.PEM
};
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final JsonFactory JSON_F = new JsonFactory();
public void testStreamingBinaryWrites() throws Exception
{
_testStreamingWrites(JSON_F, true);
_testStreamingWrites(JSON_F, false);
}
// For [core#55]
public void testIssue55() throws Exception
{
final JsonFactory f = new JsonFactory();
// First, byte-backed:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JsonGenerator gen = f.createGenerator(bytes);
ByteArrayInputStream data = new ByteArrayInputStream(new byte[2000]);
gen.writeBinary(data, 1999);
gen.close();
final int EXP_LEN = 2670;
assertEquals(EXP_LEN, bytes.size());
// Then char-backed
StringWriter sw = new StringWriter();
gen = f.createGenerator(sw);
data = new ByteArrayInputStream(new byte[2000]);
gen.writeBinary(data, 1999);
gen.close();
assertEquals(EXP_LEN, sw.toString().length());
}
/**
* This is really inadequate test, all in all, but should serve
* as some kind of sanity check. Reader-side should more thoroughly
* test things, as it does need writers to construct the data first.
*/
public void testSimpleBinaryWrite() throws Exception
{
_testSimpleBinaryWrite(false);
_testSimpleBinaryWrite(true);
}
// for [core#318]
public void testBinaryAsEmbeddedObject() throws Exception
{
JsonGenerator g;
StringWriter sw = new StringWriter();
g = JSON_F.createGenerator(sw);
g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
g.close();
assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), sw.toString());
ByteArrayOutputStream bytes = new ByteArrayOutputStream(100);
g = JSON_F.createGenerator(bytes);
g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
g.close();
assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), bytes.toString("UTF-8"));
}
/*
/**********************************************************
/* Helper methods
/**********************************************************
*/
private void _testSimpleBinaryWrite(boolean useCharBased) throws Exception
{
/* Let's only test the standard base64 variant; but write
* values in root, array and object contexts.
*/
Base64Variant b64v = Base64Variants.getDefaultVariant();
JsonFactory jf = new JsonFactory();
for (int i = 0; i < 3; ++i) {
JsonGenerator gen;
ByteArrayOutputStream bout = new ByteArrayOutputStream(200);
if (useCharBased) {
gen = jf.createGenerator(new OutputStreamWriter(bout, "UTF-8"));
} else {
gen = jf.createGenerator(bout, JsonEncoding.UTF8);
}
switch (i) {
case 0: // root
gen.writeBinary(b64v, WIKIPEDIA_BASE64_AS_BYTES, 0, WIKIPEDIA_BASE64_AS_BYTES.length);
break;
case 1: // array
gen.writeStartArray();
gen.writeBinary(b64v, WIKIPEDIA_BASE64_AS_BYTES, 0, WIKIPEDIA_BASE64_AS_BYTES.length);
gen.writeEndArray();
break;
default: // object
gen.writeStartObject();
gen.writeFieldName("field");
gen.writeBinary(b64v, WIKIPEDIA_BASE64_AS_BYTES, 0, WIKIPEDIA_BASE64_AS_BYTES.length);
gen.writeEndObject();
break;
}
gen.close();
JsonParser jp = jf.createParser(new ByteArrayInputStream(bout.toByteArray()));
// Need to skip other events before binary data:
switch (i) {
case 0:
break;
case 1:
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
break;
default:
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
break;
}
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
String actualValue = jp.getText();
jp.close();
assertEquals(WIKIPEDIA_BASE64_ENCODED, actualValue);
}
}
private final static String TEXT = "Some content so that we can test encoding of base64 data; must"
+" be long enough include a line wrap or two...";
private final static String TEXT4 = TEXT + TEXT + TEXT + TEXT;
@SuppressWarnings("resource")
private void _testStreamingWrites(JsonFactory jf, boolean useBytes) throws Exception
{
final byte[] INPUT = TEXT4.getBytes("UTF-8");
for (Base64Variant variant : VARIANTS) {
final String EXP_OUTPUT = "[" + quote(variant.encode(INPUT))+"]";
for (boolean passLength : new boolean[] { true, false }) {
for (int chunkSize : new int[] { 1, 2, 3, 4, 7, 11, 29, 5000 }) {
//System.err.println(""+variant+", length "+passLength+", chunk "+chunkSize);
JsonGenerator jgen;
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (useBytes) {
jgen = jf.createGenerator(bytes);
} else {
jgen = jf.createGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.writeStartArray();
int length = passLength ? INPUT.length : -1;
InputStream data = new ThrottledInputStream(INPUT, chunkSize);
jgen.writeBinary(variant, data, length);
jgen.writeEndArray();
jgen.close();
String JSON = bytes.toString("UTF-8");
assertEquals(EXP_OUTPUT, JSON);
}
}
}
}
} | // You are a professional Java test case writer, please create a test case named `testBinaryAsEmbeddedObject` for the issue `JacksonCore-318`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonCore-318
//
// ## Issue-Title:
// Add support for writing byte[] via JsonGenerator.writeEmbeddedObject()
//
// ## Issue-Description:
// (note: should be safe for patch, that is, 2.8.3)
//
//
// Default implementation of 2.8-added `writeEmbeddedObject()` throws exception (unsupported operation) for all values, since JSON does not have any native object types.
//
// This is different from handling of `writeObject()`, which tries to either delegate to `ObjectCodec` (if one registered), or even encode "simple" values.
//
//
// However: since support for binary data is already handled in some cases using `VALUE_EMBEDDED_OBJECT`, it would actually make sense to handle case of `byte[]` (and, if feasible, perhaps `ByteBuffer` for extra points), and also ensure `null` can be written.
//
//
// This is likely necessary to support [FasterXML/jackson-databind#1361](https://github.com/FasterXML/jackson-databind/issues/1361) and should in general make system more robust.
//
//
//
//
public void testBinaryAsEmbeddedObject() throws Exception {
| 108 | // for [core#318] | 20 | 93 | src/test/java/com/fasterxml/jackson/core/base64/Base64GenerationTest.java | src/test/java | ```markdown
## Issue-ID: JacksonCore-318
## Issue-Title:
Add support for writing byte[] via JsonGenerator.writeEmbeddedObject()
## Issue-Description:
(note: should be safe for patch, that is, 2.8.3)
Default implementation of 2.8-added `writeEmbeddedObject()` throws exception (unsupported operation) for all values, since JSON does not have any native object types.
This is different from handling of `writeObject()`, which tries to either delegate to `ObjectCodec` (if one registered), or even encode "simple" values.
However: since support for binary data is already handled in some cases using `VALUE_EMBEDDED_OBJECT`, it would actually make sense to handle case of `byte[]` (and, if feasible, perhaps `ByteBuffer` for extra points), and also ensure `null` can be written.
This is likely necessary to support [FasterXML/jackson-databind#1361](https://github.com/FasterXML/jackson-databind/issues/1361) and should in general make system more robust.
```
You are a professional Java test case writer, please create a test case named `testBinaryAsEmbeddedObject` for the issue `JacksonCore-318`, utilizing the provided issue report information and the following function signature.
```java
public void testBinaryAsEmbeddedObject() throws Exception {
```
| 93 | [
"com.fasterxml.jackson.core.JsonGenerator"
] | 5ae83d482b85929c24eb634c9403e036ba0439685e62ad8adafa535a3df4e736 | public void testBinaryAsEmbeddedObject() throws Exception
| // You are a professional Java test case writer, please create a test case named `testBinaryAsEmbeddedObject` for the issue `JacksonCore-318`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonCore-318
//
// ## Issue-Title:
// Add support for writing byte[] via JsonGenerator.writeEmbeddedObject()
//
// ## Issue-Description:
// (note: should be safe for patch, that is, 2.8.3)
//
//
// Default implementation of 2.8-added `writeEmbeddedObject()` throws exception (unsupported operation) for all values, since JSON does not have any native object types.
//
// This is different from handling of `writeObject()`, which tries to either delegate to `ObjectCodec` (if one registered), or even encode "simple" values.
//
//
// However: since support for binary data is already handled in some cases using `VALUE_EMBEDDED_OBJECT`, it would actually make sense to handle case of `byte[]` (and, if feasible, perhaps `ByteBuffer` for extra points), and also ensure `null` can be written.
//
//
// This is likely necessary to support [FasterXML/jackson-databind#1361](https://github.com/FasterXML/jackson-databind/issues/1361) and should in general make system more robust.
//
//
//
//
| JacksonCore | package com.fasterxml.jackson.core.base64;
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.testsupport.ThrottledInputStream;
public class Base64GenerationTest
extends com.fasterxml.jackson.core.BaseTest
{
/* The usual sample input string, from Thomas Hobbes's "Leviathan"
* (via Wikipedia)
*/
private final static String WIKIPEDIA_BASE64_TEXT = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
private final static byte[] WIKIPEDIA_BASE64_AS_BYTES;
static {
try {
WIKIPEDIA_BASE64_AS_BYTES = WIKIPEDIA_BASE64_TEXT.getBytes("US-ASCII");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private final String WIKIPEDIA_BASE64_ENCODED =
"TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
+"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
+"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
+"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
+"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="
;
private final static Base64Variant[] VARIANTS = {
Base64Variants.MIME,
Base64Variants.MIME_NO_LINEFEEDS,
Base64Variants.MODIFIED_FOR_URL,
Base64Variants.PEM
};
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final JsonFactory JSON_F = new JsonFactory();
public void testStreamingBinaryWrites() throws Exception
{
_testStreamingWrites(JSON_F, true);
_testStreamingWrites(JSON_F, false);
}
// For [core#55]
public void testIssue55() throws Exception
{
final JsonFactory f = new JsonFactory();
// First, byte-backed:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JsonGenerator gen = f.createGenerator(bytes);
ByteArrayInputStream data = new ByteArrayInputStream(new byte[2000]);
gen.writeBinary(data, 1999);
gen.close();
final int EXP_LEN = 2670;
assertEquals(EXP_LEN, bytes.size());
// Then char-backed
StringWriter sw = new StringWriter();
gen = f.createGenerator(sw);
data = new ByteArrayInputStream(new byte[2000]);
gen.writeBinary(data, 1999);
gen.close();
assertEquals(EXP_LEN, sw.toString().length());
}
/**
* This is really inadequate test, all in all, but should serve
* as some kind of sanity check. Reader-side should more thoroughly
* test things, as it does need writers to construct the data first.
*/
public void testSimpleBinaryWrite() throws Exception
{
_testSimpleBinaryWrite(false);
_testSimpleBinaryWrite(true);
}
// for [core#318]
public void testBinaryAsEmbeddedObject() throws Exception
{
JsonGenerator g;
StringWriter sw = new StringWriter();
g = JSON_F.createGenerator(sw);
g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
g.close();
assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), sw.toString());
ByteArrayOutputStream bytes = new ByteArrayOutputStream(100);
g = JSON_F.createGenerator(bytes);
g.writeEmbeddedObject(WIKIPEDIA_BASE64_AS_BYTES);
g.close();
assertEquals(quote(WIKIPEDIA_BASE64_ENCODED), bytes.toString("UTF-8"));
}
/*
/**********************************************************
/* Helper methods
/**********************************************************
*/
private void _testSimpleBinaryWrite(boolean useCharBased) throws Exception
{
/* Let's only test the standard base64 variant; but write
* values in root, array and object contexts.
*/
Base64Variant b64v = Base64Variants.getDefaultVariant();
JsonFactory jf = new JsonFactory();
for (int i = 0; i < 3; ++i) {
JsonGenerator gen;
ByteArrayOutputStream bout = new ByteArrayOutputStream(200);
if (useCharBased) {
gen = jf.createGenerator(new OutputStreamWriter(bout, "UTF-8"));
} else {
gen = jf.createGenerator(bout, JsonEncoding.UTF8);
}
switch (i) {
case 0: // root
gen.writeBinary(b64v, WIKIPEDIA_BASE64_AS_BYTES, 0, WIKIPEDIA_BASE64_AS_BYTES.length);
break;
case 1: // array
gen.writeStartArray();
gen.writeBinary(b64v, WIKIPEDIA_BASE64_AS_BYTES, 0, WIKIPEDIA_BASE64_AS_BYTES.length);
gen.writeEndArray();
break;
default: // object
gen.writeStartObject();
gen.writeFieldName("field");
gen.writeBinary(b64v, WIKIPEDIA_BASE64_AS_BYTES, 0, WIKIPEDIA_BASE64_AS_BYTES.length);
gen.writeEndObject();
break;
}
gen.close();
JsonParser jp = jf.createParser(new ByteArrayInputStream(bout.toByteArray()));
// Need to skip other events before binary data:
switch (i) {
case 0:
break;
case 1:
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
break;
default:
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
break;
}
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
String actualValue = jp.getText();
jp.close();
assertEquals(WIKIPEDIA_BASE64_ENCODED, actualValue);
}
}
private final static String TEXT = "Some content so that we can test encoding of base64 data; must"
+" be long enough include a line wrap or two...";
private final static String TEXT4 = TEXT + TEXT + TEXT + TEXT;
@SuppressWarnings("resource")
private void _testStreamingWrites(JsonFactory jf, boolean useBytes) throws Exception
{
final byte[] INPUT = TEXT4.getBytes("UTF-8");
for (Base64Variant variant : VARIANTS) {
final String EXP_OUTPUT = "[" + quote(variant.encode(INPUT))+"]";
for (boolean passLength : new boolean[] { true, false }) {
for (int chunkSize : new int[] { 1, 2, 3, 4, 7, 11, 29, 5000 }) {
//System.err.println(""+variant+", length "+passLength+", chunk "+chunkSize);
JsonGenerator jgen;
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (useBytes) {
jgen = jf.createGenerator(bytes);
} else {
jgen = jf.createGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.writeStartArray();
int length = passLength ? INPUT.length : -1;
InputStream data = new ThrottledInputStream(INPUT, chunkSize);
jgen.writeBinary(variant, data, length);
jgen.writeEndArray();
jgen.close();
String JSON = bytes.toString("UTF-8");
assertEquals(EXP_OUTPUT, JSON);
}
}
}
}
} |
|
public void testAvailableLocaleSet() {
Set set = LocaleUtils.availableLocaleSet();
Set set2 = LocaleUtils.availableLocaleSet();
assertNotNull(set);
assertSame(set, set2);
assertUnmodifiableCollection(set);
Locale[] jdkLocaleArray = Locale.getAvailableLocales();
List jdkLocaleList = Arrays.asList(jdkLocaleArray);
Set jdkLocaleSet = new HashSet(jdkLocaleList);
assertEquals(jdkLocaleSet, set);
} | org.apache.commons.lang.LocaleUtilsTest::testAvailableLocaleSet | src/test/org/apache/commons/lang/LocaleUtilsTest.java | 374 | src/test/org/apache/commons/lang/LocaleUtilsTest.java | testAvailableLocaleSet | /*
* 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.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Unit tests for {@link LocaleUtils}.
*
* @author Chris Hyzer
* @author Stephen Colebourne
* @version $Id$
*/
public class LocaleUtilsTest extends TestCase {
private static final Locale LOCALE_EN = new Locale("en", "");
private static final Locale LOCALE_EN_US = new Locale("en", "US");
private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ");
private static final Locale LOCALE_FR = new Locale("fr", "");
private static final Locale LOCALE_FR_CA = new Locale("fr", "CA");
private static final Locale LOCALE_QQ = new Locale("qq", "");
private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
/**
* Constructor.
*
* @param name
*/
public LocaleUtilsTest(String name) {
super(name);
}
/**
* Main.
* @param args
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* Run the test cases as a suite.
* @return the Test
*/
public static Test suite() {
TestSuite suite = new TestSuite(LocaleUtilsTest.class);
suite.setName("LocaleUtilsTest Tests");
return suite;
}
public void setUp() throws Exception {
super.setUp();
// Testing #LANG-304. Must be called before availableLocaleSet is called.
LocaleUtils.isAvailableLocale(Locale.getDefault());
}
//-----------------------------------------------------------------------
/**
* Test that constructors are public, and work, etc.
*/
public void testConstructor() {
assertNotNull(new LocaleUtils());
Constructor[] cons = LocaleUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
assertEquals(true, Modifier.isPublic(LocaleUtils.class.getModifiers()));
assertEquals(false, Modifier.isFinal(LocaleUtils.class.getModifiers()));
}
//-----------------------------------------------------------------------
/**
* Pass in a valid language, test toLocale.
*
* @param language the language string
*/
private void assertValidToLocale(String language) {
Locale locale = LocaleUtils.toLocale(language);
assertNotNull("valid locale", locale);
assertEquals(language, locale.getLanguage());
//country and variant are empty
assertTrue(locale.getCountry() == null || locale.getCountry().length() == 0);
assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0);
}
/**
* Pass in a valid language, test toLocale.
*
* @param localeString to pass to toLocale()
* @param language of the resulting Locale
* @param country of the resulting Locale
*/
private void assertValidToLocale(String localeString, String language, String country) {
Locale locale = LocaleUtils.toLocale(localeString);
assertNotNull("valid locale", locale);
assertEquals(language, locale.getLanguage());
assertEquals(country, locale.getCountry());
//variant is empty
assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0);
}
/**
* Pass in a valid language, test toLocale.
*
* @param localeString to pass to toLocale()
* @param language of the resulting Locale
* @param country of the resulting Locale
* @param variant of the resulting Locale
*/
private void assertValidToLocale(
String localeString, String language,
String country, String variant) {
Locale locale = LocaleUtils.toLocale(localeString);
assertNotNull("valid locale", locale);
assertEquals(language, locale.getLanguage());
assertEquals(country, locale.getCountry());
assertEquals(variant, locale.getVariant());
}
/**
* Test toLocale() method.
*/
public void testToLocale_1Part() {
assertEquals(null, LocaleUtils.toLocale((String) null));
assertValidToLocale("us");
assertValidToLocale("fr");
assertValidToLocale("de");
assertValidToLocale("zh");
// Valid format but lang doesnt exist, should make instance anyway
assertValidToLocale("qq");
try {
LocaleUtils.toLocale("Us");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("US");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uS");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("u#");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("u");
fail("Must be 2 chars if less than 5");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uuu");
fail("Must be 2 chars if less than 5");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uu_U");
fail("Must be 2 chars if less than 5");
} catch (IllegalArgumentException iae) {}
}
/**
* Test toLocale() method.
*/
public void testToLocale_2Part() {
assertValidToLocale("us_EN", "us", "EN");
//valid though doesnt exist
assertValidToLocale("us_ZH", "us", "ZH");
try {
LocaleUtils.toLocale("us-EN");
fail("Should fail as not underscore");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_En");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_en");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_eN");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uS_EN");
fail("Should fail first part not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_E3");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
}
/**
* Test toLocale() method.
*/
public void testToLocale_3Part() {
assertValidToLocale("us_EN_A", "us", "EN", "A");
// this isn't pretty, but was caused by a jdk bug it seems
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525
if (SystemUtils.isJavaVersionAtLeast(1.4f)) {
assertValidToLocale("us_EN_a", "us", "EN", "a");
assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF");
} else {
assertValidToLocale("us_EN_a", "us", "EN", "A");
assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF");
}
try {
LocaleUtils.toLocale("us_EN-a");
fail("Should fail as not underscore");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uu_UU_");
fail("Must be 3, 5 or 7+ in length");
} catch (IllegalArgumentException iae) {}
}
//-----------------------------------------------------------------------
/**
* Helper method for local lookups.
*
* @param locale the input locale
* @param defaultLocale the input default locale
* @param expected expected results
*/
private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) {
List localeList = defaultLocale == null ?
LocaleUtils.localeLookupList(locale) :
LocaleUtils.localeLookupList(locale, defaultLocale);
assertEquals(expected.length, localeList.size());
assertEquals(Arrays.asList(expected), localeList);
assertUnmodifiableCollection(localeList);
}
//-----------------------------------------------------------------------
/**
* Test localeLookupList() method.
*/
public void testLocaleLookupList_Locale() {
assertLocaleLookupList(null, null, new Locale[0]);
assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN});
assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US, null,
new Locale[] {
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN});
}
/**
* Test localeLookupList() method.
*/
public void testLocaleLookupList_LocaleLocale() {
assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ,
new Locale[]{LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN, LOCALE_EN,
new Locale[]{LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US,
new Locale[]{
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ,
new Locale[] {
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ,
new Locale[] {
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ_ZZ});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ_ZZ});
assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN,
new Locale[] {
LOCALE_FR_CA,
LOCALE_FR,
LOCALE_EN});
}
//-----------------------------------------------------------------------
/**
* Test availableLocaleList() method.
*/
public void testAvailableLocaleList() {
List list = LocaleUtils.availableLocaleList();
List list2 = LocaleUtils.availableLocaleList();
assertNotNull(list);
assertSame(list, list2);
assertUnmodifiableCollection(list);
Locale[] jdkLocaleArray = Locale.getAvailableLocales();
List jdkLocaleList = Arrays.asList(jdkLocaleArray);
assertEquals(jdkLocaleList, list);
}
//-----------------------------------------------------------------------
/**
* Test availableLocaleSet() method.
*/
public void testAvailableLocaleSet() {
Set set = LocaleUtils.availableLocaleSet();
Set set2 = LocaleUtils.availableLocaleSet();
assertNotNull(set);
assertSame(set, set2);
assertUnmodifiableCollection(set);
Locale[] jdkLocaleArray = Locale.getAvailableLocales();
List jdkLocaleList = Arrays.asList(jdkLocaleArray);
Set jdkLocaleSet = new HashSet(jdkLocaleList);
assertEquals(jdkLocaleSet, set);
}
//-----------------------------------------------------------------------
/**
* Test availableLocaleSet() method.
*/
public void testIsAvailableLocale() {
Set set = LocaleUtils.availableLocaleSet();
assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN));
assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US));
assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ));
assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR));
assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA));
assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ));
assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ));
}
//-----------------------------------------------------------------------
/**
* Make sure the language by country is correct.
*
* @param country
* @param languages array of languages that should be returned
*/
private void assertLanguageByCountry(String country, String[] languages) {
List list = LocaleUtils.languagesByCountry(country);
List list2 = LocaleUtils.languagesByCountry(country);
assertNotNull(list);
assertSame(list, list2);
assertEquals(languages.length, list.size());
//search through langauges
for (int i = 0; i < languages.length; i++) {
Iterator iterator = list.iterator();
boolean found = false;
// see if it was returned by the set
while (iterator.hasNext()) {
Locale locale = (Locale) iterator.next();
// should have an en empty variant
assertTrue(locale.getVariant() == null
|| locale.getVariant().length() == 0);
assertEquals(country, locale.getCountry());
if (languages[i].equals(locale.getLanguage())) {
found = true;
break;
}
}
if (!found) {
fail("Cound not find language: " + languages[i]
+ " for country: " + country);
}
}
assertUnmodifiableCollection(list);
}
/**
* Test languagesByCountry() method.
*/
public void testLanguagesByCountry() {
assertLanguageByCountry(null, new String[0]);
assertLanguageByCountry("GB", new String[]{"en"});
assertLanguageByCountry("ZZ", new String[0]);
assertLanguageByCountry("CH", new String[]{"fr", "de", "it"});
}
//-----------------------------------------------------------------------
/**
* Make sure the language by country is correct.
*
* @param language
* @param countries array of countries that should be returned
*/
private void assertCountriesByLanguage(String language, String[] countries) {
List list = LocaleUtils.countriesByLanguage(language);
List list2 = LocaleUtils.countriesByLanguage(language);
assertNotNull(list);
assertSame(list, list2);
assertEquals(countries.length, list.size());
//search through langauges
for (int i = 0; i < countries.length; i++) {
Iterator iterator = list.iterator();
boolean found = false;
// see if it was returned by the set
while (iterator.hasNext()) {
Locale locale = (Locale) iterator.next();
// should have an en empty variant
assertTrue(locale.getVariant() == null
|| locale.getVariant().length() == 0);
assertEquals(language, locale.getLanguage());
if (countries[i].equals(locale.getCountry())) {
found = true;
break;
}
}
if (!found) {
fail("Cound not find language: " + countries[i]
+ " for country: " + language);
}
}
assertUnmodifiableCollection(list);
}
/**
* Test languagesByCountry() method.
*/
public void testCountriesByLanguage() {}
// Defects4J: flaky method
// public void testCountriesByLanguage() {
// assertCountriesByLanguage(null, new String[0]);
// assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"});
// assertCountriesByLanguage("zz", new String[0]);
// assertCountriesByLanguage("it", new String[]{"IT", "CH"});
// }
/**
* @param coll the collection to check
*/
private static void assertUnmodifiableCollection(Collection coll) {
try {
coll.add("Unmodifiable");
fail();
} catch (UnsupportedOperationException ex) {}
}
} | // You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the issue `Lang-LANG-304`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-304
//
// ## Issue-Title:
// NullPointerException in isAvailableLocale(Locale)
//
// ## Issue-Description:
//
// FindBugs pointed out:
//
//
// UwF: Field not initialized in constructor: org.apache.commons.lang.LocaleUtils.cAvailableLocaleSet
//
//
// cAvailableSet is used directly once in the source - and if availableLocaleSet() hasn't been called it will cause a NullPointerException.
//
//
//
//
//
public void testAvailableLocaleSet() {
| 374 | /**
* Test availableLocaleSet() method.
*/
//----------------------------------------------------------------------- | 57 | 363 | src/test/org/apache/commons/lang/LocaleUtilsTest.java | src/test | ```markdown
## Issue-ID: Lang-LANG-304
## Issue-Title:
NullPointerException in isAvailableLocale(Locale)
## Issue-Description:
FindBugs pointed out:
UwF: Field not initialized in constructor: org.apache.commons.lang.LocaleUtils.cAvailableLocaleSet
cAvailableSet is used directly once in the source - and if availableLocaleSet() hasn't been called it will cause a NullPointerException.
```
You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the issue `Lang-LANG-304`, utilizing the provided issue report information and the following function signature.
```java
public void testAvailableLocaleSet() {
```
| 363 | [
"org.apache.commons.lang.LocaleUtils"
] | 5c1dc02d60ffc98b5555a73193ed46532ba2d79ed6a38d70f0d516a1ac171ecd | public void testAvailableLocaleSet() | // You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the issue `Lang-LANG-304`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-304
//
// ## Issue-Title:
// NullPointerException in isAvailableLocale(Locale)
//
// ## Issue-Description:
//
// FindBugs pointed out:
//
//
// UwF: Field not initialized in constructor: org.apache.commons.lang.LocaleUtils.cAvailableLocaleSet
//
//
// cAvailableSet is used directly once in the source - and if availableLocaleSet() hasn't been called it will cause a NullPointerException.
//
//
//
//
//
| 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.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* Unit tests for {@link LocaleUtils}.
*
* @author Chris Hyzer
* @author Stephen Colebourne
* @version $Id$
*/
public class LocaleUtilsTest extends TestCase {
private static final Locale LOCALE_EN = new Locale("en", "");
private static final Locale LOCALE_EN_US = new Locale("en", "US");
private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ");
private static final Locale LOCALE_FR = new Locale("fr", "");
private static final Locale LOCALE_FR_CA = new Locale("fr", "CA");
private static final Locale LOCALE_QQ = new Locale("qq", "");
private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
/**
* Constructor.
*
* @param name
*/
public LocaleUtilsTest(String name) {
super(name);
}
/**
* Main.
* @param args
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* Run the test cases as a suite.
* @return the Test
*/
public static Test suite() {
TestSuite suite = new TestSuite(LocaleUtilsTest.class);
suite.setName("LocaleUtilsTest Tests");
return suite;
}
public void setUp() throws Exception {
super.setUp();
// Testing #LANG-304. Must be called before availableLocaleSet is called.
LocaleUtils.isAvailableLocale(Locale.getDefault());
}
//-----------------------------------------------------------------------
/**
* Test that constructors are public, and work, etc.
*/
public void testConstructor() {
assertNotNull(new LocaleUtils());
Constructor[] cons = LocaleUtils.class.getDeclaredConstructors();
assertEquals(1, cons.length);
assertEquals(true, Modifier.isPublic(cons[0].getModifiers()));
assertEquals(true, Modifier.isPublic(LocaleUtils.class.getModifiers()));
assertEquals(false, Modifier.isFinal(LocaleUtils.class.getModifiers()));
}
//-----------------------------------------------------------------------
/**
* Pass in a valid language, test toLocale.
*
* @param language the language string
*/
private void assertValidToLocale(String language) {
Locale locale = LocaleUtils.toLocale(language);
assertNotNull("valid locale", locale);
assertEquals(language, locale.getLanguage());
//country and variant are empty
assertTrue(locale.getCountry() == null || locale.getCountry().length() == 0);
assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0);
}
/**
* Pass in a valid language, test toLocale.
*
* @param localeString to pass to toLocale()
* @param language of the resulting Locale
* @param country of the resulting Locale
*/
private void assertValidToLocale(String localeString, String language, String country) {
Locale locale = LocaleUtils.toLocale(localeString);
assertNotNull("valid locale", locale);
assertEquals(language, locale.getLanguage());
assertEquals(country, locale.getCountry());
//variant is empty
assertTrue(locale.getVariant() == null || locale.getVariant().length() == 0);
}
/**
* Pass in a valid language, test toLocale.
*
* @param localeString to pass to toLocale()
* @param language of the resulting Locale
* @param country of the resulting Locale
* @param variant of the resulting Locale
*/
private void assertValidToLocale(
String localeString, String language,
String country, String variant) {
Locale locale = LocaleUtils.toLocale(localeString);
assertNotNull("valid locale", locale);
assertEquals(language, locale.getLanguage());
assertEquals(country, locale.getCountry());
assertEquals(variant, locale.getVariant());
}
/**
* Test toLocale() method.
*/
public void testToLocale_1Part() {
assertEquals(null, LocaleUtils.toLocale((String) null));
assertValidToLocale("us");
assertValidToLocale("fr");
assertValidToLocale("de");
assertValidToLocale("zh");
// Valid format but lang doesnt exist, should make instance anyway
assertValidToLocale("qq");
try {
LocaleUtils.toLocale("Us");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("US");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uS");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("u#");
fail("Should fail if not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("u");
fail("Must be 2 chars if less than 5");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uuu");
fail("Must be 2 chars if less than 5");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uu_U");
fail("Must be 2 chars if less than 5");
} catch (IllegalArgumentException iae) {}
}
/**
* Test toLocale() method.
*/
public void testToLocale_2Part() {
assertValidToLocale("us_EN", "us", "EN");
//valid though doesnt exist
assertValidToLocale("us_ZH", "us", "ZH");
try {
LocaleUtils.toLocale("us-EN");
fail("Should fail as not underscore");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_En");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_en");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_eN");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uS_EN");
fail("Should fail first part not lowercase");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_E3");
fail("Should fail second part not uppercase");
} catch (IllegalArgumentException iae) {}
}
/**
* Test toLocale() method.
*/
public void testToLocale_3Part() {
assertValidToLocale("us_EN_A", "us", "EN", "A");
// this isn't pretty, but was caused by a jdk bug it seems
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525
if (SystemUtils.isJavaVersionAtLeast(1.4f)) {
assertValidToLocale("us_EN_a", "us", "EN", "a");
assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF");
} else {
assertValidToLocale("us_EN_a", "us", "EN", "A");
assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF");
}
try {
LocaleUtils.toLocale("us_EN-a");
fail("Should fail as not underscore");
} catch (IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uu_UU_");
fail("Must be 3, 5 or 7+ in length");
} catch (IllegalArgumentException iae) {}
}
//-----------------------------------------------------------------------
/**
* Helper method for local lookups.
*
* @param locale the input locale
* @param defaultLocale the input default locale
* @param expected expected results
*/
private void assertLocaleLookupList(Locale locale, Locale defaultLocale, Locale[] expected) {
List localeList = defaultLocale == null ?
LocaleUtils.localeLookupList(locale) :
LocaleUtils.localeLookupList(locale, defaultLocale);
assertEquals(expected.length, localeList.size());
assertEquals(Arrays.asList(expected), localeList);
assertUnmodifiableCollection(localeList);
}
//-----------------------------------------------------------------------
/**
* Test localeLookupList() method.
*/
public void testLocaleLookupList_Locale() {
assertLocaleLookupList(null, null, new Locale[0]);
assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN});
assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US, null,
new Locale[] {
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN});
}
/**
* Test localeLookupList() method.
*/
public void testLocaleLookupList_LocaleLocale() {
assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ,
new Locale[]{LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN, LOCALE_EN,
new Locale[]{LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US,
new Locale[]{
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ,
new Locale[] {
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ,
new Locale[] {
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ_ZZ});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ});
assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ,
new Locale[] {
LOCALE_EN_US_ZZZZ,
LOCALE_EN_US,
LOCALE_EN,
LOCALE_QQ_ZZ});
assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN,
new Locale[] {
LOCALE_FR_CA,
LOCALE_FR,
LOCALE_EN});
}
//-----------------------------------------------------------------------
/**
* Test availableLocaleList() method.
*/
public void testAvailableLocaleList() {
List list = LocaleUtils.availableLocaleList();
List list2 = LocaleUtils.availableLocaleList();
assertNotNull(list);
assertSame(list, list2);
assertUnmodifiableCollection(list);
Locale[] jdkLocaleArray = Locale.getAvailableLocales();
List jdkLocaleList = Arrays.asList(jdkLocaleArray);
assertEquals(jdkLocaleList, list);
}
//-----------------------------------------------------------------------
/**
* Test availableLocaleSet() method.
*/
public void testAvailableLocaleSet() {
Set set = LocaleUtils.availableLocaleSet();
Set set2 = LocaleUtils.availableLocaleSet();
assertNotNull(set);
assertSame(set, set2);
assertUnmodifiableCollection(set);
Locale[] jdkLocaleArray = Locale.getAvailableLocales();
List jdkLocaleList = Arrays.asList(jdkLocaleArray);
Set jdkLocaleSet = new HashSet(jdkLocaleList);
assertEquals(jdkLocaleSet, set);
}
//-----------------------------------------------------------------------
/**
* Test availableLocaleSet() method.
*/
public void testIsAvailableLocale() {
Set set = LocaleUtils.availableLocaleSet();
assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN));
assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US));
assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ));
assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR));
assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA));
assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ));
assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ));
}
//-----------------------------------------------------------------------
/**
* Make sure the language by country is correct.
*
* @param country
* @param languages array of languages that should be returned
*/
private void assertLanguageByCountry(String country, String[] languages) {
List list = LocaleUtils.languagesByCountry(country);
List list2 = LocaleUtils.languagesByCountry(country);
assertNotNull(list);
assertSame(list, list2);
assertEquals(languages.length, list.size());
//search through langauges
for (int i = 0; i < languages.length; i++) {
Iterator iterator = list.iterator();
boolean found = false;
// see if it was returned by the set
while (iterator.hasNext()) {
Locale locale = (Locale) iterator.next();
// should have an en empty variant
assertTrue(locale.getVariant() == null
|| locale.getVariant().length() == 0);
assertEquals(country, locale.getCountry());
if (languages[i].equals(locale.getLanguage())) {
found = true;
break;
}
}
if (!found) {
fail("Cound not find language: " + languages[i]
+ " for country: " + country);
}
}
assertUnmodifiableCollection(list);
}
/**
* Test languagesByCountry() method.
*/
public void testLanguagesByCountry() {
assertLanguageByCountry(null, new String[0]);
assertLanguageByCountry("GB", new String[]{"en"});
assertLanguageByCountry("ZZ", new String[0]);
assertLanguageByCountry("CH", new String[]{"fr", "de", "it"});
}
//-----------------------------------------------------------------------
/**
* Make sure the language by country is correct.
*
* @param language
* @param countries array of countries that should be returned
*/
private void assertCountriesByLanguage(String language, String[] countries) {
List list = LocaleUtils.countriesByLanguage(language);
List list2 = LocaleUtils.countriesByLanguage(language);
assertNotNull(list);
assertSame(list, list2);
assertEquals(countries.length, list.size());
//search through langauges
for (int i = 0; i < countries.length; i++) {
Iterator iterator = list.iterator();
boolean found = false;
// see if it was returned by the set
while (iterator.hasNext()) {
Locale locale = (Locale) iterator.next();
// should have an en empty variant
assertTrue(locale.getVariant() == null
|| locale.getVariant().length() == 0);
assertEquals(language, locale.getLanguage());
if (countries[i].equals(locale.getCountry())) {
found = true;
break;
}
}
if (!found) {
fail("Cound not find language: " + countries[i]
+ " for country: " + language);
}
}
assertUnmodifiableCollection(list);
}
/**
* Test languagesByCountry() method.
*/
public void testCountriesByLanguage() {}
// Defects4J: flaky method
// public void testCountriesByLanguage() {
// assertCountriesByLanguage(null, new String[0]);
// assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"});
// assertCountriesByLanguage("zz", new String[0]);
// assertCountriesByLanguage("it", new String[]{"IT", "CH"});
// }
/**
* @param coll the collection to check
*/
private static void assertUnmodifiableCollection(Collection coll) {
try {
coll.add("Unmodifiable");
fail();
} catch (UnsupportedOperationException ex) {}
}
} |
|
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");
} | com.google.javascript.jscomp.parsing.ParserTest::testForEach | test/com/google/javascript/jscomp/parsing/ParserTest.java | 971 | test/com/google/javascript/jscomp/parsing/ParserTest.java | testForEach | /*
* 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.ScriptRuntime.getMessage0(
"msg.jsdoc.missing.gt");
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(2, 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.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.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();
// ASSIGN
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 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.setIsSyntheticBlock(true);
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 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));",
"missing ) in parenthetical");
}
public void testGettersForbidden1() {
parseError("var x = {get foo() { return 3; }};",
"getters are not supported in Internet Explorer");
}
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; }};",
"getters are not supported in Internet Explorer");
}
public void testSettersForbidden() {
parseError("var x = {set foo() { return 3; }};",
"setters are not supported in Internet Explorer");
}
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, 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(){}};",
"getters are not supported in Internet Explorer");
parseError("var x = {get 'a'(){}};",
"getters are not supported in Internet Explorer");
parseError("var x = {get a(){}};",
"getters are not supported in Internet Explorer");
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){}};",
"setters are not supported in Internet Explorer");
parseError("var x = {set 'a'(x){}};",
"setters are not supported in Internet Explorer");
parseError("var x = {set a(x){}};",
"setters are not supported in Internet Explorer");
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() {
boolean isIdeMode = false;
mode = LanguageMode.ECMASCRIPT3;
parseError("var boolean;", "missing variable name");
parseError("function boolean() {};",
"missing ( before function parameters.");
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() {
boolean isIdeMode = false;
mode = LanguageMode.ECMASCRIPT3;
parseError("var x = {function: 1};", "invalid property id");
parseError("x.function;", "missing name after . operator");
parseError("var x = {get x(){} };",
"getters are not supported in Internet Explorer");
parseError("var x = {get function(){} };", "invalid property id");
parseError("var x = {get 'function'(){} };",
"getters are not supported in Internet Explorer");
parseError("var x = {get 1(){} };",
"getters are not supported in Internet Explorer");
parseError("var x = {set function(a){} };", "invalid property id");
parseError("var x = {set 'function'(a){} };",
"setters are not supported in Internet Explorer");
parseError("var x = {set 1(a){} };",
"setters are not supported in Internet Explorer");
parseError("var x = {class: 1};", "invalid property id");
parseError("x.class;", "missing name after . operator");
parse("var x = {let: 1};");
parse("x.let;");
parse("var x = {yield: 1};");
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",
"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",
"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");
}
/**
* 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());
} 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());
} 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 `testForEach` for the issue `Closure-644`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-644
//
// ## Issue-Title:
// Simple "Whitespace only" compression removing "each" keyword from "for each (var x in arr)" loop
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// See below code snippet before after compression
//
// ---Before---
// contactcenter.screenpop.updatePopStatus = function(stamp, status) {
// for each ( var curTiming in this.timeLog.timings ) {
// if ( curTiming.callId == stamp ) {
// curTiming.flag = status;
// break;
// }
// }
// };
// ---After---
// contactcenter.screenpop.updatePopStatus=function(stamp,status){for(var curTiming in this.timeLog.timings)if(curTiming.callId==stamp){curTiming.flag=status;break}};
//
//
// **What is the expected output? What do you see instead?**
// ---each keyword should be preserved
//
// **What version of the product are you using? On what operating system?**
// **Please provide any additional information below.**
// for each (\*\* in \*\*) ---> returns object value
// for (\*\* in \*\*) --> returns index
//
//
public void testForEach() {
| 971 | 42 | 960 | test/com/google/javascript/jscomp/parsing/ParserTest.java | test | ```markdown
## Issue-ID: Closure-644
## Issue-Title:
Simple "Whitespace only" compression removing "each" keyword from "for each (var x in arr)" loop
## Issue-Description:
**What steps will reproduce the problem?**
See below code snippet before after compression
---Before---
contactcenter.screenpop.updatePopStatus = function(stamp, status) {
for each ( var curTiming in this.timeLog.timings ) {
if ( curTiming.callId == stamp ) {
curTiming.flag = status;
break;
}
}
};
---After---
contactcenter.screenpop.updatePopStatus=function(stamp,status){for(var curTiming in this.timeLog.timings)if(curTiming.callId==stamp){curTiming.flag=status;break}};
**What is the expected output? What do you see instead?**
---each keyword should be preserved
**What version of the product are you using? On what operating system?**
**Please provide any additional information below.**
for each (\*\* in \*\*) ---> returns object value
for (\*\* in \*\*) --> returns index
```
You are a professional Java test case writer, please create a test case named `testForEach` for the issue `Closure-644`, utilizing the provided issue report information and the following function signature.
```java
public void testForEach() {
```
| 960 | [
"com.google.javascript.jscomp.parsing.IRFactory"
] | 5c9935843a0ced814d855a017f06eaddbede7c05c3554c2b9ef6b33b4d4cecd0 | public void testForEach() | // You are a professional Java test case writer, please create a test case named `testForEach` for the issue `Closure-644`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-644
//
// ## Issue-Title:
// Simple "Whitespace only" compression removing "each" keyword from "for each (var x in arr)" loop
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// See below code snippet before after compression
//
// ---Before---
// contactcenter.screenpop.updatePopStatus = function(stamp, status) {
// for each ( var curTiming in this.timeLog.timings ) {
// if ( curTiming.callId == stamp ) {
// curTiming.flag = status;
// break;
// }
// }
// };
// ---After---
// contactcenter.screenpop.updatePopStatus=function(stamp,status){for(var curTiming in this.timeLog.timings)if(curTiming.callId==stamp){curTiming.flag=status;break}};
//
//
// **What is the expected output? What do you see instead?**
// ---each keyword should be preserved
//
// **What version of the product are you using? On what operating system?**
// **Please provide any additional information below.**
// for each (\*\* in \*\*) ---> returns object value
// for (\*\* in \*\*) --> returns index
//
//
| 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.ScriptRuntime.getMessage0(
"msg.jsdoc.missing.gt");
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(2, 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.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.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();
// ASSIGN
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 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.setIsSyntheticBlock(true);
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 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));",
"missing ) in parenthetical");
}
public void testGettersForbidden1() {
parseError("var x = {get foo() { return 3; }};",
"getters are not supported in Internet Explorer");
}
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; }};",
"getters are not supported in Internet Explorer");
}
public void testSettersForbidden() {
parseError("var x = {set foo() { return 3; }};",
"setters are not supported in Internet Explorer");
}
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, 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(){}};",
"getters are not supported in Internet Explorer");
parseError("var x = {get 'a'(){}};",
"getters are not supported in Internet Explorer");
parseError("var x = {get a(){}};",
"getters are not supported in Internet Explorer");
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){}};",
"setters are not supported in Internet Explorer");
parseError("var x = {set 'a'(x){}};",
"setters are not supported in Internet Explorer");
parseError("var x = {set a(x){}};",
"setters are not supported in Internet Explorer");
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() {
boolean isIdeMode = false;
mode = LanguageMode.ECMASCRIPT3;
parseError("var boolean;", "missing variable name");
parseError("function boolean() {};",
"missing ( before function parameters.");
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() {
boolean isIdeMode = false;
mode = LanguageMode.ECMASCRIPT3;
parseError("var x = {function: 1};", "invalid property id");
parseError("x.function;", "missing name after . operator");
parseError("var x = {get x(){} };",
"getters are not supported in Internet Explorer");
parseError("var x = {get function(){} };", "invalid property id");
parseError("var x = {get 'function'(){} };",
"getters are not supported in Internet Explorer");
parseError("var x = {get 1(){} };",
"getters are not supported in Internet Explorer");
parseError("var x = {set function(a){} };", "invalid property id");
parseError("var x = {set 'function'(a){} };",
"setters are not supported in Internet Explorer");
parseError("var x = {set 1(a){} };",
"setters are not supported in Internet Explorer");
parseError("var x = {class: 1};", "invalid property id");
parseError("x.class;", "missing name after . operator");
parse("var x = {let: 1};");
parse("x.let;");
parse("var x = {yield: 1};");
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",
"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",
"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");
}
/**
* 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());
} 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());
} 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 testIZeroIndex() throws Exception
{
JsonPointer ptr = JsonPointer.compile("/0");
assertEquals(0, ptr.getMatchingIndex());
ptr = JsonPointer.compile("/00");
assertEquals(-1, ptr.getMatchingIndex());
} | com.fasterxml.jackson.core.TestJsonPointer::testIZeroIndex | src/test/java/com/fasterxml/jackson/core/TestJsonPointer.java | 51 | src/test/java/com/fasterxml/jackson/core/TestJsonPointer.java | testIZeroIndex | package com.fasterxml.jackson.core;
import com.fasterxml.jackson.test.BaseTest;
public class TestJsonPointer extends BaseTest
{
public void testSimplePath() throws Exception
{
final String INPUT = "/Image/15/name";
JsonPointer ptr = JsonPointer.compile(INPUT);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("Image", ptr.getMatchingProperty());
assertEquals(INPUT, ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(15, ptr.getMatchingIndex());
assertEquals("15", ptr.getMatchingProperty());
assertEquals("/15/name", ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("name", ptr.getMatchingProperty());
assertEquals("/name", ptr.toString());
// done!
ptr = ptr.tail();
assertTrue(ptr.matches());
assertNull(ptr.tail());
assertEquals("", ptr.getMatchingProperty());
assertEquals(-1, ptr.getMatchingIndex());
}
public void testWonkyNumber173() throws Exception
{
JsonPointer ptr = JsonPointer.compile("/1e0");
assertFalse(ptr.matches());
}
// [core#176]: do not allow leading zeroes
public void testIZeroIndex() throws Exception
{
JsonPointer ptr = JsonPointer.compile("/0");
assertEquals(0, ptr.getMatchingIndex());
ptr = JsonPointer.compile("/00");
assertEquals(-1, ptr.getMatchingIndex());
}
public void testQuotedPath() throws Exception
{
final String INPUT = "/w~1out/til~0de/a~1b";
JsonPointer ptr = JsonPointer.compile(INPUT);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("w/out", ptr.getMatchingProperty());
assertEquals(INPUT, ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("til~de", ptr.getMatchingProperty());
assertEquals("/til~0de/a~1b", ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("a/b", ptr.getMatchingProperty());
assertEquals("/a~1b", ptr.toString());
// done!
ptr = ptr.tail();
assertTrue(ptr.matches());
assertNull(ptr.tail());
}
// [Issue#133]
public void testLongNumbers() throws Exception
{
final long LONG_ID = ((long) Integer.MAX_VALUE) + 1L;
final String INPUT = "/User/"+LONG_ID;
JsonPointer ptr = JsonPointer.compile(INPUT);
assertEquals("User", ptr.getMatchingProperty());
assertEquals(INPUT, ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
/* 14-Mar-2014, tatu: We do not support array indexes beyond 32-bit
* range; can still match textually of course.
*/
assertEquals(-1, ptr.getMatchingIndex());
assertEquals(String.valueOf(LONG_ID), ptr.getMatchingProperty());
// done!
ptr = ptr.tail();
assertTrue(ptr.matches());
assertNull(ptr.tail());
}
} | // You are a professional Java test case writer, please create a test case named `testIZeroIndex` for the issue `JacksonCore-176`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonCore-176
//
// ## Issue-Title:
// JsonPointer should not consider "00" to be valid index
//
// ## Issue-Description:
// Although `00` can be parsed as `0` in some cases, it is not a valid JSON number; and is also not legal numeric index for JSON Pointer. As such, `JsonPointer` class should ensure it can only match property name "00" and not array index.
//
//
//
//
public void testIZeroIndex() throws Exception {
| 51 | // [core#176]: do not allow leading zeroes | 6 | 45 | src/test/java/com/fasterxml/jackson/core/TestJsonPointer.java | src/test/java | ```markdown
## Issue-ID: JacksonCore-176
## Issue-Title:
JsonPointer should not consider "00" to be valid index
## Issue-Description:
Although `00` can be parsed as `0` in some cases, it is not a valid JSON number; and is also not legal numeric index for JSON Pointer. As such, `JsonPointer` class should ensure it can only match property name "00" and not array index.
```
You are a professional Java test case writer, please create a test case named `testIZeroIndex` for the issue `JacksonCore-176`, utilizing the provided issue report information and the following function signature.
```java
public void testIZeroIndex() throws Exception {
```
| 45 | [
"com.fasterxml.jackson.core.JsonPointer"
] | 5cc33ae3000157d8d842d50c1fcda83cc9bbcb0360b3a03361baf7c5d1d0b506 | public void testIZeroIndex() throws Exception
| // You are a professional Java test case writer, please create a test case named `testIZeroIndex` for the issue `JacksonCore-176`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonCore-176
//
// ## Issue-Title:
// JsonPointer should not consider "00" to be valid index
//
// ## Issue-Description:
// Although `00` can be parsed as `0` in some cases, it is not a valid JSON number; and is also not legal numeric index for JSON Pointer. As such, `JsonPointer` class should ensure it can only match property name "00" and not array index.
//
//
//
//
| JacksonCore | package com.fasterxml.jackson.core;
import com.fasterxml.jackson.test.BaseTest;
public class TestJsonPointer extends BaseTest
{
public void testSimplePath() throws Exception
{
final String INPUT = "/Image/15/name";
JsonPointer ptr = JsonPointer.compile(INPUT);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("Image", ptr.getMatchingProperty());
assertEquals(INPUT, ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(15, ptr.getMatchingIndex());
assertEquals("15", ptr.getMatchingProperty());
assertEquals("/15/name", ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("name", ptr.getMatchingProperty());
assertEquals("/name", ptr.toString());
// done!
ptr = ptr.tail();
assertTrue(ptr.matches());
assertNull(ptr.tail());
assertEquals("", ptr.getMatchingProperty());
assertEquals(-1, ptr.getMatchingIndex());
}
public void testWonkyNumber173() throws Exception
{
JsonPointer ptr = JsonPointer.compile("/1e0");
assertFalse(ptr.matches());
}
// [core#176]: do not allow leading zeroes
public void testIZeroIndex() throws Exception
{
JsonPointer ptr = JsonPointer.compile("/0");
assertEquals(0, ptr.getMatchingIndex());
ptr = JsonPointer.compile("/00");
assertEquals(-1, ptr.getMatchingIndex());
}
public void testQuotedPath() throws Exception
{
final String INPUT = "/w~1out/til~0de/a~1b";
JsonPointer ptr = JsonPointer.compile(INPUT);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("w/out", ptr.getMatchingProperty());
assertEquals(INPUT, ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("til~de", ptr.getMatchingProperty());
assertEquals("/til~0de/a~1b", ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
assertEquals(-1, ptr.getMatchingIndex());
assertEquals("a/b", ptr.getMatchingProperty());
assertEquals("/a~1b", ptr.toString());
// done!
ptr = ptr.tail();
assertTrue(ptr.matches());
assertNull(ptr.tail());
}
// [Issue#133]
public void testLongNumbers() throws Exception
{
final long LONG_ID = ((long) Integer.MAX_VALUE) + 1L;
final String INPUT = "/User/"+LONG_ID;
JsonPointer ptr = JsonPointer.compile(INPUT);
assertEquals("User", ptr.getMatchingProperty());
assertEquals(INPUT, ptr.toString());
ptr = ptr.tail();
assertNotNull(ptr);
assertFalse(ptr.matches());
/* 14-Mar-2014, tatu: We do not support array indexes beyond 32-bit
* range; can still match textually of course.
*/
assertEquals(-1, ptr.getMatchingIndex());
assertEquals(String.valueOf(LONG_ID), ptr.getMatchingProperty());
// done!
ptr = ptr.tail();
assertTrue(ptr.matches());
assertNull(ptr.tail());
}
} |
|
public void testInnerEmptyNamespaceDOM() {
doTest("b:foo/test", DocumentContainer.MODEL_DOM, "/b:foo[1]/test[1]");
} | org.apache.commons.jxpath.ri.model.JXPath154Test::testInnerEmptyNamespaceDOM | src/test/org/apache/commons/jxpath/ri/model/JXPath154Test.java | 21 | src/test/org/apache/commons/jxpath/ri/model/JXPath154Test.java | testInnerEmptyNamespaceDOM | package org.apache.commons.jxpath.ri.model;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.xml.DocumentContainer;
public class JXPath154Test extends JXPathTestCase {
protected JXPathContext context;
protected DocumentContainer createDocumentContainer(String model) {
return new DocumentContainer(JXPathTestCase.class.getResource("InnerEmptyNamespace.xml"), model);
}
protected void doTest(String path, String model, String expectedValue) {
JXPathContext context = JXPathContext.newContext(createDocumentContainer(model));
assertEquals(expectedValue, context.getPointer(path).asPath());
}
public void testInnerEmptyNamespaceDOM() {
doTest("b:foo/test", DocumentContainer.MODEL_DOM, "/b:foo[1]/test[1]");
}
public void testInnerEmptyNamespaceJDOM() {
doTest("b:foo/test", DocumentContainer.MODEL_JDOM, "/b:foo[1]/test[1]");
}
} | // You are a professional Java test case writer, please create a test case named `testInnerEmptyNamespaceDOM` for the issue `JxPath-JXPATH-154`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-154
//
// ## Issue-Title:
// Resetting the default namespace causes a serious endless loop when requesting .asPath() on a node.
//
// ## Issue-Description:
//
// sample smaller case:
//
//
//
//
// ```
// <...>
// <b:foo xmlns:b="bla" xmlns="test111"> <!-- No nodes are placed in the tree within ns "test111" but the attribute is still there.-->
// <b:bar>a</b:bar> <!-- is in ns 'bla' -->
// <test xmlns=""></test> <!-- does not have a namespace -->
// </b:foo>
// </...>
//
// ```
//
//
// when requesting .asPath() on the 'test' node, it loops in org.apache.commons.jxpath.ri.NamespaceResolver.getPrefix(NodePointer, String),
//
// and if it didn't loop it would create a wrong xpath '//b:fo/null:test' DOMNodePointer.asPath().
//
//
// So I think that the fix should be in org.apache.commons.jxpath.ri.model.dom.DOMNodePointer.asPath()
//
//
//
//
// ```
// ....
// String ln = DOMNodePointer.getLocalName(node);
// String nsURI = getNamespaceURI();
// if (nsURI == null) {
// buffer.append(ln);
// buffer.append('[');
// buffer.append(getRelativePositionByName()).append(']');
// }
// else {
// String prefix = getNamespaceResolver().getPrefix(nsURI);
// if (prefix != null) {
// ...
//
// ```
//
//
// should become
//
//
//
//
// ```
// ...
// String ln = DOMNodePointer.getLocalName(node);
// String nsURI = getNamespaceURI();
// if (nsURI == null || nsURI.length() == 0) { // check for empty string which means that the node doesn't have a namespace.
// buffer.append(ln);
// buffer.append('[');
// buffer.append(getRelativePositionByName()).append(']');
// }
// else {
// String prefix = getNamespaceResolver().getPrefix(nsURI);
// if (prefix != null) {
// ...
//
// ```
//
//
//
//
//
public void testInnerEmptyNamespaceDOM() {
| 21 | 22 | 19 | src/test/org/apache/commons/jxpath/ri/model/JXPath154Test.java | src/test | ```markdown
## Issue-ID: JxPath-JXPATH-154
## Issue-Title:
Resetting the default namespace causes a serious endless loop when requesting .asPath() on a node.
## Issue-Description:
sample smaller case:
```
<...>
<b:foo xmlns:b="bla" xmlns="test111"> <!-- No nodes are placed in the tree within ns "test111" but the attribute is still there.-->
<b:bar>a</b:bar> <!-- is in ns 'bla' -->
<test xmlns=""></test> <!-- does not have a namespace -->
</b:foo>
</...>
```
when requesting .asPath() on the 'test' node, it loops in org.apache.commons.jxpath.ri.NamespaceResolver.getPrefix(NodePointer, String),
and if it didn't loop it would create a wrong xpath '//b:fo/null:test' DOMNodePointer.asPath().
So I think that the fix should be in org.apache.commons.jxpath.ri.model.dom.DOMNodePointer.asPath()
```
....
String ln = DOMNodePointer.getLocalName(node);
String nsURI = getNamespaceURI();
if (nsURI == null) {
buffer.append(ln);
buffer.append('[');
buffer.append(getRelativePositionByName()).append(']');
}
else {
String prefix = getNamespaceResolver().getPrefix(nsURI);
if (prefix != null) {
...
```
should become
```
...
String ln = DOMNodePointer.getLocalName(node);
String nsURI = getNamespaceURI();
if (nsURI == null || nsURI.length() == 0) { // check for empty string which means that the node doesn't have a namespace.
buffer.append(ln);
buffer.append('[');
buffer.append(getRelativePositionByName()).append(']');
}
else {
String prefix = getNamespaceResolver().getPrefix(nsURI);
if (prefix != null) {
...
```
```
You are a professional Java test case writer, please create a test case named `testInnerEmptyNamespaceDOM` for the issue `JxPath-JXPATH-154`, utilizing the provided issue report information and the following function signature.
```java
public void testInnerEmptyNamespaceDOM() {
```
| 19 | [
"org.apache.commons.jxpath.ri.model.dom.DOMNodePointer"
] | 5cc80324cf641b69b64f67e90e9aa205c5a45de20400f8117221e4a8a4b9836c | public void testInnerEmptyNamespaceDOM() | // You are a professional Java test case writer, please create a test case named `testInnerEmptyNamespaceDOM` for the issue `JxPath-JXPATH-154`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-154
//
// ## Issue-Title:
// Resetting the default namespace causes a serious endless loop when requesting .asPath() on a node.
//
// ## Issue-Description:
//
// sample smaller case:
//
//
//
//
// ```
// <...>
// <b:foo xmlns:b="bla" xmlns="test111"> <!-- No nodes are placed in the tree within ns "test111" but the attribute is still there.-->
// <b:bar>a</b:bar> <!-- is in ns 'bla' -->
// <test xmlns=""></test> <!-- does not have a namespace -->
// </b:foo>
// </...>
//
// ```
//
//
// when requesting .asPath() on the 'test' node, it loops in org.apache.commons.jxpath.ri.NamespaceResolver.getPrefix(NodePointer, String),
//
// and if it didn't loop it would create a wrong xpath '//b:fo/null:test' DOMNodePointer.asPath().
//
//
// So I think that the fix should be in org.apache.commons.jxpath.ri.model.dom.DOMNodePointer.asPath()
//
//
//
//
// ```
// ....
// String ln = DOMNodePointer.getLocalName(node);
// String nsURI = getNamespaceURI();
// if (nsURI == null) {
// buffer.append(ln);
// buffer.append('[');
// buffer.append(getRelativePositionByName()).append(']');
// }
// else {
// String prefix = getNamespaceResolver().getPrefix(nsURI);
// if (prefix != null) {
// ...
//
// ```
//
//
// should become
//
//
//
//
// ```
// ...
// String ln = DOMNodePointer.getLocalName(node);
// String nsURI = getNamespaceURI();
// if (nsURI == null || nsURI.length() == 0) { // check for empty string which means that the node doesn't have a namespace.
// buffer.append(ln);
// buffer.append('[');
// buffer.append(getRelativePositionByName()).append(']');
// }
// else {
// String prefix = getNamespaceResolver().getPrefix(nsURI);
// if (prefix != null) {
// ...
//
// ```
//
//
//
//
//
| JxPath | package org.apache.commons.jxpath.ri.model;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.xml.DocumentContainer;
public class JXPath154Test extends JXPathTestCase {
protected JXPathContext context;
protected DocumentContainer createDocumentContainer(String model) {
return new DocumentContainer(JXPathTestCase.class.getResource("InnerEmptyNamespace.xml"), model);
}
protected void doTest(String path, String model, String expectedValue) {
JXPathContext context = JXPathContext.newContext(createDocumentContainer(model));
assertEquals(expectedValue, context.getPointer(path).asPath());
}
public void testInnerEmptyNamespaceDOM() {
doTest("b:foo/test", DocumentContainer.MODEL_DOM, "/b:foo[1]/test[1]");
}
public void testInnerEmptyNamespaceJDOM() {
doTest("b:foo/test", DocumentContainer.MODEL_JDOM, "/b:foo[1]/test[1]");
}
} |
||
public void testNoPrivateAccessForProperties6() {
// Overriding a private property with a non-private property
// in a different file causes problems.
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.bar_ = function() {};"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
} | com.google.javascript.jscomp.CheckAccessControlsTest::testNoPrivateAccessForProperties6 | test/com/google/javascript/jscomp/CheckAccessControlsTest.java | 408 | test/com/google/javascript/jscomp/CheckAccessControlsTest.java | testNoPrivateAccessForProperties6 | /*
* 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;
import static com.google.javascript.jscomp.CheckAccessControls.BAD_PRIVATE_GLOBAL_ACCESS;
import static com.google.javascript.jscomp.CheckAccessControls.BAD_PRIVATE_PROPERTY_ACCESS;
import static com.google.javascript.jscomp.CheckAccessControls.BAD_PROTECTED_PROPERTY_ACCESS;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_CLASS;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_CLASS_REASON;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_NAME;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_NAME_REASON;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_PROP;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_PROP_REASON;
import static com.google.javascript.jscomp.CheckAccessControls.PRIVATE_OVERRIDE;
import static com.google.javascript.jscomp.CheckAccessControls.VISIBILITY_MISMATCH;
import static com.google.javascript.jscomp.CheckAccessControls.CONST_PROPERTY_REASSIGNED_VALUE;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CompilerOptions;
/**
* Tests for {@link CheckAccessControls}.
*
* @author nicksantos@google.com (Nick Santos)
*/
public class CheckAccessControlsTest extends CompilerTestCase {
public CheckAccessControlsTest() {
parseTypeInfo = true;
enableTypeCheck(CheckLevel.WARNING);
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
return new CheckAccessControls(compiler);
}
@Override
protected CompilerOptions getOptions() {
CompilerOptions options = super.getOptions();
options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS, CheckLevel.ERROR);
options.setWarningLevel(DiagnosticGroups.CONSTANT_PROPERTY,
CheckLevel.ERROR);
return options;
}
/**
* Tests that the given Javascript code has a @deprecated marker
* somewhere in it which raises an error. Also tests that the
* deprecated marker works with a message. The Javascript should
* have a JsDoc of the form "@deprecated %s\n".
*
* @param js The Javascript code to parse and test.
* @param reason A simple deprecation reason string, used for testing
* the addition of a deprecation reason to the @deprecated tag.
* @param error The deprecation error expected when no reason is given.
* @param errorWithMessage The deprecation error expected when a reason
* message is given.
*/
private void testDep(String js, String reason,
DiagnosticType error,
DiagnosticType errorWithMessage) {
// Test without a reason.
test(String.format(js, ""), null, error);
// Test with a reason.
test(String.format(js, reason), null, errorWithMessage, null, reason);
}
public void testDeprecatedFunction() {
testDep("/** @deprecated %s */ function f() {} function g() { f(); }",
"Some Reason",
DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testWarningOnDeprecatedConstVariable() {
testDep("/** @deprecated %s */ var f = 4; function g() { alert(f); }",
"Another reason",
DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testThatNumbersArentDeprecated() {
testSame("/** @deprecated */ var f = 4; var h = 3; " +
"function g() { alert(h); }");
}
public void testDeprecatedFunctionVariable() {
testDep("/** @deprecated %s */ var f = function() {}; " +
"function g() { f(); }", "I like g...",
DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testNoWarningInGlobalScope() {
testSame("var goog = {}; goog.makeSingleton = function(x) {};" +
"/** @deprecated */ function f() {} goog.makeSingleton(f);");
}
public void testNoWarningInGlobalScopeForCall() {
testDep("/** @deprecated %s */ function f() {} f();",
"Some global scope", DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testNoWarningInDeprecatedFunction() {
testSame("/** @deprecated */ function f() {} " +
"/** @deprecated */ function g() { f(); }");
}
public void testWarningInNormalClass() {
testDep("/** @deprecated %s */ function f() {}" +
"/** @constructor */ var Foo = function() {}; " +
"Foo.prototype.bar = function() { f(); }",
"FooBar", DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testWarningForProperty1() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert((new Foo()).bar); };",
"A property is bad",
DEPRECATED_PROP, DEPRECATED_PROP_REASON);
}
public void testWarningForProperty2() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert(this.bar); };",
"Zee prop, it is deprecated!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForDeprecatedClass() {
testDep("/** @constructor \n* @deprecated %s */ function Foo() {} " +
"function f() { new Foo(); }",
"Use the class 'Bar'",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testNoWarningForDeprecatedClassInstance() {
testSame("/** @constructor \n * @deprecated */ function Foo() {} " +
"/** @param {Foo} x */ function f(x) { return x; }");
}
public void testWarningForDeprecatedSuperClass() {
testDep("/** @constructor \n * @deprecated %s */ function Foo() {} " +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"function f() { new SubFoo(); }",
"Superclass to the rescue!",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testWarningForDeprecatedSuperClass2() {
testDep("/** @constructor \n * @deprecated %s */ function Foo() {} " +
"var namespace = {}; " +
"/** @constructor \n * @extends {Foo} */ " +
"namespace.SubFoo = function() {}; " +
"function f() { new namespace.SubFoo(); }",
"Its only weakness is Kryptoclass",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testWarningForPrototypeProperty() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert(Foo.prototype.bar); };",
"It is now in production, use that model...",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testNoWarningForNumbers() {
testSame("/** @constructor */ function Foo() {}" +
"/** @deprecated */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert(3); };");
}
public void testWarningForMethod1() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = function() {};" +
"Foo.prototype.baz = function() { this.bar(); };",
"There is a madness to this method",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForMethod2() {
testDep("/** @constructor */ function Foo() {} " +
"/** @deprecated %s */ Foo.prototype.bar; " +
"Foo.prototype.baz = function() { this.bar(); };",
"Stop the ringing!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testNoWarningInDeprecatedClass() {
testSame("/** @deprecated */ function f() {} " +
"/** @constructor \n * @deprecated */ " +
"var Foo = function() {}; " +
"Foo.prototype.bar = function() { f(); }");
}
public void testNoWarningInDeprecatedClass2() {
testSame("/** @deprecated */ function f() {} " +
"/** @constructor \n * @deprecated */ " +
"var Foo = function() {}; " +
"Foo.bar = function() { f(); }");
}
public void testNoWarningInDeprecatedStaticMethod() {
testSame("/** @deprecated */ function f() {} " +
"/** @constructor */ " +
"var Foo = function() {}; " +
"/** @deprecated */ Foo.bar = function() { f(); }");
}
public void testWarningInStaticMethod() {
testDep("/** @deprecated %s */ function f() {} " +
"/** @constructor */ " +
"var Foo = function() {}; " +
"Foo.bar = function() { f(); }",
"crazy!",
DEPRECATED_NAME,
DEPRECATED_NAME_REASON);
}
public void testDeprecatedObjLitKey() {
testDep("var f = {}; /** @deprecated %s */ f.foo = 3; " +
"function g() { return f.foo; }",
"It is literally not used anymore",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForSubclassMethod() {
testDep("/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"/** @deprecated %s */ SubFoo.prototype.bar = function() {};" +
"function f() { (new SubFoo()).bar(); };",
"I have a parent class!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForSuperClassWithDeprecatedSubclassMethod() {
testSame("/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"/** @deprecated \n * @override */ SubFoo.prototype.bar = " +
"function() {};" +
"function f() { (new Foo()).bar(); };");
}
public void testWarningForSuperclassMethod() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"SubFoo.prototype.bar = function() {};" +
"function f() { (new SubFoo()).bar(); };",
"I have a child class!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForSuperclassMethod2() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s \n* @protected */" +
"Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"/** @protected */SubFoo.prototype.bar = function() {};" +
"function f() { (new SubFoo()).bar(); };",
"I have another child class...",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForBind() {
testDep("/** @deprecated %s */ Function.prototype.bind = function() {};" +
"(function() {}).bind();",
"I'm bound to this method...",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForDeprecatedClassInGlobalScope() {
testDep("/** @constructor \n * @deprecated %s */ var Foo = function() {};" +
"new Foo();",
"I'm a very worldly object!",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testNoWarningForPrototypeCopying() {
testSame("/** @constructor */ var Foo = function() {};" +
"Foo.prototype.bar = function() {};" +
"/** @deprecated */ Foo.prototype.baz = Foo.prototype.bar;" +
"(new Foo()).bar();");
}
public void testNoWarningOnDeprecatedPrototype() {
// This used to cause an NPE.
testSame("/** @constructor */ var Foo = function() {};" +
"/** @deprecated */ Foo.prototype = {};" +
"Foo.prototype.bar = function() {};");
}
public void testPrivateAccessForNames() {
testSame("/** @private */ function foo_() {}; foo_();");
test(new String[] {
"/** @private */ function foo_() {};",
"foo_();"
}, null, BAD_PRIVATE_GLOBAL_ACCESS);
}
public void testPrivateAccessForProperties1() {
testSame("/** @constructor */ function Foo() {}" +
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); }; (new Foo).bar_();");
}
public void testPrivateAccessForProperties2() {
testSame(new String[] {
"/** @constructor */ function Foo() {}",
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); }; (new Foo).bar_();"
});
}
public void testPrivateAccessForProperties3() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @private */ Foo.prototype.bar_ = function() {}; (new Foo).bar_();",
"Foo.prototype.baz = function() { this.bar_(); };"
});
}
public void testNoPrivateAccessForProperties1() {
test(new String[] {
"/** @constructor */ function Foo() {} (new Foo).bar_();",
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); };"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties2() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); };",
"(new Foo).bar_();"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties3() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor */ function OtherFoo() { (new Foo).bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties4() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() { this.bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties5() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.baz = function() { this.bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties6() {
// Overriding a private property with a non-private property
// in a different file causes problems.
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.bar_ = function() {};"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties7() {
// It's ok to override a private property with a non-private property
// in the same file, but you'll get yelled at when you try to use it.
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};" +
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.bar_ = function() {};",
"SubFoo.prototype.baz = function() { this.bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties8() {
test(new String[] {
"/** @constructor */ function Foo() { /** @private */ this.bar_ = 3; }",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() { /** @private */ this.bar_ = 3; };"
}, null, PRIVATE_OVERRIDE);
}
public void testProtectedAccessForProperties1() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"Foo.prototype.baz = function() { this.bar(); };"
});
}
public void testProtectedAccessForProperties2() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"/** @constructor \n * @extends {Foo} */" +
"function SubFoo() { this.bar(); }"
});
}
public void testProtectedAccessForProperties3() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"/** @constructor \n * @extends {Foo} */" +
"function SubFoo() { }" +
"SubFoo.baz = function() { (new Foo).bar(); }"
});
}
public void testProtectedAccessForProperties4() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.bar = function() {};",
"/** @constructor \n * @extends {Foo} */" +
"function SubFoo() { Foo.bar(); }"
});
}
public void testProtectedAccessForProperties5() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"/** @constructor \n * @extends {Foo} */" +
"var SubFoo = function() { this.bar(); }"
});
}
public void testProtectedAccessForProperties6() {
testSame(new String[] {
"var goog = {};" +
"/** @constructor */ goog.Foo = function() {};" +
"/** @protected */ goog.Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {goog.Foo} */" +
"goog.SubFoo = function() { this.bar(); };"
});
}
public void testNoProtectedAccessForProperties1() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @protected */ Foo.prototype.bar = function() {};",
"(new Foo).bar();"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties2() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @protected */ Foo.prototype.bar = function() {};",
"/** @constructor */ function OtherFoo() { (new Foo).bar(); }"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties3() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubberFoo() { (new SubFoo).bar(); }"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties4() {
test(new String[] {
"/** @constructor */ function Foo() { (new SubFoo).bar(); } ",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};",
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties5() {
test(new String[] {
"var goog = {};" +
"/** @constructor */ goog.Foo = function() {};" +
"/** @protected */ goog.Foo.prototype.bar = function() {};",
"/** @constructor */" +
"goog.NotASubFoo = function() { (new goog.Foo).bar(); };"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoExceptionsWithBadConstructors1() {
testSame(new String[] {
"function Foo() { (new SubFoo).bar(); } " +
"/** @constructor */ function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};"
});
}
public void testNoExceptionsWithBadConstructors2() {
testSame(new String[] {
"/** @constructor */ function Foo() {} " +
"Foo.prototype.bar = function() {};" +
"/** @constructor */" +
"function SubFoo() {}" +
"/** @protected */ " +
"SubFoo.prototype.bar = function() { (new Foo).bar(); };"
});
}
public void testGoodOverrideOfProtectedProperty() {
testSame(new String[] {
"/** @constructor */ function Foo() { } " +
"/** @protected */ Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @inheritDoc */ SubFoo.prototype.bar = function() {};",
});
}
public void testBadOverrideOfProtectedProperty() {
test(new String[] {
"/** @constructor */ function Foo() { } " +
"/** @protected */ Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @private */ SubFoo.prototype.bar = function() {};",
}, null, VISIBILITY_MISMATCH);
}
public void testBadOverrideOfPrivateProperty() {
test(new String[] {
"/** @constructor */ function Foo() { } " +
"/** @private */ Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};",
}, null, PRIVATE_OVERRIDE);
}
public void testAccessOfStaticMethodOnPrivateConstructor() {
testSame(new String[] {
"/** @constructor \n * @private */ function Foo() { } " +
"Foo.create = function() { return new Foo(); };",
"Foo.create()",
});
}
public void testAccessOfStaticMethodOnPrivateQualifiedConstructor() {
testSame(new String[] {
"var goog = {};" +
"/** @constructor \n * @private */ goog.Foo = function() { }; " +
"goog.Foo.create = function() { return new goog.Foo(); };",
"goog.Foo.create()",
});
}
public void testInstanceofOfPrivateConstructor() {
testSame(new String[] {
"var goog = {};" +
"/** @constructor \n * @private */ goog.Foo = function() { }; " +
"goog.Foo.create = function() { return new goog.Foo(); };",
"goog instanceof goog.Foo",
});
}
public void testOkAssignmentOfDeprecatedProperty() {
testSame(
"/** @constructor */ function Foo() {" +
" /** @deprecated */ this.bar = 3;" +
"}");
}
public void testBadReadOfDeprecatedProperty() {
testDep(
"/** @constructor */ function Foo() {" +
" /** @deprecated %s */ this.bar = 3;" +
" this.baz = this.bar;" +
"}",
"GRR",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testAutoboxedDeprecatedProperty() {
testDep(
"/** @constructor */ function String() {}" +
"/** @deprecated %s */ String.prototype.length;" +
"function f() { return 'x'.length; }",
"GRR",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testAutoboxedPrivateProperty() {
test(new String[] {
"/** @constructor */ function String() {}" +
"/** @private */ String.prototype.length;",
"function f() { return 'x'.length; }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNullableDeprecatedProperty() {
testDep(
"/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.length;" +
"/** @param {?Foo} x */ function f(x) { return x.length; }",
"GRR",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testNullablePrivateProperty() {
test(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @private */ Foo.prototype.length;",
"/** @param {?Foo} x */ function f(x) { return x.length; }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testConstantProperty1() {
test("/** @constructor */ function A() {" +
"/** @const */ this.bar = 3;}" +
"/** @constructor */ function B() {" +
"/** @const */ this.bar = 3;this.bar += 4;}",
null, CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty2() {
test("/** @constructor */ function Foo() {}" +
"/** @const */ Foo.prototype.prop = 2;" +
"var foo = new Foo();" +
"foo.prop = 3;",
null , CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty3() {
testSame("var o = { /** @const */ x: 1 };" +
"o.x = 2;");
}
public void testConstantProperty4() {
test("/** @constructor */ function cat(name) {}" +
"/** @const */ cat.test = 1;" +
"cat.test *= 2;",
null, CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty5() {
test("/** @constructor */ function Foo() { this.prop = 1;}" +
"/** @const */ Foo.prototype.prop;" +
"Foo.prototype.prop = 2",
null , CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty6() {
test("/** @constructor */ function Foo() { this.prop = 1;}" +
"/** @const */ Foo.prototype.prop = 2;",
null , CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty7() {
testSame("/** @constructor */ function Foo() {} " +
"Foo.prototype.bar_ = function() {};" +
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"/** @const */ /** @override */ SubFoo.prototype.bar_ = function() {};" +
"SubFoo.prototype.baz = function() { this.bar_(); }");
}
public void testConstantProperty8() {
testSame("var o = { /** @const */ x: 1 };" +
"var y = o.x;");
}
public void testConstantProperty9() {
testSame("/** @constructor */ function A() {" +
"/** @const */ this.bar = 3;}" +
"/** @constructor */ function B() {" +
"this.bar = 4;}");
}
public void testConstantProperty10() {
testSame("/** @constructor */ function Foo() { this.prop = 1;}" +
"/** @const */ Foo.prototype.prop;");
}
public void testSuppressConstantProperty() {
testSame("/** @constructor */ function A() {" +
"/** @const */ this.bar = 3;}" +
"/**\n" +
" * @suppress {constantProperty}\n" +
" * @constructor\n" +
" */ function B() {" +
"/** @const */ this.bar = 3;this.bar += 4;}");
}
} | // You are a professional Java test case writer, please create a test case named `testNoPrivateAccessForProperties6` for the issue `Closure-254`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-254
//
// ## Issue-Title:
// no warnings when @private prop is redeclared on subclass
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// /\*\* @constructor \*/ function Foo() { /\*\* @private \*/ this.x\_ = 3; }
//
// then, in a separate file:
// /\*\* @constructor
// \* @extends {Foo} \*/ function SubFoo() { /\*\* @private \*/ this.x\_ = 3; }
//
// then, compile with --jscomp\_error=visibility
//
// Expected: You should get an error.
// Actual: No error.
//
// You get an error as appropriate if the second @private annotation is removed.
//
//
public void testNoPrivateAccessForProperties6() {
| 408 | 71 | 398 | test/com/google/javascript/jscomp/CheckAccessControlsTest.java | test | ```markdown
## Issue-ID: Closure-254
## Issue-Title:
no warnings when @private prop is redeclared on subclass
## Issue-Description:
**What steps will reproduce the problem?**
/\*\* @constructor \*/ function Foo() { /\*\* @private \*/ this.x\_ = 3; }
then, in a separate file:
/\*\* @constructor
\* @extends {Foo} \*/ function SubFoo() { /\*\* @private \*/ this.x\_ = 3; }
then, compile with --jscomp\_error=visibility
Expected: You should get an error.
Actual: No error.
You get an error as appropriate if the second @private annotation is removed.
```
You are a professional Java test case writer, please create a test case named `testNoPrivateAccessForProperties6` for the issue `Closure-254`, utilizing the provided issue report information and the following function signature.
```java
public void testNoPrivateAccessForProperties6() {
```
| 398 | [
"com.google.javascript.jscomp.CheckAccessControls"
] | 5cd85d21598f8d902417a917431143ff5561bc87009f057959a782f5802bc865 | public void testNoPrivateAccessForProperties6() | // You are a professional Java test case writer, please create a test case named `testNoPrivateAccessForProperties6` for the issue `Closure-254`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-254
//
// ## Issue-Title:
// no warnings when @private prop is redeclared on subclass
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// /\*\* @constructor \*/ function Foo() { /\*\* @private \*/ this.x\_ = 3; }
//
// then, in a separate file:
// /\*\* @constructor
// \* @extends {Foo} \*/ function SubFoo() { /\*\* @private \*/ this.x\_ = 3; }
//
// then, compile with --jscomp\_error=visibility
//
// Expected: You should get an error.
// Actual: No error.
//
// You get an error as appropriate if the second @private annotation is removed.
//
//
| 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;
import static com.google.javascript.jscomp.CheckAccessControls.BAD_PRIVATE_GLOBAL_ACCESS;
import static com.google.javascript.jscomp.CheckAccessControls.BAD_PRIVATE_PROPERTY_ACCESS;
import static com.google.javascript.jscomp.CheckAccessControls.BAD_PROTECTED_PROPERTY_ACCESS;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_CLASS;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_CLASS_REASON;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_NAME;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_NAME_REASON;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_PROP;
import static com.google.javascript.jscomp.CheckAccessControls.DEPRECATED_PROP_REASON;
import static com.google.javascript.jscomp.CheckAccessControls.PRIVATE_OVERRIDE;
import static com.google.javascript.jscomp.CheckAccessControls.VISIBILITY_MISMATCH;
import static com.google.javascript.jscomp.CheckAccessControls.CONST_PROPERTY_REASSIGNED_VALUE;
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.CompilerOptions;
/**
* Tests for {@link CheckAccessControls}.
*
* @author nicksantos@google.com (Nick Santos)
*/
public class CheckAccessControlsTest extends CompilerTestCase {
public CheckAccessControlsTest() {
parseTypeInfo = true;
enableTypeCheck(CheckLevel.WARNING);
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
return new CheckAccessControls(compiler);
}
@Override
protected CompilerOptions getOptions() {
CompilerOptions options = super.getOptions();
options.setWarningLevel(DiagnosticGroups.ACCESS_CONTROLS, CheckLevel.ERROR);
options.setWarningLevel(DiagnosticGroups.CONSTANT_PROPERTY,
CheckLevel.ERROR);
return options;
}
/**
* Tests that the given Javascript code has a @deprecated marker
* somewhere in it which raises an error. Also tests that the
* deprecated marker works with a message. The Javascript should
* have a JsDoc of the form "@deprecated %s\n".
*
* @param js The Javascript code to parse and test.
* @param reason A simple deprecation reason string, used for testing
* the addition of a deprecation reason to the @deprecated tag.
* @param error The deprecation error expected when no reason is given.
* @param errorWithMessage The deprecation error expected when a reason
* message is given.
*/
private void testDep(String js, String reason,
DiagnosticType error,
DiagnosticType errorWithMessage) {
// Test without a reason.
test(String.format(js, ""), null, error);
// Test with a reason.
test(String.format(js, reason), null, errorWithMessage, null, reason);
}
public void testDeprecatedFunction() {
testDep("/** @deprecated %s */ function f() {} function g() { f(); }",
"Some Reason",
DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testWarningOnDeprecatedConstVariable() {
testDep("/** @deprecated %s */ var f = 4; function g() { alert(f); }",
"Another reason",
DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testThatNumbersArentDeprecated() {
testSame("/** @deprecated */ var f = 4; var h = 3; " +
"function g() { alert(h); }");
}
public void testDeprecatedFunctionVariable() {
testDep("/** @deprecated %s */ var f = function() {}; " +
"function g() { f(); }", "I like g...",
DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testNoWarningInGlobalScope() {
testSame("var goog = {}; goog.makeSingleton = function(x) {};" +
"/** @deprecated */ function f() {} goog.makeSingleton(f);");
}
public void testNoWarningInGlobalScopeForCall() {
testDep("/** @deprecated %s */ function f() {} f();",
"Some global scope", DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testNoWarningInDeprecatedFunction() {
testSame("/** @deprecated */ function f() {} " +
"/** @deprecated */ function g() { f(); }");
}
public void testWarningInNormalClass() {
testDep("/** @deprecated %s */ function f() {}" +
"/** @constructor */ var Foo = function() {}; " +
"Foo.prototype.bar = function() { f(); }",
"FooBar", DEPRECATED_NAME, DEPRECATED_NAME_REASON);
}
public void testWarningForProperty1() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert((new Foo()).bar); };",
"A property is bad",
DEPRECATED_PROP, DEPRECATED_PROP_REASON);
}
public void testWarningForProperty2() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert(this.bar); };",
"Zee prop, it is deprecated!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForDeprecatedClass() {
testDep("/** @constructor \n* @deprecated %s */ function Foo() {} " +
"function f() { new Foo(); }",
"Use the class 'Bar'",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testNoWarningForDeprecatedClassInstance() {
testSame("/** @constructor \n * @deprecated */ function Foo() {} " +
"/** @param {Foo} x */ function f(x) { return x; }");
}
public void testWarningForDeprecatedSuperClass() {
testDep("/** @constructor \n * @deprecated %s */ function Foo() {} " +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"function f() { new SubFoo(); }",
"Superclass to the rescue!",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testWarningForDeprecatedSuperClass2() {
testDep("/** @constructor \n * @deprecated %s */ function Foo() {} " +
"var namespace = {}; " +
"/** @constructor \n * @extends {Foo} */ " +
"namespace.SubFoo = function() {}; " +
"function f() { new namespace.SubFoo(); }",
"Its only weakness is Kryptoclass",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testWarningForPrototypeProperty() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert(Foo.prototype.bar); };",
"It is now in production, use that model...",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testNoWarningForNumbers() {
testSame("/** @constructor */ function Foo() {}" +
"/** @deprecated */ Foo.prototype.bar = 3;" +
"Foo.prototype.baz = function() { alert(3); };");
}
public void testWarningForMethod1() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = function() {};" +
"Foo.prototype.baz = function() { this.bar(); };",
"There is a madness to this method",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForMethod2() {
testDep("/** @constructor */ function Foo() {} " +
"/** @deprecated %s */ Foo.prototype.bar; " +
"Foo.prototype.baz = function() { this.bar(); };",
"Stop the ringing!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testNoWarningInDeprecatedClass() {
testSame("/** @deprecated */ function f() {} " +
"/** @constructor \n * @deprecated */ " +
"var Foo = function() {}; " +
"Foo.prototype.bar = function() { f(); }");
}
public void testNoWarningInDeprecatedClass2() {
testSame("/** @deprecated */ function f() {} " +
"/** @constructor \n * @deprecated */ " +
"var Foo = function() {}; " +
"Foo.bar = function() { f(); }");
}
public void testNoWarningInDeprecatedStaticMethod() {
testSame("/** @deprecated */ function f() {} " +
"/** @constructor */ " +
"var Foo = function() {}; " +
"/** @deprecated */ Foo.bar = function() { f(); }");
}
public void testWarningInStaticMethod() {
testDep("/** @deprecated %s */ function f() {} " +
"/** @constructor */ " +
"var Foo = function() {}; " +
"Foo.bar = function() { f(); }",
"crazy!",
DEPRECATED_NAME,
DEPRECATED_NAME_REASON);
}
public void testDeprecatedObjLitKey() {
testDep("var f = {}; /** @deprecated %s */ f.foo = 3; " +
"function g() { return f.foo; }",
"It is literally not used anymore",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForSubclassMethod() {
testDep("/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"/** @deprecated %s */ SubFoo.prototype.bar = function() {};" +
"function f() { (new SubFoo()).bar(); };",
"I have a parent class!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForSuperClassWithDeprecatedSubclassMethod() {
testSame("/** @constructor */ function Foo() {}" +
"Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"/** @deprecated \n * @override */ SubFoo.prototype.bar = " +
"function() {};" +
"function f() { (new Foo()).bar(); };");
}
public void testWarningForSuperclassMethod() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"SubFoo.prototype.bar = function() {};" +
"function f() { (new SubFoo()).bar(); };",
"I have a child class!",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForSuperclassMethod2() {
testDep("/** @constructor */ function Foo() {}" +
"/** @deprecated %s \n* @protected */" +
"Foo.prototype.bar = function() {};" +
"/** @constructor \n * @extends {Foo} */ function SubFoo() {}" +
"/** @protected */SubFoo.prototype.bar = function() {};" +
"function f() { (new SubFoo()).bar(); };",
"I have another child class...",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForBind() {
testDep("/** @deprecated %s */ Function.prototype.bind = function() {};" +
"(function() {}).bind();",
"I'm bound to this method...",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testWarningForDeprecatedClassInGlobalScope() {
testDep("/** @constructor \n * @deprecated %s */ var Foo = function() {};" +
"new Foo();",
"I'm a very worldly object!",
DEPRECATED_CLASS,
DEPRECATED_CLASS_REASON);
}
public void testNoWarningForPrototypeCopying() {
testSame("/** @constructor */ var Foo = function() {};" +
"Foo.prototype.bar = function() {};" +
"/** @deprecated */ Foo.prototype.baz = Foo.prototype.bar;" +
"(new Foo()).bar();");
}
public void testNoWarningOnDeprecatedPrototype() {
// This used to cause an NPE.
testSame("/** @constructor */ var Foo = function() {};" +
"/** @deprecated */ Foo.prototype = {};" +
"Foo.prototype.bar = function() {};");
}
public void testPrivateAccessForNames() {
testSame("/** @private */ function foo_() {}; foo_();");
test(new String[] {
"/** @private */ function foo_() {};",
"foo_();"
}, null, BAD_PRIVATE_GLOBAL_ACCESS);
}
public void testPrivateAccessForProperties1() {
testSame("/** @constructor */ function Foo() {}" +
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); }; (new Foo).bar_();");
}
public void testPrivateAccessForProperties2() {
testSame(new String[] {
"/** @constructor */ function Foo() {}",
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); }; (new Foo).bar_();"
});
}
public void testPrivateAccessForProperties3() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @private */ Foo.prototype.bar_ = function() {}; (new Foo).bar_();",
"Foo.prototype.baz = function() { this.bar_(); };"
});
}
public void testNoPrivateAccessForProperties1() {
test(new String[] {
"/** @constructor */ function Foo() {} (new Foo).bar_();",
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); };"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties2() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};" +
"Foo.prototype.baz = function() { this.bar_(); };",
"(new Foo).bar_();"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties3() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor */ function OtherFoo() { (new Foo).bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties4() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() { this.bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties5() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.baz = function() { this.bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties6() {
// Overriding a private property with a non-private property
// in a different file causes problems.
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.bar_ = function() {};"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties7() {
// It's ok to override a private property with a non-private property
// in the same file, but you'll get yelled at when you try to use it.
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @private */ Foo.prototype.bar_ = function() {};" +
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"SubFoo.prototype.bar_ = function() {};",
"SubFoo.prototype.baz = function() { this.bar_(); }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNoPrivateAccessForProperties8() {
test(new String[] {
"/** @constructor */ function Foo() { /** @private */ this.bar_ = 3; }",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() { /** @private */ this.bar_ = 3; };"
}, null, PRIVATE_OVERRIDE);
}
public void testProtectedAccessForProperties1() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"Foo.prototype.baz = function() { this.bar(); };"
});
}
public void testProtectedAccessForProperties2() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"/** @constructor \n * @extends {Foo} */" +
"function SubFoo() { this.bar(); }"
});
}
public void testProtectedAccessForProperties3() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"/** @constructor \n * @extends {Foo} */" +
"function SubFoo() { }" +
"SubFoo.baz = function() { (new Foo).bar(); }"
});
}
public void testProtectedAccessForProperties4() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.bar = function() {};",
"/** @constructor \n * @extends {Foo} */" +
"function SubFoo() { Foo.bar(); }"
});
}
public void testProtectedAccessForProperties5() {
testSame(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @protected */ Foo.prototype.bar = function() {};" +
"(new Foo).bar();",
"/** @constructor \n * @extends {Foo} */" +
"var SubFoo = function() { this.bar(); }"
});
}
public void testProtectedAccessForProperties6() {
testSame(new String[] {
"var goog = {};" +
"/** @constructor */ goog.Foo = function() {};" +
"/** @protected */ goog.Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {goog.Foo} */" +
"goog.SubFoo = function() { this.bar(); };"
});
}
public void testNoProtectedAccessForProperties1() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @protected */ Foo.prototype.bar = function() {};",
"(new Foo).bar();"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties2() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @protected */ Foo.prototype.bar = function() {};",
"/** @constructor */ function OtherFoo() { (new Foo).bar(); }"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties3() {
test(new String[] {
"/** @constructor */ function Foo() {} " +
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubberFoo() { (new SubFoo).bar(); }"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties4() {
test(new String[] {
"/** @constructor */ function Foo() { (new SubFoo).bar(); } ",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};",
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoProtectedAccessForProperties5() {
test(new String[] {
"var goog = {};" +
"/** @constructor */ goog.Foo = function() {};" +
"/** @protected */ goog.Foo.prototype.bar = function() {};",
"/** @constructor */" +
"goog.NotASubFoo = function() { (new goog.Foo).bar(); };"
}, null, BAD_PROTECTED_PROPERTY_ACCESS);
}
public void testNoExceptionsWithBadConstructors1() {
testSame(new String[] {
"function Foo() { (new SubFoo).bar(); } " +
"/** @constructor */ function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};"
});
}
public void testNoExceptionsWithBadConstructors2() {
testSame(new String[] {
"/** @constructor */ function Foo() {} " +
"Foo.prototype.bar = function() {};" +
"/** @constructor */" +
"function SubFoo() {}" +
"/** @protected */ " +
"SubFoo.prototype.bar = function() { (new Foo).bar(); };"
});
}
public void testGoodOverrideOfProtectedProperty() {
testSame(new String[] {
"/** @constructor */ function Foo() { } " +
"/** @protected */ Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @inheritDoc */ SubFoo.prototype.bar = function() {};",
});
}
public void testBadOverrideOfProtectedProperty() {
test(new String[] {
"/** @constructor */ function Foo() { } " +
"/** @protected */ Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @private */ SubFoo.prototype.bar = function() {};",
}, null, VISIBILITY_MISMATCH);
}
public void testBadOverrideOfPrivateProperty() {
test(new String[] {
"/** @constructor */ function Foo() { } " +
"/** @private */ Foo.prototype.bar = function() {};",
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {}" +
"/** @protected */ SubFoo.prototype.bar = function() {};",
}, null, PRIVATE_OVERRIDE);
}
public void testAccessOfStaticMethodOnPrivateConstructor() {
testSame(new String[] {
"/** @constructor \n * @private */ function Foo() { } " +
"Foo.create = function() { return new Foo(); };",
"Foo.create()",
});
}
public void testAccessOfStaticMethodOnPrivateQualifiedConstructor() {
testSame(new String[] {
"var goog = {};" +
"/** @constructor \n * @private */ goog.Foo = function() { }; " +
"goog.Foo.create = function() { return new goog.Foo(); };",
"goog.Foo.create()",
});
}
public void testInstanceofOfPrivateConstructor() {
testSame(new String[] {
"var goog = {};" +
"/** @constructor \n * @private */ goog.Foo = function() { }; " +
"goog.Foo.create = function() { return new goog.Foo(); };",
"goog instanceof goog.Foo",
});
}
public void testOkAssignmentOfDeprecatedProperty() {
testSame(
"/** @constructor */ function Foo() {" +
" /** @deprecated */ this.bar = 3;" +
"}");
}
public void testBadReadOfDeprecatedProperty() {
testDep(
"/** @constructor */ function Foo() {" +
" /** @deprecated %s */ this.bar = 3;" +
" this.baz = this.bar;" +
"}",
"GRR",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testAutoboxedDeprecatedProperty() {
testDep(
"/** @constructor */ function String() {}" +
"/** @deprecated %s */ String.prototype.length;" +
"function f() { return 'x'.length; }",
"GRR",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testAutoboxedPrivateProperty() {
test(new String[] {
"/** @constructor */ function String() {}" +
"/** @private */ String.prototype.length;",
"function f() { return 'x'.length; }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testNullableDeprecatedProperty() {
testDep(
"/** @constructor */ function Foo() {}" +
"/** @deprecated %s */ Foo.prototype.length;" +
"/** @param {?Foo} x */ function f(x) { return x.length; }",
"GRR",
DEPRECATED_PROP,
DEPRECATED_PROP_REASON);
}
public void testNullablePrivateProperty() {
test(new String[] {
"/** @constructor */ function Foo() {}" +
"/** @private */ Foo.prototype.length;",
"/** @param {?Foo} x */ function f(x) { return x.length; }"
}, null, BAD_PRIVATE_PROPERTY_ACCESS);
}
public void testConstantProperty1() {
test("/** @constructor */ function A() {" +
"/** @const */ this.bar = 3;}" +
"/** @constructor */ function B() {" +
"/** @const */ this.bar = 3;this.bar += 4;}",
null, CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty2() {
test("/** @constructor */ function Foo() {}" +
"/** @const */ Foo.prototype.prop = 2;" +
"var foo = new Foo();" +
"foo.prop = 3;",
null , CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty3() {
testSame("var o = { /** @const */ x: 1 };" +
"o.x = 2;");
}
public void testConstantProperty4() {
test("/** @constructor */ function cat(name) {}" +
"/** @const */ cat.test = 1;" +
"cat.test *= 2;",
null, CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty5() {
test("/** @constructor */ function Foo() { this.prop = 1;}" +
"/** @const */ Foo.prototype.prop;" +
"Foo.prototype.prop = 2",
null , CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty6() {
test("/** @constructor */ function Foo() { this.prop = 1;}" +
"/** @const */ Foo.prototype.prop = 2;",
null , CONST_PROPERTY_REASSIGNED_VALUE);
}
public void testConstantProperty7() {
testSame("/** @constructor */ function Foo() {} " +
"Foo.prototype.bar_ = function() {};" +
"/** @constructor \n * @extends {Foo} */ " +
"function SubFoo() {};" +
"/** @const */ /** @override */ SubFoo.prototype.bar_ = function() {};" +
"SubFoo.prototype.baz = function() { this.bar_(); }");
}
public void testConstantProperty8() {
testSame("var o = { /** @const */ x: 1 };" +
"var y = o.x;");
}
public void testConstantProperty9() {
testSame("/** @constructor */ function A() {" +
"/** @const */ this.bar = 3;}" +
"/** @constructor */ function B() {" +
"this.bar = 4;}");
}
public void testConstantProperty10() {
testSame("/** @constructor */ function Foo() { this.prop = 1;}" +
"/** @const */ Foo.prototype.prop;");
}
public void testSuppressConstantProperty() {
testSame("/** @constructor */ function A() {" +
"/** @const */ this.bar = 3;}" +
"/**\n" +
" * @suppress {constantProperty}\n" +
" * @constructor\n" +
" */ function B() {" +
"/** @const */ this.bar = 3;this.bar += 4;}");
}
} |
||
public void testSimpleModeLeavesUnusedParams() {
args.add("--compilation_level=SIMPLE_OPTIMIZATIONS");
testSame("window.f = function(a) {};");
} | com.google.javascript.jscomp.CommandLineRunnerTest::testSimpleModeLeavesUnusedParams | test/com/google/javascript/jscomp/CommandLineRunnerTest.java | 156 | test/com/google/javascript/jscomp/CommandLineRunnerTest.java | testSimpleModeLeavesUnusedParams | /*
* 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 nicksantos@google.com (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 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");
test(
"/** @constructor */ function F() { this.a = 0; }" +
"F.prototype.inc = function() { this.a++; return 10; };" +
"F.prototype.bar = function() { " +
" var c = 3; var val = inc(); this.a += val + c;" +
"};" +
"window['f'] = new F();" +
"window['f']['bar'] = window['f'].bar;",
"function a(){ this.a = 0; }" +
"a.prototype.b = function(){ var b=inc(); this.a += b + 3; };" +
"window.f = new a;" +
"window.f.bar = window.f.b");
}
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;", SyntacticScopeCreator.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 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 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 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(
lastCompiler.getModuleGraph(), 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 = {};",
SyntacticScopeCreator.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() {
test("var x = f.function", RhinoErrorReporter.PARSE_ERROR);
}
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 `testSimpleModeLeavesUnusedParams` for the issue `Closure-253`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-253
//
// ## Issue-Title:
// function arguments should not be optimized away
//
// ## Issue-Description:
// Function arguments should not be optimized away, as this comprimizes the function's length property.
//
// **What steps will reproduce the problem?**
//
// // ==ClosureCompiler==
// // @compilation\_level SIMPLE\_OPTIMIZATIONS
// // @output\_file\_name default.js
// // ==/ClosureCompiler==
// function foo (bar, baz) {
// return bar;
// }
// alert (foo.length);
// function foo (bar, baz) {
// return bar;
// }
// alert (foo.length);
//
// --------------------------------------
//
// What is the expected output?
//
// function foo(a,b){return a}alert(foo.length);
//
// --------------------------------------
//
// What do you see instead?
//
// function foo(a){return a}alert(foo.length);
//
// --------------------------------------
//
// **What version of the product are you using? On what operating system?**
//
// I'm using the product from the web page http://closure-compiler.appspot.com/home
//
// I'm using Firefox 3.6.10 on Ubuntu 10.0.4
//
// **Please provide any additional information below.**
//
// The function's length property is essential to many techniques, such as currying functions.
//
//
public void testSimpleModeLeavesUnusedParams() {
| 156 | 1 | 153 | test/com/google/javascript/jscomp/CommandLineRunnerTest.java | test | ```markdown
## Issue-ID: Closure-253
## Issue-Title:
function arguments should not be optimized away
## Issue-Description:
Function arguments should not be optimized away, as this comprimizes the function's length property.
**What steps will reproduce the problem?**
// ==ClosureCompiler==
// @compilation\_level SIMPLE\_OPTIMIZATIONS
// @output\_file\_name default.js
// ==/ClosureCompiler==
function foo (bar, baz) {
return bar;
}
alert (foo.length);
function foo (bar, baz) {
return bar;
}
alert (foo.length);
--------------------------------------
What is the expected output?
function foo(a,b){return a}alert(foo.length);
--------------------------------------
What do you see instead?
function foo(a){return a}alert(foo.length);
--------------------------------------
**What version of the product are you using? On what operating system?**
I'm using the product from the web page http://closure-compiler.appspot.com/home
I'm using Firefox 3.6.10 on Ubuntu 10.0.4
**Please provide any additional information below.**
The function's length property is essential to many techniques, such as currying functions.
```
You are a professional Java test case writer, please create a test case named `testSimpleModeLeavesUnusedParams` for the issue `Closure-253`, utilizing the provided issue report information and the following function signature.
```java
public void testSimpleModeLeavesUnusedParams() {
```
| 153 | [
"com.google.javascript.jscomp.RemoveUnusedVars"
] | 5d0a52d450c33f0e5b99bc85aa408e57f6a933e661e8b8abc23420aa3936b31e | public void testSimpleModeLeavesUnusedParams() | // You are a professional Java test case writer, please create a test case named `testSimpleModeLeavesUnusedParams` for the issue `Closure-253`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-253
//
// ## Issue-Title:
// function arguments should not be optimized away
//
// ## Issue-Description:
// Function arguments should not be optimized away, as this comprimizes the function's length property.
//
// **What steps will reproduce the problem?**
//
// // ==ClosureCompiler==
// // @compilation\_level SIMPLE\_OPTIMIZATIONS
// // @output\_file\_name default.js
// // ==/ClosureCompiler==
// function foo (bar, baz) {
// return bar;
// }
// alert (foo.length);
// function foo (bar, baz) {
// return bar;
// }
// alert (foo.length);
//
// --------------------------------------
//
// What is the expected output?
//
// function foo(a,b){return a}alert(foo.length);
//
// --------------------------------------
//
// What do you see instead?
//
// function foo(a){return a}alert(foo.length);
//
// --------------------------------------
//
// **What version of the product are you using? On what operating system?**
//
// I'm using the product from the web page http://closure-compiler.appspot.com/home
//
// I'm using Firefox 3.6.10 on Ubuntu 10.0.4
//
// **Please provide any additional information below.**
//
// The function's length property is essential to many techniques, such as currying functions.
//
//
| 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 nicksantos@google.com (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 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");
test(
"/** @constructor */ function F() { this.a = 0; }" +
"F.prototype.inc = function() { this.a++; return 10; };" +
"F.prototype.bar = function() { " +
" var c = 3; var val = inc(); this.a += val + c;" +
"};" +
"window['f'] = new F();" +
"window['f']['bar'] = window['f'].bar;",
"function a(){ this.a = 0; }" +
"a.prototype.b = function(){ var b=inc(); this.a += b + 3; };" +
"window.f = new a;" +
"window.f.bar = window.f.b");
}
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;", SyntacticScopeCreator.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 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 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 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(
lastCompiler.getModuleGraph(), 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 = {};",
SyntacticScopeCreator.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() {
test("var x = f.function", RhinoErrorReporter.PARSE_ERROR);
}
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 testBug2495455() {
PeriodFormatter pfmt1 = new PeriodFormatterBuilder()
.appendLiteral("P")
.appendYears()
.appendSuffix("Y")
.appendMonths()
.appendSuffix("M")
.appendWeeks()
.appendSuffix("W")
.appendDays()
.appendSuffix("D")
.appendSeparatorIfFieldsAfter("T")
.appendHours()
.appendSuffix("H")
.appendMinutes()
.appendSuffix("M")
.appendSecondsWithOptionalMillis()
.appendSuffix("S")
.toFormatter();
PeriodFormatter pfmt2 = new PeriodFormatterBuilder()
.append(ISOPeriodFormat.standard())
.toFormatter();
pfmt1.parsePeriod("PT1003199059S");
pfmt2.parsePeriod("PT1003199059S");
} | org.joda.time.format.TestPeriodFormatterBuilder::testBug2495455 | src/test/java/org/joda/time/format/TestPeriodFormatterBuilder.java | 869 | src/test/java/org/joda/time/format/TestPeriodFormatterBuilder.java | testBug2495455 | /*
* Copyright 2001-2006 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.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.PeriodType;
/**
* This class is a Junit unit test for PeriodFormatterBuilder.
*
* @author Stephen Colebourne
*/
public class TestPeriodFormatterBuilder extends TestCase {
private static final Period PERIOD = new Period(1, 2, 3, 4, 5, 6, 7, 8);
private static final Period EMPTY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0);
private static final Period YEAR_DAY_PERIOD = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime());
private static final Period EMPTY_YEAR_DAY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0, PeriodType.yearDayTime());
private static final Period TIME_PERIOD = new Period(0, 0, 0, 0, 5, 6, 7, 8);
private static final Period DATE_PERIOD = new Period(1, 2, 3, 4, 0, 0, 0, 0);
//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");
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 PeriodFormatterBuilder builder;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestPeriodFormatterBuilder.class);
}
public TestPeriodFormatterBuilder(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);
builder = new PeriodFormatterBuilder();
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testToFormatterPrinterParser() {
builder.appendYears();
assertNotNull(builder.toFormatter());
assertNotNull(builder.toPrinter());
assertNotNull(builder.toParser());
}
//-----------------------------------------------------------------------
public void testFormatYears() {
PeriodFormatter f = builder.appendYears().toFormatter();
assertEquals("1", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMonths() {
PeriodFormatter f = builder.appendMonths().toFormatter();
assertEquals("2", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatWeeks() {
PeriodFormatter f = builder.appendWeeks().toFormatter();
assertEquals("3", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatDays() {
PeriodFormatter f = builder.appendDays().toFormatter();
assertEquals("4", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatHours() {
PeriodFormatter f = builder.appendHours().toFormatter();
assertEquals("5", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMinutes() {
PeriodFormatter f = builder.appendMinutes().toFormatter();
assertEquals("6", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSeconds() {
PeriodFormatter f = builder.appendSeconds().toFormatter();
assertEquals("7", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSecondsWithMillis() {
PeriodFormatter f = builder.appendSecondsWithMillis().toFormatter();
Period p = new Period(0, 0, 0, 0, 0, 0, 7, 0);
assertEquals("7.000", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1);
assertEquals("7.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 999);
assertEquals("7.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1000);
assertEquals("8.000", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1001);
assertEquals("8.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, -1);
assertEquals("6.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, 1);
assertEquals("-6.999", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, -1);
assertEquals("-7.001", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0.000", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSecondsWithOptionalMillis() {
PeriodFormatter f = builder.appendSecondsWithOptionalMillis().toFormatter();
Period p = new Period(0, 0, 0, 0, 0, 0, 7, 0);
assertEquals("7", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1);
assertEquals("7.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 999);
assertEquals("7.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1000);
assertEquals("8", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1001);
assertEquals("8.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, -1);
assertEquals("6.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, 1);
assertEquals("-6.999", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, -1);
assertEquals("-7.001", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMillis() {
PeriodFormatter f = builder.appendMillis().toFormatter();
assertEquals("8", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMillis3Digit() {
PeriodFormatter f = builder.appendMillis3Digit().toFormatter();
assertEquals("008", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("000", f.print(p));
assertEquals(3, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatPrefixSimple1() {
PeriodFormatter f = builder.appendPrefix("Years:").appendYears().toFormatter();
assertEquals("Years:1", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Years:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixSimple2() {
PeriodFormatter f = builder.appendPrefix("Hours:").appendHours().toFormatter();
assertEquals("Hours:5", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Hours:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixSimple3() {
try {
builder.appendPrefix(null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatPrefixPlural1() {
PeriodFormatter f = builder.appendPrefix("Year:", "Years:").appendYears().toFormatter();
assertEquals("Year:1", f.print(PERIOD));
assertEquals(6, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Years:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixPlural2() {
PeriodFormatter f = builder.appendPrefix("Hour:", "Hours:").appendHours().toFormatter();
assertEquals("Hours:5", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Hours:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixPlural3() {
try {
builder.appendPrefix(null, "");
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendPrefix("", null);
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendPrefix(null, null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testFormatSuffixSimple1() {
PeriodFormatter f = builder.appendYears().appendSuffix(" years").toFormatter();
assertEquals("1 years", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 years", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixSimple2() {
PeriodFormatter f = builder.appendHours().appendSuffix(" hours").toFormatter();
assertEquals("5 hours", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 hours", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixSimple3() {
try {
builder.appendSuffix(null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatSuffixSimple4() {
try {
builder.appendSuffix(" hours");
fail();
} catch (IllegalStateException ex) {}
}
public void testFormatSuffixPlural1() {
PeriodFormatter f = builder.appendYears().appendSuffix(" year", " years").toFormatter();
assertEquals("1 year", f.print(PERIOD));
assertEquals(6, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 years", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixPlural2() {
PeriodFormatter f = builder.appendHours().appendSuffix(" hour", " hours").toFormatter();
assertEquals("5 hours", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 hours", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixPlural3() {
try {
builder.appendSuffix(null, "");
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendSuffix("", null);
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendSuffix(null, null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatSuffixPlural4() {
try {
builder.appendSuffix(" hour", " hours");
fail();
} catch (IllegalStateException ex) {}
}
//-----------------------------------------------------------------------
public void testFormatPrefixSuffix() {
PeriodFormatter f = builder.appendPrefix("P").appendYears().appendSuffix("Y").toFormatter();
assertEquals("P1Y", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("P0Y", f.print(p));
assertEquals(3, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatSeparatorSimple() {
PeriodFormatter f = builder.appendYears().appendSeparator("T").appendHours().toFormatter();
assertEquals("1T5", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("5", f.print(TIME_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1", f.print(DATE_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatSeparatorComplex() {
PeriodFormatter f = builder
.appendYears().appendSeparator(", ", " and ")
.appendHours().appendSeparator(", ", " and ")
.appendMinutes().appendSeparator(", ", " and ")
.toFormatter();
assertEquals("1, 5 and 6", f.print(PERIOD));
assertEquals(10, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(3, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("5 and 6", f.print(TIME_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1", f.print(DATE_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatSeparatorIfFieldsAfter() {
PeriodFormatter f = builder.appendYears().appendSeparatorIfFieldsAfter("T").appendHours().toFormatter();
assertEquals("1T5", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("T5", f.print(TIME_PERIOD));
assertEquals(2, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1", f.print(DATE_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatSeparatorIfFieldsBefore() {
PeriodFormatter f = builder.appendYears().appendSeparatorIfFieldsBefore("T").appendHours().toFormatter();
assertEquals("1T5", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("5", f.print(TIME_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1T", f.print(DATE_PERIOD));
assertEquals(2, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatLiteral() {
PeriodFormatter f = builder.appendLiteral("HELLO").toFormatter();
assertEquals("HELLO", f.print(PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(0, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatAppendFormatter() {
PeriodFormatter base = builder.appendYears().appendLiteral("-").toFormatter();
PeriodFormatter f = new PeriodFormatterBuilder().append(base).appendYears().toFormatter();
assertEquals("1-1", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatMinDigits() {
PeriodFormatter f = new PeriodFormatterBuilder().minimumPrintedDigits(4).appendYears().toFormatter();
assertEquals("0001", f.print(PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatPrintZeroDefault() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
// test only last instance of same field is output
f = new PeriodFormatterBuilder()
.appendYears().appendLiteral("-")
.appendYears().toFormatter();
assertEquals("-0", f.print(EMPTY_PERIOD));
assertEquals(2, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroRarelyLast() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroRarelyLast()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroRarelyFirst() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("0---", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("0---", f.print(EMPTY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroRarelyFirstYears() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendYears().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstMonths() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendMonths().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstWeeks() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendWeeks().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstDays() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendDays().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstHours() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendHours().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstMinutes() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendMinutes().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstSeconds() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendSeconds().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroIfSupported() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroIfSupported()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("0---0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("0-0-0-0", f.print(EMPTY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroAlways() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("0-0-0-0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1-0-0-4", f.print(YEAR_DAY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("0-0-0-0", f.print(EMPTY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroNever() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroNever()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("---", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(0, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("---", f.print(EMPTY_PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(0, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatAppend_PrinterParser_null_null() {
try {
new PeriodFormatterBuilder().append(null, null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatAppend_PrinterParser_Printer_null() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).appendMonths();
assertNotNull(bld.toPrinter());
assertNull(bld.toParser());
PeriodFormatter f = bld.toFormatter();
assertEquals("1-2", f.print(PERIOD));
try {
f.parsePeriod("1-2");
fail();
} catch (UnsupportedOperationException ex) {}
}
public void testFormatAppend_PrinterParser_null_Parser() {
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(null, parser).appendMonths();
assertNull(bld.toPrinter());
assertNotNull(bld.toParser());
PeriodFormatter f = bld.toFormatter();
try {
f.print(PERIOD);
fail();
} catch (UnsupportedOperationException ex) {}
assertEquals(new Period(0, 2, 1, 0, 0, 0, 0, 0), f.parsePeriod("1-2"));
}
public void testFormatAppend_PrinterParser_PrinterParser() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, parser).appendMonths();
assertNotNull(bld.toPrinter());
assertNotNull(bld.toParser());
PeriodFormatter f = bld.toFormatter();
assertEquals("1-2", f.print(PERIOD));
assertEquals(new Period(0, 2, 1, 0, 0, 0, 0, 0), f.parsePeriod("1-2"));
}
public void testFormatAppend_PrinterParser_Printer_null_null_Parser() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).append(null, parser);
assertNull(bld.toPrinter());
assertNull(bld.toParser());
try {
bld.toFormatter();
fail();
} catch (IllegalStateException ex) {}
}
public void testFormatAppend_PrinterParserThenClear() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).append(null, parser);
assertNull(bld.toPrinter());
assertNull(bld.toParser());
bld.clear();
bld.appendMonths();
assertNotNull(bld.toPrinter());
assertNotNull(bld.toParser());
}
public void testBug2495455() {
PeriodFormatter pfmt1 = new PeriodFormatterBuilder()
.appendLiteral("P")
.appendYears()
.appendSuffix("Y")
.appendMonths()
.appendSuffix("M")
.appendWeeks()
.appendSuffix("W")
.appendDays()
.appendSuffix("D")
.appendSeparatorIfFieldsAfter("T")
.appendHours()
.appendSuffix("H")
.appendMinutes()
.appendSuffix("M")
.appendSecondsWithOptionalMillis()
.appendSuffix("S")
.toFormatter();
PeriodFormatter pfmt2 = new PeriodFormatterBuilder()
.append(ISOPeriodFormat.standard())
.toFormatter();
pfmt1.parsePeriod("PT1003199059S");
pfmt2.parsePeriod("PT1003199059S");
}
} | // You are a professional Java test case writer, please create a test case named `testBug2495455` for the issue `Time-64`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-64
//
// ## Issue-Title:
// #64 Different behaviour of PeriodFormatter
//
//
//
//
//
// ## Issue-Description:
// PeriodFormatter pfmt2 = pfmtbuilder2.append(ISOPeriodFormat.standard() ).toFormatter(); is not the same as
//
// PeriodFormatterBuilder pfmtbuilder1 = new PeriodFormatterBuilder()
//
// .appendLiteral("P")
//
// .appendYears()
//
// .appendSuffix("Y")
//
// .appendMonths()
//
// .appendSuffix("M")
//
// .appendWeeks()
//
// .appendSuffix("W")
//
// .appendDays()
//
// .appendSuffix("D")
//
// .appendSeparatorIfFieldsAfter("T")
//
// .appendHours()
//
// .appendSuffix("H")
//
// .appendMinutes()
//
// .appendSuffix("M")
//
// .appendSecondsWithOptionalMillis()
//
// .appendSuffix("S");
//
//
// which is copied from ISOPeriodFormat.standard() method
//
//
//
//
public void testBug2495455() {
| 869 | 27 | 845 | src/test/java/org/joda/time/format/TestPeriodFormatterBuilder.java | src/test/java | ```markdown
## Issue-ID: Time-64
## Issue-Title:
#64 Different behaviour of PeriodFormatter
## Issue-Description:
PeriodFormatter pfmt2 = pfmtbuilder2.append(ISOPeriodFormat.standard() ).toFormatter(); is not the same as
PeriodFormatterBuilder pfmtbuilder1 = new PeriodFormatterBuilder()
.appendLiteral("P")
.appendYears()
.appendSuffix("Y")
.appendMonths()
.appendSuffix("M")
.appendWeeks()
.appendSuffix("W")
.appendDays()
.appendSuffix("D")
.appendSeparatorIfFieldsAfter("T")
.appendHours()
.appendSuffix("H")
.appendMinutes()
.appendSuffix("M")
.appendSecondsWithOptionalMillis()
.appendSuffix("S");
which is copied from ISOPeriodFormat.standard() method
```
You are a professional Java test case writer, please create a test case named `testBug2495455` for the issue `Time-64`, utilizing the provided issue report information and the following function signature.
```java
public void testBug2495455() {
```
| 845 | [
"org.joda.time.format.PeriodFormatterBuilder"
] | 5d87162d9374d20cfe3f4bf892de0b7476e1a0708b95e60690f69c1a39850e59 | public void testBug2495455() | // You are a professional Java test case writer, please create a test case named `testBug2495455` for the issue `Time-64`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-64
//
// ## Issue-Title:
// #64 Different behaviour of PeriodFormatter
//
//
//
//
//
// ## Issue-Description:
// PeriodFormatter pfmt2 = pfmtbuilder2.append(ISOPeriodFormat.standard() ).toFormatter(); is not the same as
//
// PeriodFormatterBuilder pfmtbuilder1 = new PeriodFormatterBuilder()
//
// .appendLiteral("P")
//
// .appendYears()
//
// .appendSuffix("Y")
//
// .appendMonths()
//
// .appendSuffix("M")
//
// .appendWeeks()
//
// .appendSuffix("W")
//
// .appendDays()
//
// .appendSuffix("D")
//
// .appendSeparatorIfFieldsAfter("T")
//
// .appendHours()
//
// .appendSuffix("H")
//
// .appendMinutes()
//
// .appendSuffix("M")
//
// .appendSecondsWithOptionalMillis()
//
// .appendSuffix("S");
//
//
// which is copied from ISOPeriodFormat.standard() method
//
//
//
//
| Time | /*
* Copyright 2001-2006 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.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.PeriodType;
/**
* This class is a Junit unit test for PeriodFormatterBuilder.
*
* @author Stephen Colebourne
*/
public class TestPeriodFormatterBuilder extends TestCase {
private static final Period PERIOD = new Period(1, 2, 3, 4, 5, 6, 7, 8);
private static final Period EMPTY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0);
private static final Period YEAR_DAY_PERIOD = new Period(1, 0, 0, 4, 5, 6, 7, 8, PeriodType.yearDayTime());
private static final Period EMPTY_YEAR_DAY_PERIOD = new Period(0, 0, 0, 0, 0, 0, 0, 0, PeriodType.yearDayTime());
private static final Period TIME_PERIOD = new Period(0, 0, 0, 0, 5, 6, 7, 8);
private static final Period DATE_PERIOD = new Period(1, 2, 3, 4, 0, 0, 0, 0);
//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");
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 PeriodFormatterBuilder builder;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestPeriodFormatterBuilder.class);
}
public TestPeriodFormatterBuilder(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);
builder = new PeriodFormatterBuilder();
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testToFormatterPrinterParser() {
builder.appendYears();
assertNotNull(builder.toFormatter());
assertNotNull(builder.toPrinter());
assertNotNull(builder.toParser());
}
//-----------------------------------------------------------------------
public void testFormatYears() {
PeriodFormatter f = builder.appendYears().toFormatter();
assertEquals("1", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMonths() {
PeriodFormatter f = builder.appendMonths().toFormatter();
assertEquals("2", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatWeeks() {
PeriodFormatter f = builder.appendWeeks().toFormatter();
assertEquals("3", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatDays() {
PeriodFormatter f = builder.appendDays().toFormatter();
assertEquals("4", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatHours() {
PeriodFormatter f = builder.appendHours().toFormatter();
assertEquals("5", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMinutes() {
PeriodFormatter f = builder.appendMinutes().toFormatter();
assertEquals("6", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSeconds() {
PeriodFormatter f = builder.appendSeconds().toFormatter();
assertEquals("7", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSecondsWithMillis() {
PeriodFormatter f = builder.appendSecondsWithMillis().toFormatter();
Period p = new Period(0, 0, 0, 0, 0, 0, 7, 0);
assertEquals("7.000", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1);
assertEquals("7.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 999);
assertEquals("7.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1000);
assertEquals("8.000", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1001);
assertEquals("8.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, -1);
assertEquals("6.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, 1);
assertEquals("-6.999", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, -1);
assertEquals("-7.001", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0.000", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSecondsWithOptionalMillis() {
PeriodFormatter f = builder.appendSecondsWithOptionalMillis().toFormatter();
Period p = new Period(0, 0, 0, 0, 0, 0, 7, 0);
assertEquals("7", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1);
assertEquals("7.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 999);
assertEquals("7.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1000);
assertEquals("8", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, 1001);
assertEquals("8.001", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 7, -1);
assertEquals("6.999", f.print(p));
assertEquals(5, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, 1);
assertEquals("-6.999", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, -7, -1);
assertEquals("-7.001", f.print(p));
assertEquals(6, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMillis() {
PeriodFormatter f = builder.appendMillis().toFormatter();
assertEquals("8", f.print(PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0", f.print(p));
assertEquals(1, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatMillis3Digit() {
PeriodFormatter f = builder.appendMillis3Digit().toFormatter();
assertEquals("008", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("000", f.print(p));
assertEquals(3, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatPrefixSimple1() {
PeriodFormatter f = builder.appendPrefix("Years:").appendYears().toFormatter();
assertEquals("Years:1", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Years:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixSimple2() {
PeriodFormatter f = builder.appendPrefix("Hours:").appendHours().toFormatter();
assertEquals("Hours:5", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Hours:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixSimple3() {
try {
builder.appendPrefix(null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatPrefixPlural1() {
PeriodFormatter f = builder.appendPrefix("Year:", "Years:").appendYears().toFormatter();
assertEquals("Year:1", f.print(PERIOD));
assertEquals(6, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Years:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixPlural2() {
PeriodFormatter f = builder.appendPrefix("Hour:", "Hours:").appendHours().toFormatter();
assertEquals("Hours:5", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("Hours:0", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatPrefixPlural3() {
try {
builder.appendPrefix(null, "");
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendPrefix("", null);
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendPrefix(null, null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testFormatSuffixSimple1() {
PeriodFormatter f = builder.appendYears().appendSuffix(" years").toFormatter();
assertEquals("1 years", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 years", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixSimple2() {
PeriodFormatter f = builder.appendHours().appendSuffix(" hours").toFormatter();
assertEquals("5 hours", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 hours", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixSimple3() {
try {
builder.appendSuffix(null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatSuffixSimple4() {
try {
builder.appendSuffix(" hours");
fail();
} catch (IllegalStateException ex) {}
}
public void testFormatSuffixPlural1() {
PeriodFormatter f = builder.appendYears().appendSuffix(" year", " years").toFormatter();
assertEquals("1 year", f.print(PERIOD));
assertEquals(6, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 years", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixPlural2() {
PeriodFormatter f = builder.appendHours().appendSuffix(" hour", " hours").toFormatter();
assertEquals("5 hours", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("0 hours", f.print(p));
assertEquals(7, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
public void testFormatSuffixPlural3() {
try {
builder.appendSuffix(null, "");
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendSuffix("", null);
fail();
} catch (IllegalArgumentException ex) {}
try {
builder.appendSuffix(null, null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatSuffixPlural4() {
try {
builder.appendSuffix(" hour", " hours");
fail();
} catch (IllegalStateException ex) {}
}
//-----------------------------------------------------------------------
public void testFormatPrefixSuffix() {
PeriodFormatter f = builder.appendPrefix("P").appendYears().appendSuffix("Y").toFormatter();
assertEquals("P1Y", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
Period p = new Period(0, 0, 0, 0, 0, 0, 0, 0);
assertEquals("P0Y", f.print(p));
assertEquals(3, f.getPrinter().calculatePrintedLength(p, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(p, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatSeparatorSimple() {
PeriodFormatter f = builder.appendYears().appendSeparator("T").appendHours().toFormatter();
assertEquals("1T5", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("5", f.print(TIME_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1", f.print(DATE_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatSeparatorComplex() {
PeriodFormatter f = builder
.appendYears().appendSeparator(", ", " and ")
.appendHours().appendSeparator(", ", " and ")
.appendMinutes().appendSeparator(", ", " and ")
.toFormatter();
assertEquals("1, 5 and 6", f.print(PERIOD));
assertEquals(10, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(3, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("5 and 6", f.print(TIME_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1", f.print(DATE_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatSeparatorIfFieldsAfter() {
PeriodFormatter f = builder.appendYears().appendSeparatorIfFieldsAfter("T").appendHours().toFormatter();
assertEquals("1T5", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("T5", f.print(TIME_PERIOD));
assertEquals(2, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1", f.print(DATE_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatSeparatorIfFieldsBefore() {
PeriodFormatter f = builder.appendYears().appendSeparatorIfFieldsBefore("T").appendHours().toFormatter();
assertEquals("1T5", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("5", f.print(TIME_PERIOD));
assertEquals(1, f.getPrinter().calculatePrintedLength(TIME_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(TIME_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1T", f.print(DATE_PERIOD));
assertEquals(2, f.getPrinter().calculatePrintedLength(DATE_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(DATE_PERIOD, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatLiteral() {
PeriodFormatter f = builder.appendLiteral("HELLO").toFormatter();
assertEquals("HELLO", f.print(PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(0, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatAppendFormatter() {
PeriodFormatter base = builder.appendYears().appendLiteral("-").toFormatter();
PeriodFormatter f = new PeriodFormatterBuilder().append(base).appendYears().toFormatter();
assertEquals("1-1", f.print(PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatMinDigits() {
PeriodFormatter f = new PeriodFormatterBuilder().minimumPrintedDigits(4).appendYears().toFormatter();
assertEquals("0001", f.print(PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatPrintZeroDefault() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
// test only last instance of same field is output
f = new PeriodFormatterBuilder()
.appendYears().appendLiteral("-")
.appendYears().toFormatter();
assertEquals("-0", f.print(EMPTY_PERIOD));
assertEquals(2, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroRarelyLast() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroRarelyLast()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("---0", f.print(EMPTY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroRarelyFirst() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("0---", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("0---", f.print(EMPTY_PERIOD));
assertEquals(4, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(1, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroRarelyFirstYears() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendYears().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstMonths() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendMonths().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstWeeks() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendWeeks().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstDays() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendDays().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstHours() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendHours().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstMinutes() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendMinutes().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroRarelyFirstSeconds() {
PeriodFormatter f = new PeriodFormatterBuilder()
.printZeroRarelyFirst()
.appendSeconds().toFormatter();
assertEquals("0", f.print(EMPTY_PERIOD));
}
public void testFormatPrintZeroIfSupported() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroIfSupported()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("0---0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("0-0-0-0", f.print(EMPTY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroAlways() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("0-0-0-0", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1-0-0-4", f.print(YEAR_DAY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("0-0-0-0", f.print(EMPTY_PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
public void testFormatPrintZeroNever() {
PeriodFormatter f =
new PeriodFormatterBuilder()
.printZeroNever()
.appendYears().appendLiteral("-")
.appendMonths().appendLiteral("-")
.appendWeeks().appendLiteral("-")
.appendDays().toFormatter();
assertEquals("1-2-3-4", f.print(PERIOD));
assertEquals(7, f.getPrinter().calculatePrintedLength(PERIOD, null));
assertEquals(4, f.getPrinter().countFieldsToPrint(PERIOD, Integer.MAX_VALUE, null));
assertEquals("---", f.print(EMPTY_YEAR_DAY_PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(EMPTY_YEAR_DAY_PERIOD, null));
assertEquals(0, f.getPrinter().countFieldsToPrint(EMPTY_YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("1---4", f.print(YEAR_DAY_PERIOD));
assertEquals(5, f.getPrinter().calculatePrintedLength(YEAR_DAY_PERIOD, null));
assertEquals(2, f.getPrinter().countFieldsToPrint(YEAR_DAY_PERIOD, Integer.MAX_VALUE, null));
assertEquals("---", f.print(EMPTY_PERIOD));
assertEquals(3, f.getPrinter().calculatePrintedLength(EMPTY_PERIOD, null));
assertEquals(0, f.getPrinter().countFieldsToPrint(EMPTY_PERIOD, Integer.MAX_VALUE, null));
}
//-----------------------------------------------------------------------
public void testFormatAppend_PrinterParser_null_null() {
try {
new PeriodFormatterBuilder().append(null, null);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFormatAppend_PrinterParser_Printer_null() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).appendMonths();
assertNotNull(bld.toPrinter());
assertNull(bld.toParser());
PeriodFormatter f = bld.toFormatter();
assertEquals("1-2", f.print(PERIOD));
try {
f.parsePeriod("1-2");
fail();
} catch (UnsupportedOperationException ex) {}
}
public void testFormatAppend_PrinterParser_null_Parser() {
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(null, parser).appendMonths();
assertNull(bld.toPrinter());
assertNotNull(bld.toParser());
PeriodFormatter f = bld.toFormatter();
try {
f.print(PERIOD);
fail();
} catch (UnsupportedOperationException ex) {}
assertEquals(new Period(0, 2, 1, 0, 0, 0, 0, 0), f.parsePeriod("1-2"));
}
public void testFormatAppend_PrinterParser_PrinterParser() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, parser).appendMonths();
assertNotNull(bld.toPrinter());
assertNotNull(bld.toParser());
PeriodFormatter f = bld.toFormatter();
assertEquals("1-2", f.print(PERIOD));
assertEquals(new Period(0, 2, 1, 0, 0, 0, 0, 0), f.parsePeriod("1-2"));
}
public void testFormatAppend_PrinterParser_Printer_null_null_Parser() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).append(null, parser);
assertNull(bld.toPrinter());
assertNull(bld.toParser());
try {
bld.toFormatter();
fail();
} catch (IllegalStateException ex) {}
}
public void testFormatAppend_PrinterParserThenClear() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).append(null, parser);
assertNull(bld.toPrinter());
assertNull(bld.toParser());
bld.clear();
bld.appendMonths();
assertNotNull(bld.toPrinter());
assertNotNull(bld.toParser());
}
public void testBug2495455() {
PeriodFormatter pfmt1 = new PeriodFormatterBuilder()
.appendLiteral("P")
.appendYears()
.appendSuffix("Y")
.appendMonths()
.appendSuffix("M")
.appendWeeks()
.appendSuffix("W")
.appendDays()
.appendSuffix("D")
.appendSeparatorIfFieldsAfter("T")
.appendHours()
.appendSuffix("H")
.appendMinutes()
.appendSuffix("M")
.appendSecondsWithOptionalMillis()
.appendSuffix("S")
.toFormatter();
PeriodFormatter pfmt2 = new PeriodFormatterBuilder()
.append(ISOPeriodFormat.standard())
.toFormatter();
pfmt1.parsePeriod("PT1003199059S");
pfmt2.parsePeriod("PT1003199059S");
}
} |
||
public void testGoogIsFunction2() throws Exception {
testClosureFunction("goog.isFunction",
OBJECT_NUMBER_STRING_BOOLEAN,
U2U_CONSTRUCTOR_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN);
} | com.google.javascript.jscomp.ClosureReverseAbstractInterpreterTest::testGoogIsFunction2 | test/com/google/javascript/jscomp/ClosureReverseAbstractInterpreterTest.java | 124 | test/com/google/javascript/jscomp/ClosureReverseAbstractInterpreterTest.java | testGoogIsFunction2 | /*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.testing.Asserts;
public class ClosureReverseAbstractInterpreterTest extends
CompilerTypeTestCase {
public void testGoogIsDef1() throws Exception {
testClosureFunction("goog.isDef",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsDef2() throws Exception {
testClosureFunction("goog.isDef",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE));
}
public void testGoogIsNull1() throws Exception {
testClosureFunction("goog.isNull",
createOptionalType(NUMBER_TYPE),
NULL_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsNull2() throws Exception {
testClosureFunction("goog.isNull",
createNullableType(NUMBER_TYPE),
NULL_TYPE,
NUMBER_TYPE);
}
public void testGoogIsDefAndNotNull1() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsDefAndNotNull2() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
createNullableType(NUMBER_TYPE));
}
public void testGoogIsDefAndNotNull3() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(createNullableType(NUMBER_TYPE)),
NUMBER_TYPE,
createOptionalType(createNullableType(NUMBER_TYPE)));
}
public void testGoogIsString1() throws Exception {
testClosureFunction("goog.isString",
createNullableType(STRING_TYPE),
STRING_TYPE,
NULL_TYPE);
}
public void testGoogIsString2() throws Exception {
testClosureFunction("goog.isString",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE));
}
public void testGoogIsBoolean1() throws Exception {
testClosureFunction("goog.isBoolean",
createNullableType(BOOLEAN_TYPE),
BOOLEAN_TYPE,
NULL_TYPE);
}
public void testGoogIsBoolean2() throws Exception {
testClosureFunction("goog.isBoolean",
createUnionType(BOOLEAN_TYPE, STRING_TYPE, NO_OBJECT_TYPE),
BOOLEAN_TYPE,
createUnionType(STRING_TYPE, NO_OBJECT_TYPE));
}
public void testGoogIsNumber() throws Exception {
testClosureFunction("goog.isNumber",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction() throws Exception {
testClosureFunction("goog.isFunction",
createNullableType(OBJECT_FUNCTION_TYPE),
OBJECT_FUNCTION_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction2() throws Exception {
testClosureFunction("goog.isFunction",
OBJECT_NUMBER_STRING_BOOLEAN,
U2U_CONSTRUCTOR_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN);
}
public void testGoogIsFunction3() throws Exception {
testClosureFunction("goog.isFunction",
createUnionType(U2U_CONSTRUCTOR_TYPE,NUMBER_STRING_BOOLEAN),
U2U_CONSTRUCTOR_TYPE,
NUMBER_STRING_BOOLEAN);
}
public void testGoogIsArray() throws Exception {
testClosureFunction("goog.isArray",
OBJECT_TYPE,
ARRAY_TYPE,
OBJECT_TYPE);
}
public void testGoogIsArrayOnNull() throws Exception {
testClosureFunction("goog.isArray",
null,
ARRAY_TYPE,
null);
}
public void testGoogIsFunctionOnNull() throws Exception {
testClosureFunction("goog.isFunction",
null,
U2U_CONSTRUCTOR_TYPE,
null);
}
public void testGoogIsObjectOnNull() throws Exception {
testClosureFunction("goog.isObject",
null,
OBJECT_TYPE,
null);
}
private void testClosureFunction(String function, JSType type,
JSType trueType, JSType falseType) {
// function(a) where a : type
Node n = compiler.parseTestCode("var a; " + function + "(a)");
Node call = n.getLastChild().getLastChild();
Node name = call.getLastChild();
Scope scope = new SyntacticScopeCreator(compiler).createScope(n, null);
FlowScope flowScope = LinkedFlowScope.createEntryLattice(scope);
assertEquals(Token.CALL, call.getType());
assertEquals(Token.NAME, name.getType());
GoogleCodingConvention convention = new GoogleCodingConvention();
flowScope.inferSlotType("a", type);
ClosureReverseAbstractInterpreter rai =
new ClosureReverseAbstractInterpreter(convention, registry);
// trueScope
Asserts.assertTypeEquals(
trueType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, true)
.getSlot("a").getType());
// falseScope
Asserts.assertTypeEquals(
falseType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, false)
.getSlot("a").getType());
}
} | // You are a professional Java test case writer, please create a test case named `testGoogIsFunction2` for the issue `Closure-841`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-841
//
// ## Issue-Title:
// Bad type inference with goog.isFunction and friends
//
// ## Issue-Description:
// experimental/johnlenz/typeerror/test.js:16: WARNING - Property length
// never defined on Number
// var i = object.length;
//
//
// This is the reduced test case:
//
// /\*\*
// \* @param {\*} object Any object.
// \* @return {boolean}
// \*/
// test.isMatched = function(object) {
// if (goog.isDef(object)) {
// if (goog.isFunction(object)) {
// // return object();
// } else if (goog.isBoolean(object)) {
// // return object;
// } else if (goog.isString(object)) {
// // return test.isDef(object);
// } else if (goog.isArray(object)) {
// var i = object.length;
// }
// }
// return false;
// };
//
//
public void testGoogIsFunction2() throws Exception {
| 124 | 7 | 119 | test/com/google/javascript/jscomp/ClosureReverseAbstractInterpreterTest.java | test | ```markdown
## Issue-ID: Closure-841
## Issue-Title:
Bad type inference with goog.isFunction and friends
## Issue-Description:
experimental/johnlenz/typeerror/test.js:16: WARNING - Property length
never defined on Number
var i = object.length;
This is the reduced test case:
/\*\*
\* @param {\*} object Any object.
\* @return {boolean}
\*/
test.isMatched = function(object) {
if (goog.isDef(object)) {
if (goog.isFunction(object)) {
// return object();
} else if (goog.isBoolean(object)) {
// return object;
} else if (goog.isString(object)) {
// return test.isDef(object);
} else if (goog.isArray(object)) {
var i = object.length;
}
}
return false;
};
```
You are a professional Java test case writer, please create a test case named `testGoogIsFunction2` for the issue `Closure-841`, utilizing the provided issue report information and the following function signature.
```java
public void testGoogIsFunction2() throws Exception {
```
| 119 | [
"com.google.javascript.jscomp.type.ChainableReverseAbstractInterpreter"
] | 5e331d80a3d6fe729f3f639f32b643f754ab721451190ed7abc0fa0812ab9b40 | public void testGoogIsFunction2() throws Exception | // You are a professional Java test case writer, please create a test case named `testGoogIsFunction2` for the issue `Closure-841`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-841
//
// ## Issue-Title:
// Bad type inference with goog.isFunction and friends
//
// ## Issue-Description:
// experimental/johnlenz/typeerror/test.js:16: WARNING - Property length
// never defined on Number
// var i = object.length;
//
//
// This is the reduced test case:
//
// /\*\*
// \* @param {\*} object Any object.
// \* @return {boolean}
// \*/
// test.isMatched = function(object) {
// if (goog.isDef(object)) {
// if (goog.isFunction(object)) {
// // return object();
// } else if (goog.isBoolean(object)) {
// // return object;
// } else if (goog.isString(object)) {
// // return test.isDef(object);
// } else if (goog.isArray(object)) {
// var i = object.length;
// }
// }
// return false;
// };
//
//
| Closure | /*
* Copyright 2007 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.javascript.jscomp.type.ClosureReverseAbstractInterpreter;
import com.google.javascript.jscomp.type.FlowScope;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.testing.Asserts;
public class ClosureReverseAbstractInterpreterTest extends
CompilerTypeTestCase {
public void testGoogIsDef1() throws Exception {
testClosureFunction("goog.isDef",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsDef2() throws Exception {
testClosureFunction("goog.isDef",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE));
}
public void testGoogIsNull1() throws Exception {
testClosureFunction("goog.isNull",
createOptionalType(NUMBER_TYPE),
NULL_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsNull2() throws Exception {
testClosureFunction("goog.isNull",
createNullableType(NUMBER_TYPE),
NULL_TYPE,
NUMBER_TYPE);
}
public void testGoogIsDefAndNotNull1() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(NUMBER_TYPE),
NUMBER_TYPE,
createOptionalType(NUMBER_TYPE));
}
public void testGoogIsDefAndNotNull2() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
createNullableType(NUMBER_TYPE));
}
public void testGoogIsDefAndNotNull3() throws Exception {
testClosureFunction("goog.isDefAndNotNull",
createOptionalType(createNullableType(NUMBER_TYPE)),
NUMBER_TYPE,
createOptionalType(createNullableType(NUMBER_TYPE)));
}
public void testGoogIsString1() throws Exception {
testClosureFunction("goog.isString",
createNullableType(STRING_TYPE),
STRING_TYPE,
NULL_TYPE);
}
public void testGoogIsString2() throws Exception {
testClosureFunction("goog.isString",
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE),
createNullableType(NUMBER_TYPE));
}
public void testGoogIsBoolean1() throws Exception {
testClosureFunction("goog.isBoolean",
createNullableType(BOOLEAN_TYPE),
BOOLEAN_TYPE,
NULL_TYPE);
}
public void testGoogIsBoolean2() throws Exception {
testClosureFunction("goog.isBoolean",
createUnionType(BOOLEAN_TYPE, STRING_TYPE, NO_OBJECT_TYPE),
BOOLEAN_TYPE,
createUnionType(STRING_TYPE, NO_OBJECT_TYPE));
}
public void testGoogIsNumber() throws Exception {
testClosureFunction("goog.isNumber",
createNullableType(NUMBER_TYPE),
NUMBER_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction() throws Exception {
testClosureFunction("goog.isFunction",
createNullableType(OBJECT_FUNCTION_TYPE),
OBJECT_FUNCTION_TYPE,
NULL_TYPE);
}
public void testGoogIsFunction2() throws Exception {
testClosureFunction("goog.isFunction",
OBJECT_NUMBER_STRING_BOOLEAN,
U2U_CONSTRUCTOR_TYPE,
OBJECT_NUMBER_STRING_BOOLEAN);
}
public void testGoogIsFunction3() throws Exception {
testClosureFunction("goog.isFunction",
createUnionType(U2U_CONSTRUCTOR_TYPE,NUMBER_STRING_BOOLEAN),
U2U_CONSTRUCTOR_TYPE,
NUMBER_STRING_BOOLEAN);
}
public void testGoogIsArray() throws Exception {
testClosureFunction("goog.isArray",
OBJECT_TYPE,
ARRAY_TYPE,
OBJECT_TYPE);
}
public void testGoogIsArrayOnNull() throws Exception {
testClosureFunction("goog.isArray",
null,
ARRAY_TYPE,
null);
}
public void testGoogIsFunctionOnNull() throws Exception {
testClosureFunction("goog.isFunction",
null,
U2U_CONSTRUCTOR_TYPE,
null);
}
public void testGoogIsObjectOnNull() throws Exception {
testClosureFunction("goog.isObject",
null,
OBJECT_TYPE,
null);
}
private void testClosureFunction(String function, JSType type,
JSType trueType, JSType falseType) {
// function(a) where a : type
Node n = compiler.parseTestCode("var a; " + function + "(a)");
Node call = n.getLastChild().getLastChild();
Node name = call.getLastChild();
Scope scope = new SyntacticScopeCreator(compiler).createScope(n, null);
FlowScope flowScope = LinkedFlowScope.createEntryLattice(scope);
assertEquals(Token.CALL, call.getType());
assertEquals(Token.NAME, name.getType());
GoogleCodingConvention convention = new GoogleCodingConvention();
flowScope.inferSlotType("a", type);
ClosureReverseAbstractInterpreter rai =
new ClosureReverseAbstractInterpreter(convention, registry);
// trueScope
Asserts.assertTypeEquals(
trueType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, true)
.getSlot("a").getType());
// falseScope
Asserts.assertTypeEquals(
falseType,
rai.getPreciserScopeKnowingConditionOutcome(call, flowScope, false)
.getSlot("a").getType());
}
} |
||
public void testIssue291() {
fold("if (true) { f.onchange(); }", "if (1) f.onchange();");
foldSame("if (f) { f.onchange(); }");
foldSame("if (f) { f.bar(); } else { f.onchange(); }");
fold("if (f) { f.bonchange(); }", "f && f.bonchange();");
foldSame("if (f) { f['x'](); }");
} | com.google.javascript.jscomp.PeepholeSubstituteAlternateSyntaxTest::testIssue291 | test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java | 571 | test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java | testIssue291 | /*
* 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;
/**
* Tests for PeepholeSubstituteAlternateSyntaxTest in isolation.
* Tests for the interaction of multiple peephole passes are in
* PeepholeIntegrationTest.
*/
public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase {
// Externs for builtin constructors
// Needed for testFoldLiteralObjectConstructors(),
// testFoldLiteralArrayConstructors() and testFoldRegExp...()
private static final String FOLD_CONSTANTS_TEST_EXTERNS =
"var Object = function(){};\n" +
"var RegExp = function(a){};\n" +
"var Array = function(a){};\n";
// TODO(user): Remove this when we no longer need to do string comparison.
private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) {
super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree);
}
public PeepholeSubstituteAlternateSyntaxTest() {
super(FOLD_CONSTANTS_TEST_EXTERNS);
}
@Override
public void setUp() throws Exception {
super.setUp();
enableLineNumberCheck(true);
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
CompilerPass peepholePass =
new PeepholeOptimizationsPass(compiler,
new PeepholeSubstituteAlternateSyntax());
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);
}
void assertResultString(String js, String expected) {
assertResultString(js, expected, false);
}
// 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.
void assertResultString(String js, String expected, boolean normalize) {
PeepholeSubstituteAlternateSyntaxTest scTest
= new PeepholeSubstituteAlternateSyntaxTest(false);
if (normalize) {
scTest.enableNormalize();
} else {
scTest.disableNormalize();
}
scTest.test(js, expected);
}
/** Check that removing blocks with 1 child works */
public void testFoldOneChildBlocks() {
fold("function(){if(x)a();x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){a()}x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){return 3}}",
"function(){if(x)return 3}");
fold("function(){if(x){a()}}",
"function(){x&&a()}");
fold("function(){if(x){throw 1}}", "function(){if(x)throw 1;}");
// Try it out with functions
fold("function(){if(x){foo()}}", "function(){x&&foo()}");
fold("function(){if(x){foo()}else{bar()}}",
"function(){x?foo():bar()}");
// Try it out with properties and methods
fold("function(){if(x){a.b=1}}", "function(){if(x)a.b=1}");
fold("function(){if(x){a.b*=1}}", "function(){if(x)a.b*=1}");
fold("function(){if(x){a.b+=1}}", "function(){if(x)a.b+=1}");
fold("function(){if(x){++a.b}}", "function(){x&&++a.b}");
fold("function(){if(x){a.foo()}}", "function(){x&&a.foo()}");
// Try it out with throw/catch/finally [which should not change]
fold("function(){try{foo()}catch(e){bar(e)}finally{baz()}}",
"function(){try{foo()}catch(e){bar(e)}finally{baz()}}");
// Try it out with switch statements
fold("function(){switch(x){case 1:break}}",
"function(){switch(x){case 1:break}}");
// Do while loops stay in a block if that's where they started
fold("function(){if(e1){do foo();while(e2)}else foo2()}",
"function(){if(e1){do foo();while(e2)}else foo2()}");
// Test an obscure case with do and while
fold("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
// Play with nested IFs
fold("function(){if(x){if(y)foo()}}",
"function(){x&&y&&foo()}");
fold("function(){if(x){if(y)foo();else bar()}}",
"function(){if(x)y?foo():bar()}");
fold("function(){if(x){if(y)foo()}else bar()}",
"function(){if(x)y&&foo();else bar()}");
fold("function(){if(x){if(y)foo();else bar()}else{baz()}}",
"function(){if(x)y?foo():bar();else baz()}");
fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
"if(e1)while(e2)e3&&foo();else bar()");
fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
"if(e1)with(e2)e3&&foo();else bar()");
fold("if(x){if(y){var x;}}", "if(x)if(y)var x");
fold("if(x){ if(y){var x;}else{var z;} }",
"if(x)if(y)var x;else var z");
// NOTE - technically we can remove the blocks since both the parent
// and child have elses. But we don't since it causes ambiguities in
// some cases where not all descendent ifs having elses
fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
"if(x)if(y)var x;else var z;else var w");
fold("if (x) {var x;}else { if (y) { var y;} }",
"if(x)var x;else if(y)var y");
// Here's some of the ambiguous cases
fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
"if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
fold("function(){foo()}", "function(){foo()}");
fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
fold("try{foo()}catch(ex){bar()}finally{baz()}",
"try{foo()}catch(ex){bar()}finally{baz()}");
}
/** Try to minimize returns */
public void testFoldReturns() {
fold("function(){if(x)return 1;else return 2}",
"function(){return x?1:2}");
fold("function(){if(x)return 1+x;else return 2-x}",
"function(){return x?1+x:2-x}");
fold("function(){if(x)return y += 1;else return y += 2}",
"function(){return x?(y+=1):(y+=2)}");
// don't touch cases where either side doesn't return a value
foldSame("function(){if(x)return;else return 2-x}");
foldSame("function(){if(x)return x;else return}");
foldSame("function(){for(var x in y) { return x.y; } return k}");
}
/** Try to minimize assignments */
public void testFoldAssignments() {
fold("function(){if(x)y=3;else y=4;}", "function(){y=x?3:4}");
fold("function(){if(x)y=1+a;else y=2+a;}", "function(){y=x?1+a:2+a}");
// and operation assignments
fold("function(){if(x)y+=1;else y+=2;}", "function(){y+=x?1:2}");
fold("function(){if(x)y-=1;else y-=2;}", "function(){y-=x?1:2}");
fold("function(){if(x)y%=1;else y%=2;}", "function(){y%=x?1:2}");
fold("function(){if(x)y|=1;else y|=2;}", "function(){y|=x?1:2}");
// sanity check, don't fold if the 2 ops don't match
foldSame("function(){if(x)y-=1;else y+=2}");
// sanity check, don't fold if the 2 LHS don't match
foldSame("function(){if(x)y-=1;else z-=1}");
// sanity check, don't fold if there are potential effects
foldSame("function(){if(x)y().a=3;else y().a=4}");
}
public void testRemoveDuplicateStatements() {
fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
"x=(a) ? 1 : 2; x++");
fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
" else { x = 2; x++; y += 1; z = pi; }",
"x=(a) ? 1 : 2; x++; y += 1; z = pi;");
fold("function z() {" +
"if (a) { foo(); return true } else { goo(); return true }" +
"}",
"function z() {(a) ? foo() : goo(); return true}");
fold("function z() {if (a) { foo(); x = true; return true " +
"} else { goo(); x = true; return true }}",
"function z() {(a) ? foo() : goo(); x = true; return true}");
fold("function z() {" +
" if (a) { bar(); foo(); return true }" +
" else { bar(); goo(); return true }" +
"}",
"function z() {" +
" if (a) { bar(); foo(); }" +
" else { bar(); goo(); }" +
" return true;" +
"}");
}
public void testNotCond() {
fold("function(){if(!x)foo()}", "function(){x||foo()}");
fold("function(){if(!x)b=1}", "function(){x||(b=1)}");
fold("if(!x)z=1;else if(y)z=2", "if(x){if(y)z=2}else z=1");
foldSame("function(){if(!(x=1))a.b=1}");
}
public void testAndParenthesesCount() {
foldSame("function(){if(x||y)a.foo()}");
}
public void testFoldLogicalOpStringCompare() {
// side-effects
// There is two way to parse two &&'s and both are correct.
assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
}
public void testFoldNot() {
fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
// Because !(x<NaN) != x>=NaN don't fold < and > cases.
foldSame("while(!(x>y)){a=b;}");
foldSame("while(!(x>=y)){a=b;}");
foldSame("while(!(x<y)){a=b;}");
foldSame("while(!(x<=y)){a=b;}");
foldSame("while(!(x<=NaN)){a=b;}");
// NOT forces a boolean context
fold("x = !(y() && true)", "x = !y()");
// This will be further optimized by PeepholeFoldConstants.
fold("x = !true", "x = !1");
}
public void testFoldRegExpConstructor() {
enableNormalize();
// Cannot fold all the way to a literal because there are too few arguments.
fold("x = new RegExp", "x = RegExp()");
// Empty regexp should not fold to // since that is a line comment in js
fold("x = new RegExp(\"\")", "x = RegExp(\"\")");
fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")");
// Bogus flags should not fold
fold("x = new RegExp(\"foobar\", \"bogus\")",
"x = RegExp(\"foobar\",\"bogus\")",
PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS);
// Don't fold if the flags contain 'g'
fold("x = new RegExp(\"foobar\", \"g\")",
"x = RegExp(\"foobar\",\"g\")");
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = RegExp(\"foobar\",\"ig\")");
// Can Fold
fold("x = new RegExp(\"foobar\")", "x = /foobar/");
fold("x = RegExp(\"foobar\")", "x = /foobar/");
fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
// Make sure that escaping works
fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
// Don't fold things that crash older versions of Safari and that don't work
// as regex literals on recent versions of Safari
fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
// Don't fold really long regexp literals, because Opera 9.2's
// regexp parser will explode.
String longRegexp = "";
for (int i = 0; i < 200; i++) longRegexp += "x";
foldSame("x = RegExp(\"" + longRegexp + "\")");
// Shouldn't fold RegExp unnormalized because
// we can't be sure that RegExp hasn't been redefined
disableNormalize();
foldSame("x = new RegExp(\"foobar\")");
}
public void testFoldRegExpConstructorStringCompare() {
// Might have something to do with the internal representation of \n and how
// it is used in node comparison.
assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true);
}
public void testContainsUnicodeEscape() throws Exception {
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(""));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\\u2028"));
assertTrue(
PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028"));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028bar\\u2028"));
}
public void testFoldLiteralObjectConstructors() {
enableNormalize();
// Can fold when normalized
fold("x = new Object", "x = ({})");
fold("x = new Object()", "x = ({})");
fold("x = Object()", "x = ({})");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Object");
foldSame("x = new Object()");
foldSame("x = Object()");
enableNormalize();
// Cannot fold, the constructor being used is actually a local function
foldSame("x = " +
"(function(){function Object(){this.x=4};return new Object();})();");
}
public void testFoldLiteralArrayConstructors() {
enableNormalize();
// No arguments - can fold when normalized
fold("x = new Array", "x = []");
fold("x = new Array()", "x = []");
fold("x = Array()", "x = []");
// One argument - can be fold when normalized
fold("x = new Array(0)", "x = []");
fold("x = Array(0)", "x = []");
fold("x = new Array(\"a\")", "x = [\"a\"]");
fold("x = Array(\"a\")", "x = [\"a\"]");
// One argument - cannot be fold when normalized
fold("x = new Array(7)", "x = Array(7)");
fold("x = Array(7)", "x = Array(7)");
fold("x = new Array(y)", "x = Array(y)");
fold("x = Array(y)", "x = Array(y)");
fold("x = new Array(foo())", "x = Array(foo())");
fold("x = Array(foo())", "x = Array(foo())");
// More than one argument - can be fold when normalized
fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Array");
foldSame("x = new Array()");
foldSame("x = Array()");
foldSame("x = new Array(0)");
foldSame("x = Array(0)");
foldSame("x = new Array(\"a\")");
foldSame("x = Array(\"a\")");
foldSame("x = new Array(7)");
foldSame("x = Array(7)");
foldSame("x = new Array(foo())");
foldSame("x = Array(foo())");
foldSame("x = new Array(1, 2, 3, 4)");
foldSame("x = Array(1, 2, 3, 4)");
foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = new Array(Array(1, '2', 3, '4'))");
foldSame("x = Array(Array(1, '2', 3, '4'))");
foldSame("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))");
foldSame("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))");
}
public void testMinimizeExprCondition() {
fold("(x ? true : false) && y()", "x&&y()");
fold("(x ? false : true) && y()", "(!x)&&y()");
fold("(x ? true : y) && y()", "(x || y)&&y()");
fold("(x ? y : false) && y()", "(x && y)&&y()");
fold("(x && true) && y()", "x && y()");
fold("(x && false) && y()", "0&&y()");
fold("(x || true) && y()", "1&&y()");
fold("(x || false) && y()", "x&&y()");
}
public void testMinimizeWhileCondition() {
// This test uses constant folding logic, so is only here for completeness.
fold("while(!!true) foo()", "while(1) foo()");
// These test tryMinimizeCondition
fold("while(!!x) foo()", "while(x) foo()");
fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
fold("while(x||!!y) foo()", "while(x||y) foo()");
fold("while(!(!!x&&y)) foo()", "while(!(x&&y)) foo()");
}
public void testMinimizeForCondition() {
// This test uses constant folding logic, so is only here for completeness.
// These could be simplified to "for(;;) ..."
fold("for(;!!true;) foo()", "for(;1;) foo()");
// Don't bother with FOR inits as there are normalized out.
fold("for(!!true;;) foo()", "for(!!1;;) foo()");
// These test tryMinimizeCondition
fold("for(;!!x;) foo()", "for(;x;) foo()");
// sanity check
foldSame("for(a in b) foo()");
foldSame("for(a in {}) foo()");
foldSame("for(a in []) foo()");
fold("for(a in !!true) foo()", "for(a in !!1) foo()");
}
public void testMinimizeCondition_example1() {
// Based on a real failing code sample.
fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
}
public void testFoldConditionalVarDeclaration() {
fold("if(x) var y=1;else y=2", "var y=x?1:2");
fold("if(x) y=1;else var y=2", "var y=x?1:2");
foldSame("if(x) var y = 1; z = 2");
foldSame("if(x) y = 1; var z = 2");
foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
foldSame("if(x) var y = 1; else {y = 2; print(y)}");
}
public void testFoldReturnResult() {
foldSame("function f(){return false;}");
foldSame("function f(){return null;}");
fold("function f(){return void 0;}",
"function f(){return}");
foldSame("function f(){return void foo();}");
fold("function f(){return undefined;}",
"function f(){return}");
fold("function(){if(a()){return undefined;}}",
"function(){if(a()){return}}");
}
public void testFoldStandardConstructors() {
foldSame("new Foo('a')");
foldSame("var x = new goog.Foo(1)");
foldSame("var x = new String(1)");
foldSame("var x = new Number(1)");
foldSame("var x = new Boolean(1)");
enableNormalize();
fold("var x = new Object('a')", "var x = Object('a')");
fold("var x = new RegExp('')", "var x = RegExp('')");
fold("var x = new Error('20')", "var x = Error(\"20\")");
fold("var x = new Array(20)", "var x = Array(20)");
}
public void testSubsituteReturn() {
fold("function f() { while(x) { return }}",
"function f() { while(x) { break }}");
foldSame("function f() { while(x) { return 5 } }");
foldSame("function f() { a: { return 5 } }");
fold("function f() { while(x) { return 5} return 5}",
"function f() { while(x) { break } return 5}");
fold("function f() { while(x) { return x} return x}",
"function f() { while(x) { break } return x}");
fold("function f() { while(x) { if (y) { return }}} ",
"function f() { while(x) { if (y) { break }}} ");
fold("function f() { while(x) { if (y) { return }} return} ",
"function f() { while(x) { if (y) { break }} return} ");
fold("function f() { while(x) { if (y) { return 5 }} return 5} ",
"function f() { while(x) { if (y) { break }} return 5} ");
// It doesn't matter if x is changed between them. We are still returning
// x at whatever x value current holds. The whole x = 1 is skipped.
fold("function f() { while(x) { if (y) { return x } x = 1} return x} ",
"function f() { while(x) { if (y) { break } x = 1} return x} ");
// RemoveUnreachableCode would take care of the useless breaks.
fold("function f() { while(x) { if (y) { return x } return x} return x}",
"function f() { while(x) { if (y) { break } break } return x}");
// A break here only breaks out of the inner loop.
foldSame("function f() { while(x) { while (y) { return } } }");
foldSame("function f() { while(1) { return 7} return 5}");
foldSame("function f() {" +
" try { while(x) {return f()}} catch (e) { } return f()}");
foldSame("function f() {" +
" try { while(x) {return f()}} finally {alert(1)} return f()}");
// Both returns has the same handler
fold("function f() {" +
" try { while(x) { return f() } return f() } catch (e) { } }",
"function f() {" +
" try { while(x) { break } return f() } catch (e) { } }");
// We can't fold this because it'll change the order of when foo is called.
foldSame("function f() {" +
" try { while(x) { return foo() } } finally { alert(1) } " +
" return foo()}");
// This is fine, we have no side effect in the return value.
fold("function f() {" +
" try { while(x) { return 1 } } finally { alert(1) } return 1}",
"function f() {" +
" try { while(x) { break } } finally { alert(1) } return 1}"
);
foldSame("function f() { try{ return a } finally { a = 2 } return a; }");
}
public void testIssue291() {
fold("if (true) { f.onchange(); }", "if (1) f.onchange();");
foldSame("if (f) { f.onchange(); }");
foldSame("if (f) { f.bar(); } else { f.onchange(); }");
fold("if (f) { f.bonchange(); }", "f && f.bonchange();");
foldSame("if (f) { f['x'](); }");
}
} | // You are a professional Java test case writer, please create a test case named `testIssue291` for the issue `Closure-291`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-291
//
// ## Issue-Title:
// IE8 error: Object doesn't support this action
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Use script with fragment like
// if (e.onchange) {
// e.onchange({
// \_extendedByPrototype: Prototype.emptyFunction,
// target: e
// });
// }
// 2. Compile with Compiler (command-line, latest version)
// 3. Use in IE8
//
// What is the expected output?
// Script:
// if(b.onchange){b.onchange({\_extendedByPrototype:Prototype.emptyFunction,target
// :b})}
//
// What do you see instead?
// Script:
// b.onchange&&b.onchange({\_extendedByPrototype:Prototype.emptyFunction,target
// :b})
// IE8:
// Error message "Object doesn't support this action"
//
// **What version of the product are you using? On what operating system?**
// Version: 20100917 (revision 440)
// Built on: 2010/09/17 17:55
//
//
public void testIssue291() {
| 571 | 87 | 565 | test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java | test | ```markdown
## Issue-ID: Closure-291
## Issue-Title:
IE8 error: Object doesn't support this action
## Issue-Description:
**What steps will reproduce the problem?**
1. Use script with fragment like
if (e.onchange) {
e.onchange({
\_extendedByPrototype: Prototype.emptyFunction,
target: e
});
}
2. Compile with Compiler (command-line, latest version)
3. Use in IE8
What is the expected output?
Script:
if(b.onchange){b.onchange({\_extendedByPrototype:Prototype.emptyFunction,target
:b})}
What do you see instead?
Script:
b.onchange&&b.onchange({\_extendedByPrototype:Prototype.emptyFunction,target
:b})
IE8:
Error message "Object doesn't support this action"
**What version of the product are you using? On what operating system?**
Version: 20100917 (revision 440)
Built on: 2010/09/17 17:55
```
You are a professional Java test case writer, please create a test case named `testIssue291` for the issue `Closure-291`, utilizing the provided issue report information and the following function signature.
```java
public void testIssue291() {
```
| 565 | [
"com.google.javascript.jscomp.PeepholeSubstituteAlternateSyntax"
] | 5e6dfafbdc38d10db632b54ced3765e6c708b4d9636d5b2492629d19f544440e | public void testIssue291() | // You are a professional Java test case writer, please create a test case named `testIssue291` for the issue `Closure-291`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-291
//
// ## Issue-Title:
// IE8 error: Object doesn't support this action
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
// 1. Use script with fragment like
// if (e.onchange) {
// e.onchange({
// \_extendedByPrototype: Prototype.emptyFunction,
// target: e
// });
// }
// 2. Compile with Compiler (command-line, latest version)
// 3. Use in IE8
//
// What is the expected output?
// Script:
// if(b.onchange){b.onchange({\_extendedByPrototype:Prototype.emptyFunction,target
// :b})}
//
// What do you see instead?
// Script:
// b.onchange&&b.onchange({\_extendedByPrototype:Prototype.emptyFunction,target
// :b})
// IE8:
// Error message "Object doesn't support this action"
//
// **What version of the product are you using? On what operating system?**
// Version: 20100917 (revision 440)
// Built on: 2010/09/17 17:55
//
//
| 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;
/**
* Tests for PeepholeSubstituteAlternateSyntaxTest in isolation.
* Tests for the interaction of multiple peephole passes are in
* PeepholeIntegrationTest.
*/
public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase {
// Externs for builtin constructors
// Needed for testFoldLiteralObjectConstructors(),
// testFoldLiteralArrayConstructors() and testFoldRegExp...()
private static final String FOLD_CONSTANTS_TEST_EXTERNS =
"var Object = function(){};\n" +
"var RegExp = function(a){};\n" +
"var Array = function(a){};\n";
// TODO(user): Remove this when we no longer need to do string comparison.
private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) {
super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree);
}
public PeepholeSubstituteAlternateSyntaxTest() {
super(FOLD_CONSTANTS_TEST_EXTERNS);
}
@Override
public void setUp() throws Exception {
super.setUp();
enableLineNumberCheck(true);
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
CompilerPass peepholePass =
new PeepholeOptimizationsPass(compiler,
new PeepholeSubstituteAlternateSyntax());
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);
}
void assertResultString(String js, String expected) {
assertResultString(js, expected, false);
}
// 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.
void assertResultString(String js, String expected, boolean normalize) {
PeepholeSubstituteAlternateSyntaxTest scTest
= new PeepholeSubstituteAlternateSyntaxTest(false);
if (normalize) {
scTest.enableNormalize();
} else {
scTest.disableNormalize();
}
scTest.test(js, expected);
}
/** Check that removing blocks with 1 child works */
public void testFoldOneChildBlocks() {
fold("function(){if(x)a();x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){a()}x=3}",
"function(){x&&a();x=3}");
fold("function(){if(x){return 3}}",
"function(){if(x)return 3}");
fold("function(){if(x){a()}}",
"function(){x&&a()}");
fold("function(){if(x){throw 1}}", "function(){if(x)throw 1;}");
// Try it out with functions
fold("function(){if(x){foo()}}", "function(){x&&foo()}");
fold("function(){if(x){foo()}else{bar()}}",
"function(){x?foo():bar()}");
// Try it out with properties and methods
fold("function(){if(x){a.b=1}}", "function(){if(x)a.b=1}");
fold("function(){if(x){a.b*=1}}", "function(){if(x)a.b*=1}");
fold("function(){if(x){a.b+=1}}", "function(){if(x)a.b+=1}");
fold("function(){if(x){++a.b}}", "function(){x&&++a.b}");
fold("function(){if(x){a.foo()}}", "function(){x&&a.foo()}");
// Try it out with throw/catch/finally [which should not change]
fold("function(){try{foo()}catch(e){bar(e)}finally{baz()}}",
"function(){try{foo()}catch(e){bar(e)}finally{baz()}}");
// Try it out with switch statements
fold("function(){switch(x){case 1:break}}",
"function(){switch(x){case 1:break}}");
// Do while loops stay in a block if that's where they started
fold("function(){if(e1){do foo();while(e2)}else foo2()}",
"function(){if(e1){do foo();while(e2)}else foo2()}");
// Test an obscure case with do and while
fold("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
// Play with nested IFs
fold("function(){if(x){if(y)foo()}}",
"function(){x&&y&&foo()}");
fold("function(){if(x){if(y)foo();else bar()}}",
"function(){if(x)y?foo():bar()}");
fold("function(){if(x){if(y)foo()}else bar()}",
"function(){if(x)y&&foo();else bar()}");
fold("function(){if(x){if(y)foo();else bar()}else{baz()}}",
"function(){if(x)y?foo():bar();else baz()}");
fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
"if(e1)while(e2)e3&&foo();else bar()");
fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
"if(e1)with(e2)e3&&foo();else bar()");
fold("if(x){if(y){var x;}}", "if(x)if(y)var x");
fold("if(x){ if(y){var x;}else{var z;} }",
"if(x)if(y)var x;else var z");
// NOTE - technically we can remove the blocks since both the parent
// and child have elses. But we don't since it causes ambiguities in
// some cases where not all descendent ifs having elses
fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
"if(x)if(y)var x;else var z;else var w");
fold("if (x) {var x;}else { if (y) { var y;} }",
"if(x)var x;else if(y)var y");
// Here's some of the ambiguous cases
fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
"if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
fold("function(){foo()}", "function(){foo()}");
fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
fold("try{foo()}catch(ex){bar()}finally{baz()}",
"try{foo()}catch(ex){bar()}finally{baz()}");
}
/** Try to minimize returns */
public void testFoldReturns() {
fold("function(){if(x)return 1;else return 2}",
"function(){return x?1:2}");
fold("function(){if(x)return 1+x;else return 2-x}",
"function(){return x?1+x:2-x}");
fold("function(){if(x)return y += 1;else return y += 2}",
"function(){return x?(y+=1):(y+=2)}");
// don't touch cases where either side doesn't return a value
foldSame("function(){if(x)return;else return 2-x}");
foldSame("function(){if(x)return x;else return}");
foldSame("function(){for(var x in y) { return x.y; } return k}");
}
/** Try to minimize assignments */
public void testFoldAssignments() {
fold("function(){if(x)y=3;else y=4;}", "function(){y=x?3:4}");
fold("function(){if(x)y=1+a;else y=2+a;}", "function(){y=x?1+a:2+a}");
// and operation assignments
fold("function(){if(x)y+=1;else y+=2;}", "function(){y+=x?1:2}");
fold("function(){if(x)y-=1;else y-=2;}", "function(){y-=x?1:2}");
fold("function(){if(x)y%=1;else y%=2;}", "function(){y%=x?1:2}");
fold("function(){if(x)y|=1;else y|=2;}", "function(){y|=x?1:2}");
// sanity check, don't fold if the 2 ops don't match
foldSame("function(){if(x)y-=1;else y+=2}");
// sanity check, don't fold if the 2 LHS don't match
foldSame("function(){if(x)y-=1;else z-=1}");
// sanity check, don't fold if there are potential effects
foldSame("function(){if(x)y().a=3;else y().a=4}");
}
public void testRemoveDuplicateStatements() {
fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
"x=(a) ? 1 : 2; x++");
fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
" else { x = 2; x++; y += 1; z = pi; }",
"x=(a) ? 1 : 2; x++; y += 1; z = pi;");
fold("function z() {" +
"if (a) { foo(); return true } else { goo(); return true }" +
"}",
"function z() {(a) ? foo() : goo(); return true}");
fold("function z() {if (a) { foo(); x = true; return true " +
"} else { goo(); x = true; return true }}",
"function z() {(a) ? foo() : goo(); x = true; return true}");
fold("function z() {" +
" if (a) { bar(); foo(); return true }" +
" else { bar(); goo(); return true }" +
"}",
"function z() {" +
" if (a) { bar(); foo(); }" +
" else { bar(); goo(); }" +
" return true;" +
"}");
}
public void testNotCond() {
fold("function(){if(!x)foo()}", "function(){x||foo()}");
fold("function(){if(!x)b=1}", "function(){x||(b=1)}");
fold("if(!x)z=1;else if(y)z=2", "if(x){if(y)z=2}else z=1");
foldSame("function(){if(!(x=1))a.b=1}");
}
public void testAndParenthesesCount() {
foldSame("function(){if(x||y)a.foo()}");
}
public void testFoldLogicalOpStringCompare() {
// side-effects
// There is two way to parse two &&'s and both are correct.
assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
}
public void testFoldNot() {
fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
// Because !(x<NaN) != x>=NaN don't fold < and > cases.
foldSame("while(!(x>y)){a=b;}");
foldSame("while(!(x>=y)){a=b;}");
foldSame("while(!(x<y)){a=b;}");
foldSame("while(!(x<=y)){a=b;}");
foldSame("while(!(x<=NaN)){a=b;}");
// NOT forces a boolean context
fold("x = !(y() && true)", "x = !y()");
// This will be further optimized by PeepholeFoldConstants.
fold("x = !true", "x = !1");
}
public void testFoldRegExpConstructor() {
enableNormalize();
// Cannot fold all the way to a literal because there are too few arguments.
fold("x = new RegExp", "x = RegExp()");
// Empty regexp should not fold to // since that is a line comment in js
fold("x = new RegExp(\"\")", "x = RegExp(\"\")");
fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")");
// Bogus flags should not fold
fold("x = new RegExp(\"foobar\", \"bogus\")",
"x = RegExp(\"foobar\",\"bogus\")",
PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS);
// Don't fold if the flags contain 'g'
fold("x = new RegExp(\"foobar\", \"g\")",
"x = RegExp(\"foobar\",\"g\")");
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = RegExp(\"foobar\",\"ig\")");
// Can Fold
fold("x = new RegExp(\"foobar\")", "x = /foobar/");
fold("x = RegExp(\"foobar\")", "x = /foobar/");
fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
// Make sure that escaping works
fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
// Don't fold things that crash older versions of Safari and that don't work
// as regex literals on recent versions of Safari
fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
// Don't fold really long regexp literals, because Opera 9.2's
// regexp parser will explode.
String longRegexp = "";
for (int i = 0; i < 200; i++) longRegexp += "x";
foldSame("x = RegExp(\"" + longRegexp + "\")");
// Shouldn't fold RegExp unnormalized because
// we can't be sure that RegExp hasn't been redefined
disableNormalize();
foldSame("x = new RegExp(\"foobar\")");
}
public void testFoldRegExpConstructorStringCompare() {
// Might have something to do with the internal representation of \n and how
// it is used in node comparison.
assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true);
}
public void testContainsUnicodeEscape() throws Exception {
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(""));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\\u2028"));
assertTrue(
PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028"));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028bar\\u2028"));
}
public void testFoldLiteralObjectConstructors() {
enableNormalize();
// Can fold when normalized
fold("x = new Object", "x = ({})");
fold("x = new Object()", "x = ({})");
fold("x = Object()", "x = ({})");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Object");
foldSame("x = new Object()");
foldSame("x = Object()");
enableNormalize();
// Cannot fold, the constructor being used is actually a local function
foldSame("x = " +
"(function(){function Object(){this.x=4};return new Object();})();");
}
public void testFoldLiteralArrayConstructors() {
enableNormalize();
// No arguments - can fold when normalized
fold("x = new Array", "x = []");
fold("x = new Array()", "x = []");
fold("x = Array()", "x = []");
// One argument - can be fold when normalized
fold("x = new Array(0)", "x = []");
fold("x = Array(0)", "x = []");
fold("x = new Array(\"a\")", "x = [\"a\"]");
fold("x = Array(\"a\")", "x = [\"a\"]");
// One argument - cannot be fold when normalized
fold("x = new Array(7)", "x = Array(7)");
fold("x = Array(7)", "x = Array(7)");
fold("x = new Array(y)", "x = Array(y)");
fold("x = Array(y)", "x = Array(y)");
fold("x = new Array(foo())", "x = Array(foo())");
fold("x = Array(foo())", "x = Array(foo())");
// More than one argument - can be fold when normalized
fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Array");
foldSame("x = new Array()");
foldSame("x = Array()");
foldSame("x = new Array(0)");
foldSame("x = Array(0)");
foldSame("x = new Array(\"a\")");
foldSame("x = Array(\"a\")");
foldSame("x = new Array(7)");
foldSame("x = Array(7)");
foldSame("x = new Array(foo())");
foldSame("x = Array(foo())");
foldSame("x = new Array(1, 2, 3, 4)");
foldSame("x = Array(1, 2, 3, 4)");
foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = new Array(Array(1, '2', 3, '4'))");
foldSame("x = Array(Array(1, '2', 3, '4'))");
foldSame("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))");
foldSame("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))");
}
public void testMinimizeExprCondition() {
fold("(x ? true : false) && y()", "x&&y()");
fold("(x ? false : true) && y()", "(!x)&&y()");
fold("(x ? true : y) && y()", "(x || y)&&y()");
fold("(x ? y : false) && y()", "(x && y)&&y()");
fold("(x && true) && y()", "x && y()");
fold("(x && false) && y()", "0&&y()");
fold("(x || true) && y()", "1&&y()");
fold("(x || false) && y()", "x&&y()");
}
public void testMinimizeWhileCondition() {
// This test uses constant folding logic, so is only here for completeness.
fold("while(!!true) foo()", "while(1) foo()");
// These test tryMinimizeCondition
fold("while(!!x) foo()", "while(x) foo()");
fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
fold("while(x||!!y) foo()", "while(x||y) foo()");
fold("while(!(!!x&&y)) foo()", "while(!(x&&y)) foo()");
}
public void testMinimizeForCondition() {
// This test uses constant folding logic, so is only here for completeness.
// These could be simplified to "for(;;) ..."
fold("for(;!!true;) foo()", "for(;1;) foo()");
// Don't bother with FOR inits as there are normalized out.
fold("for(!!true;;) foo()", "for(!!1;;) foo()");
// These test tryMinimizeCondition
fold("for(;!!x;) foo()", "for(;x;) foo()");
// sanity check
foldSame("for(a in b) foo()");
foldSame("for(a in {}) foo()");
foldSame("for(a in []) foo()");
fold("for(a in !!true) foo()", "for(a in !!1) foo()");
}
public void testMinimizeCondition_example1() {
// Based on a real failing code sample.
fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
}
public void testFoldConditionalVarDeclaration() {
fold("if(x) var y=1;else y=2", "var y=x?1:2");
fold("if(x) y=1;else var y=2", "var y=x?1:2");
foldSame("if(x) var y = 1; z = 2");
foldSame("if(x) y = 1; var z = 2");
foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
foldSame("if(x) var y = 1; else {y = 2; print(y)}");
}
public void testFoldReturnResult() {
foldSame("function f(){return false;}");
foldSame("function f(){return null;}");
fold("function f(){return void 0;}",
"function f(){return}");
foldSame("function f(){return void foo();}");
fold("function f(){return undefined;}",
"function f(){return}");
fold("function(){if(a()){return undefined;}}",
"function(){if(a()){return}}");
}
public void testFoldStandardConstructors() {
foldSame("new Foo('a')");
foldSame("var x = new goog.Foo(1)");
foldSame("var x = new String(1)");
foldSame("var x = new Number(1)");
foldSame("var x = new Boolean(1)");
enableNormalize();
fold("var x = new Object('a')", "var x = Object('a')");
fold("var x = new RegExp('')", "var x = RegExp('')");
fold("var x = new Error('20')", "var x = Error(\"20\")");
fold("var x = new Array(20)", "var x = Array(20)");
}
public void testSubsituteReturn() {
fold("function f() { while(x) { return }}",
"function f() { while(x) { break }}");
foldSame("function f() { while(x) { return 5 } }");
foldSame("function f() { a: { return 5 } }");
fold("function f() { while(x) { return 5} return 5}",
"function f() { while(x) { break } return 5}");
fold("function f() { while(x) { return x} return x}",
"function f() { while(x) { break } return x}");
fold("function f() { while(x) { if (y) { return }}} ",
"function f() { while(x) { if (y) { break }}} ");
fold("function f() { while(x) { if (y) { return }} return} ",
"function f() { while(x) { if (y) { break }} return} ");
fold("function f() { while(x) { if (y) { return 5 }} return 5} ",
"function f() { while(x) { if (y) { break }} return 5} ");
// It doesn't matter if x is changed between them. We are still returning
// x at whatever x value current holds. The whole x = 1 is skipped.
fold("function f() { while(x) { if (y) { return x } x = 1} return x} ",
"function f() { while(x) { if (y) { break } x = 1} return x} ");
// RemoveUnreachableCode would take care of the useless breaks.
fold("function f() { while(x) { if (y) { return x } return x} return x}",
"function f() { while(x) { if (y) { break } break } return x}");
// A break here only breaks out of the inner loop.
foldSame("function f() { while(x) { while (y) { return } } }");
foldSame("function f() { while(1) { return 7} return 5}");
foldSame("function f() {" +
" try { while(x) {return f()}} catch (e) { } return f()}");
foldSame("function f() {" +
" try { while(x) {return f()}} finally {alert(1)} return f()}");
// Both returns has the same handler
fold("function f() {" +
" try { while(x) { return f() } return f() } catch (e) { } }",
"function f() {" +
" try { while(x) { break } return f() } catch (e) { } }");
// We can't fold this because it'll change the order of when foo is called.
foldSame("function f() {" +
" try { while(x) { return foo() } } finally { alert(1) } " +
" return foo()}");
// This is fine, we have no side effect in the return value.
fold("function f() {" +
" try { while(x) { return 1 } } finally { alert(1) } return 1}",
"function f() {" +
" try { while(x) { break } } finally { alert(1) } return 1}"
);
foldSame("function f() { try{ return a } finally { a = 2 } return a; }");
}
public void testIssue291() {
fold("if (true) { f.onchange(); }", "if (1) f.onchange();");
foldSame("if (f) { f.onchange(); }");
foldSame("if (f) { f.bar(); } else { f.onchange(); }");
fold("if (f) { f.bonchange(); }", "f && f.bonchange();");
foldSame("if (f) { f['x'](); }");
}
} |
||
public void testIssue937() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
WarningLevel warnings = WarningLevel.DEFAULT;
warnings.setOptionsForWarningLevel(options);
String code = "" +
"console.log(" +
"/** @type {function():!string} */ ((new x())['abc'])() );";
String result = "" +
"console.log((new x()).abc());";
test(options, code, result);
} | com.google.javascript.jscomp.IntegrationTest::testIssue937 | test/com/google/javascript/jscomp/IntegrationTest.java | 2,430 | test/com/google/javascript/jscomp/IntegrationTest.java | testIssue937 | /*
* 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.Lists;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.CompilerOptions.TracerMode;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.regex.Pattern;
/**
* Tests for {@link PassFactory}.
*
* @author nicksantos@google.com (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 testConstructorCycle() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
test(options,
"/** @return {function()} */ var AsyncTestCase = function() {};\n" +
"/**\n" +
" * @constructor\n" +
" */ Foo = /** @type {function(new:Foo)} */ (AyncTestCase());",
RhinoErrorReporter.PARSE_ERROR);
}
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 testAngularPassOff() {
testSame(createCompilerOptions(),
"/** @ngInject */ function f() {} " +
"/** @ngInject */ function g(a){} " +
"/** @ngInject */ var b = function f(a) {} ");
}
public void testAngularPassOn() {
CompilerOptions options = createCompilerOptions();
options.angularPass = true;
test(options,
"/** @ngInject */ function f() {} " +
"/** @ngInject */ function g(a){} " +
"/** @ngInject */ var b = function f(a, b, c) {} ",
"function f() {} " +
"function g(a) {} g['$inject']=['a'];" +
"var b = function f(a, b, c) {}; b['$inject']=['a', 'b', 'c']");
}
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;" +
"/** @expose */ Foo.prototype.tiger;" +
"function moe(a, b) { return a.meeny + b.miny + a.tiger; }" +
"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+b.tiger" +
"}");
}
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 testGoogDefine1() {
String code = CLOSURE_BOILERPLATE +
"/** @define {boolean} */ goog.define('FLAG', true);";
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.collapseProperties = true;
options.setDefineToBooleanLiteral("FLAG", false);
test(options, code, CLOSURE_COMPILED + " var FLAG = false;");
}
public void testGoogDefine2() {
String code = CLOSURE_BOILERPLATE +
"goog.provide('ns');" +
"/** @define {boolean} */ goog.define('ns.FLAG', true);";
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.collapseProperties = true;
options.setDefineToBooleanLiteral("ns.FLAG", false);
test(options, code, CLOSURE_COMPILED + "var ns$FLAG = false;");
}
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);
// skip i,j,o (reserved)
if (letter >= 'i') {
letter++;
}
if (letter >= 'j') {
letter++;
}
if (letter >= 'o') {
letter++;
}
expected += "a.argz = function() {arguments};";
expected += "function " + letter + "(c){}";
}
code += "var F = new f(); F.argz();";
expected += "var q = new b(); q.argz();";
for (int i = 0; i < 10; i++) {
code += "F.devir" + i + "();";
char letter = (char) ('d' + i);
// skip i,j,o (reserved)
if (letter >= 'i') {
letter++;
}
if (letter >= 'j') {
letter++;
}
if (letter >= 'o') {
letter++;
}
expected += letter + "(q);";
}
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" +
"};";
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 testSuppressCastWarning() {
CompilerOptions options = createCompilerOptions();
options.setWarningLevel(DiagnosticGroups.CHECK_TYPES, CheckLevel.WARNING);
normalizeResults = true;
test(options,
"function f() { var xyz = /** @type {string} */ (0); }",
DiagnosticType.warning(
"JSC_INVALID_CAST", "invalid cast"));
testSame(options,
"/** @suppress {invalidCasts} */\n" +
"function f() { var xyz = /** @type {string} */ (0); }");
testSame(options,
"/** @const */ var g = {};" +
"/** @suppress {invalidCasts} */" +
"g.a = g.b = function() { var xyz = /** @type {string} */ (0); }");
}
public void testLhsCast() {
CompilerOptions options = createCompilerOptions();
test(
options,
"/** @const */ var g = {};" +
"/** @type {number} */ (g.foo) = 3;",
"/** @const */ var g = {};" +
"g.foo = 3;");
}
public void testRenamePrefix() {
String code = "var x = {}; function f(y) {}";
CompilerOptions options = createCompilerOptions();
options.renamePrefix = "G_";
options.variableRenaming = VariableRenamingPolicy.ALL;
test(options, code, "var G_={}; function G_a(a) {}");
}
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 testRenamePrefixNamespaceProtectSideEffects() {
String code = "var x = null; try { +x.FOO; } catch (e) {}";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(
options);
options.renamePrefixNamespace = "_";
test(options, code, "_.x = null; try { +_.x.FOO; } catch (e) {}");
}
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 testGoogDefineClass1() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
level.setTypeBasedOptimizationOptions(options);
String code = "" +
"var ns = {};\n" +
"ns.C = goog.defineClass(null, {\n" +
" /** @constructor */\n" +
" constructor: function () {this.someProperty = 1}\n" +
"});\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 testGoogDefineClass2() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
level.setTypeBasedOptimizationOptions(options);
String code = "" +
"var C = goog.defineClass(null, {\n" +
" /** @constructor */\n" +
" constructor: function () {this.someProperty = 1}\n" +
"});\n" +
"alert(new C().someProperty + new C().someProperty);\n";
assertTrue(options.inlineProperties);
assertTrue(options.collapseProperties);
// CollapseProperties used to prevent inlining this property.
test(options, code, "alert(2);");
}
public void testGoogDefineClass3() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
level.setTypeBasedOptimizationOptions(options);
WarningLevel warnings = WarningLevel.VERBOSE;
warnings.setOptionsForWarningLevel(options);
String code = "" +
"var C = goog.defineClass(null, {\n" +
" /** @constructor */\n" +
" constructor: function () {\n" +
" /** @type {number} */\n" +
" this.someProperty = 1},\n" +
" /** @param {string} a */\n" +
" someMethod: function (a) {}\n" +
"});" +
"var x = new C();\n" +
"x.someMethod(x.someProperty);\n";
assertTrue(options.inlineProperties);
assertTrue(options.collapseProperties);
// CollapseProperties used to prevent inlining this property.
test(options, code, TypeValidator.TYPE_MISMATCH_WARNING);
}
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 testIssue937() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
WarningLevel warnings = WarningLevel.DEFAULT;
warnings.setOptionsForWarningLevel(options);
String code = "" +
"console.log(" +
"/** @type {function():!string} */ ((new x())['abc'])() );";
String result = "" +
"console.log((new x()).abc());";
test(options, code, result);
}
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(a) {\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 = 4500;
// 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 + ";");
// }
// Checks that the summary and the log in the output of PerformanceTracker
// have the expected number of columns
public void testPerfTracker() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream outstream = new PrintStream(output);
Compiler compiler = new Compiler(outstream);
CompilerOptions options = new CompilerOptions();
List<SourceFile> inputs = Lists.newArrayList();
List<SourceFile> externs = Lists.newArrayList();
options.setTracerMode(TracerMode.ALL);
inputs.add(SourceFile.fromCode("foo", "function fun(){}"));
compiler.compile(externs, inputs, options);
outstream.flush();
outstream.close();
Pattern p = Pattern.compile(
".*Summary:\npass,runtime,runs,changingRuns,reduction,gzReduction" +
".*TOTAL:" +
"\nRuntime\\(ms\\): [0-9]+" +
"\n#Runs: [0-9]+" +
"\n#Changing runs: [0-9]+" +
"\n#Loopable runs: [0-9]+" +
"\n#Changing loopable runs: [0-9]+" +
"\nReduction\\(bytes\\): [0-9]+" +
"\nGzReduction\\(bytes\\): [0-9]+" +
"\nSize\\(bytes\\): [0-9]+" +
"\nGzSize\\(bytes\\): [0-9]+" +
"\n\nLog:\n" +
"pass,runtime,runs,changingRuns,reduction,gzReduction,size,gzSize.*",
Pattern.DOTALL);
assertTrue(p.matcher(output.toString()).matches());
}
// isEquivalentTo returns false for alpha-equivalent nodes
public void testIsEquivalentTo() {
String[] input1 = {"function f(z) { return z; }"};
String[] input2 = {"function f(y) { return y; }"};
CompilerOptions options = new CompilerOptions();
Node out1 = parse(input1, options, false);
Node out2 = parse(input2, options, false);
assertFalse(out1.isEquivalentTo(out2));
}
/** 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 `testIssue937` for the issue `Closure-937`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-937
//
// ## Issue-Title:
// Casting a function before calling it produces bad code and breaks plugin code
//
// ## Issue-Description:
// 1. Compile this code with ADVANCED\_OPTIMIZATIONS:
// console.log( /\*\* @type {function(!string):!string} \*/ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable'])( '$version' ) );
//
// produces:
//
// 'use strict';console.log((0,(new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable)("$version"));
//
// 2. Compare with this code:
// console.log( /\*\* @type {!string} \*/ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable']( '$version' )) )
//
// produces:
//
// 'use strict';console.log((new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version"));
//
//
// Notice the (0,...) wrapping around the GetVariable function in the first example. This causes the call to fail in every browser (this code is IE-only but it's just for a minimal example). The second version produces a warning that the type of GetVariable could not be determined (I enabled type warnings), and it wouldn't be possible to define these in an externs file without making a horrible mess.
//
// This applies to all cases where functions are cast, but only causes problems (other than bloat) with plugins like this. It seems to serve no purpose whatsoever, so I assume it is a bug.
//
// Running on a mac, not sure what version but it reports Built on: 2013/02/12 17:00, so will have been downloaded about that time.
//
//
public void testIssue937() {
| 2,430 | 129 | 2,417 | test/com/google/javascript/jscomp/IntegrationTest.java | test | ```markdown
## Issue-ID: Closure-937
## Issue-Title:
Casting a function before calling it produces bad code and breaks plugin code
## Issue-Description:
1. Compile this code with ADVANCED\_OPTIMIZATIONS:
console.log( /\*\* @type {function(!string):!string} \*/ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable'])( '$version' ) );
produces:
'use strict';console.log((0,(new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable)("$version"));
2. Compare with this code:
console.log( /\*\* @type {!string} \*/ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable']( '$version' )) )
produces:
'use strict';console.log((new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version"));
Notice the (0,...) wrapping around the GetVariable function in the first example. This causes the call to fail in every browser (this code is IE-only but it's just for a minimal example). The second version produces a warning that the type of GetVariable could not be determined (I enabled type warnings), and it wouldn't be possible to define these in an externs file without making a horrible mess.
This applies to all cases where functions are cast, but only causes problems (other than bloat) with plugins like this. It seems to serve no purpose whatsoever, so I assume it is a bug.
Running on a mac, not sure what version but it reports Built on: 2013/02/12 17:00, so will have been downloaded about that time.
```
You are a professional Java test case writer, please create a test case named `testIssue937` for the issue `Closure-937`, utilizing the provided issue report information and the following function signature.
```java
public void testIssue937() {
```
| 2,417 | [
"com.google.javascript.jscomp.PrepareAst"
] | 5f118375a434aedd01f48bb5ea2e9e7a68f8a440f6b38d30ea630ed135d311a9 | public void testIssue937() | // You are a professional Java test case writer, please create a test case named `testIssue937` for the issue `Closure-937`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-937
//
// ## Issue-Title:
// Casting a function before calling it produces bad code and breaks plugin code
//
// ## Issue-Description:
// 1. Compile this code with ADVANCED\_OPTIMIZATIONS:
// console.log( /\*\* @type {function(!string):!string} \*/ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable'])( '$version' ) );
//
// produces:
//
// 'use strict';console.log((0,(new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable)("$version"));
//
// 2. Compare with this code:
// console.log( /\*\* @type {!string} \*/ ((new window.ActiveXObject( 'ShockwaveFlash.ShockwaveFlash' ))['GetVariable']( '$version' )) )
//
// produces:
//
// 'use strict';console.log((new window.ActiveXObject("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version"));
//
//
// Notice the (0,...) wrapping around the GetVariable function in the first example. This causes the call to fail in every browser (this code is IE-only but it's just for a minimal example). The second version produces a warning that the type of GetVariable could not be determined (I enabled type warnings), and it wouldn't be possible to define these in an externs file without making a horrible mess.
//
// This applies to all cases where functions are cast, but only causes problems (other than bloat) with plugins like this. It seems to serve no purpose whatsoever, so I assume it is a bug.
//
// Running on a mac, not sure what version but it reports Built on: 2013/02/12 17:00, so will have been downloaded about that time.
//
//
| 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.Lists;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.CompilerOptions.TracerMode;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.regex.Pattern;
/**
* Tests for {@link PassFactory}.
*
* @author nicksantos@google.com (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 testConstructorCycle() {
CompilerOptions options = createCompilerOptions();
options.checkTypes = true;
test(options,
"/** @return {function()} */ var AsyncTestCase = function() {};\n" +
"/**\n" +
" * @constructor\n" +
" */ Foo = /** @type {function(new:Foo)} */ (AyncTestCase());",
RhinoErrorReporter.PARSE_ERROR);
}
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 testAngularPassOff() {
testSame(createCompilerOptions(),
"/** @ngInject */ function f() {} " +
"/** @ngInject */ function g(a){} " +
"/** @ngInject */ var b = function f(a) {} ");
}
public void testAngularPassOn() {
CompilerOptions options = createCompilerOptions();
options.angularPass = true;
test(options,
"/** @ngInject */ function f() {} " +
"/** @ngInject */ function g(a){} " +
"/** @ngInject */ var b = function f(a, b, c) {} ",
"function f() {} " +
"function g(a) {} g['$inject']=['a'];" +
"var b = function f(a, b, c) {}; b['$inject']=['a', 'b', 'c']");
}
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;" +
"/** @expose */ Foo.prototype.tiger;" +
"function moe(a, b) { return a.meeny + b.miny + a.tiger; }" +
"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+b.tiger" +
"}");
}
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 testGoogDefine1() {
String code = CLOSURE_BOILERPLATE +
"/** @define {boolean} */ goog.define('FLAG', true);";
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.collapseProperties = true;
options.setDefineToBooleanLiteral("FLAG", false);
test(options, code, CLOSURE_COMPILED + " var FLAG = false;");
}
public void testGoogDefine2() {
String code = CLOSURE_BOILERPLATE +
"goog.provide('ns');" +
"/** @define {boolean} */ goog.define('ns.FLAG', true);";
CompilerOptions options = createCompilerOptions();
options.closurePass = true;
options.collapseProperties = true;
options.setDefineToBooleanLiteral("ns.FLAG", false);
test(options, code, CLOSURE_COMPILED + "var ns$FLAG = false;");
}
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);
// skip i,j,o (reserved)
if (letter >= 'i') {
letter++;
}
if (letter >= 'j') {
letter++;
}
if (letter >= 'o') {
letter++;
}
expected += "a.argz = function() {arguments};";
expected += "function " + letter + "(c){}";
}
code += "var F = new f(); F.argz();";
expected += "var q = new b(); q.argz();";
for (int i = 0; i < 10; i++) {
code += "F.devir" + i + "();";
char letter = (char) ('d' + i);
// skip i,j,o (reserved)
if (letter >= 'i') {
letter++;
}
if (letter >= 'j') {
letter++;
}
if (letter >= 'o') {
letter++;
}
expected += letter + "(q);";
}
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" +
"};";
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 testSuppressCastWarning() {
CompilerOptions options = createCompilerOptions();
options.setWarningLevel(DiagnosticGroups.CHECK_TYPES, CheckLevel.WARNING);
normalizeResults = true;
test(options,
"function f() { var xyz = /** @type {string} */ (0); }",
DiagnosticType.warning(
"JSC_INVALID_CAST", "invalid cast"));
testSame(options,
"/** @suppress {invalidCasts} */\n" +
"function f() { var xyz = /** @type {string} */ (0); }");
testSame(options,
"/** @const */ var g = {};" +
"/** @suppress {invalidCasts} */" +
"g.a = g.b = function() { var xyz = /** @type {string} */ (0); }");
}
public void testLhsCast() {
CompilerOptions options = createCompilerOptions();
test(
options,
"/** @const */ var g = {};" +
"/** @type {number} */ (g.foo) = 3;",
"/** @const */ var g = {};" +
"g.foo = 3;");
}
public void testRenamePrefix() {
String code = "var x = {}; function f(y) {}";
CompilerOptions options = createCompilerOptions();
options.renamePrefix = "G_";
options.variableRenaming = VariableRenamingPolicy.ALL;
test(options, code, "var G_={}; function G_a(a) {}");
}
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 testRenamePrefixNamespaceProtectSideEffects() {
String code = "var x = null; try { +x.FOO; } catch (e) {}";
CompilerOptions options = createCompilerOptions();
testSame(options, code);
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(
options);
options.renamePrefixNamespace = "_";
test(options, code, "_.x = null; try { +_.x.FOO; } catch (e) {}");
}
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 testGoogDefineClass1() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
level.setTypeBasedOptimizationOptions(options);
String code = "" +
"var ns = {};\n" +
"ns.C = goog.defineClass(null, {\n" +
" /** @constructor */\n" +
" constructor: function () {this.someProperty = 1}\n" +
"});\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 testGoogDefineClass2() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
level.setTypeBasedOptimizationOptions(options);
String code = "" +
"var C = goog.defineClass(null, {\n" +
" /** @constructor */\n" +
" constructor: function () {this.someProperty = 1}\n" +
"});\n" +
"alert(new C().someProperty + new C().someProperty);\n";
assertTrue(options.inlineProperties);
assertTrue(options.collapseProperties);
// CollapseProperties used to prevent inlining this property.
test(options, code, "alert(2);");
}
public void testGoogDefineClass3() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.ADVANCED_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
level.setTypeBasedOptimizationOptions(options);
WarningLevel warnings = WarningLevel.VERBOSE;
warnings.setOptionsForWarningLevel(options);
String code = "" +
"var C = goog.defineClass(null, {\n" +
" /** @constructor */\n" +
" constructor: function () {\n" +
" /** @type {number} */\n" +
" this.someProperty = 1},\n" +
" /** @param {string} a */\n" +
" someMethod: function (a) {}\n" +
"});" +
"var x = new C();\n" +
"x.someMethod(x.someProperty);\n";
assertTrue(options.inlineProperties);
assertTrue(options.collapseProperties);
// CollapseProperties used to prevent inlining this property.
test(options, code, TypeValidator.TYPE_MISMATCH_WARNING);
}
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 testIssue937() {
CompilerOptions options = createCompilerOptions();
CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
level.setOptionsForCompilationLevel(options);
WarningLevel warnings = WarningLevel.DEFAULT;
warnings.setOptionsForWarningLevel(options);
String code = "" +
"console.log(" +
"/** @type {function():!string} */ ((new x())['abc'])() );";
String result = "" +
"console.log((new x()).abc());";
test(options, code, result);
}
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(a) {\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 = 4500;
// 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 + ";");
// }
// Checks that the summary and the log in the output of PerformanceTracker
// have the expected number of columns
public void testPerfTracker() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
PrintStream outstream = new PrintStream(output);
Compiler compiler = new Compiler(outstream);
CompilerOptions options = new CompilerOptions();
List<SourceFile> inputs = Lists.newArrayList();
List<SourceFile> externs = Lists.newArrayList();
options.setTracerMode(TracerMode.ALL);
inputs.add(SourceFile.fromCode("foo", "function fun(){}"));
compiler.compile(externs, inputs, options);
outstream.flush();
outstream.close();
Pattern p = Pattern.compile(
".*Summary:\npass,runtime,runs,changingRuns,reduction,gzReduction" +
".*TOTAL:" +
"\nRuntime\\(ms\\): [0-9]+" +
"\n#Runs: [0-9]+" +
"\n#Changing runs: [0-9]+" +
"\n#Loopable runs: [0-9]+" +
"\n#Changing loopable runs: [0-9]+" +
"\nReduction\\(bytes\\): [0-9]+" +
"\nGzReduction\\(bytes\\): [0-9]+" +
"\nSize\\(bytes\\): [0-9]+" +
"\nGzSize\\(bytes\\): [0-9]+" +
"\n\nLog:\n" +
"pass,runtime,runs,changingRuns,reduction,gzReduction,size,gzSize.*",
Pattern.DOTALL);
assertTrue(p.matcher(output.toString()).matches());
}
// isEquivalentTo returns false for alpha-equivalent nodes
public void testIsEquivalentTo() {
String[] input1 = {"function f(z) { return z; }"};
String[] input2 = {"function f(y) { return y; }"};
CompilerOptions options = new CompilerOptions();
Node out1 = parse(input1, options, false);
Node out2 = parse(input2, options, false);
assertFalse(out1.isEquivalentTo(out2));
}
/** Creates a CompilerOptions object with google coding conventions. */
@Override
protected CompilerOptions createCompilerOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(new GoogleCodingConvention());
return options;
}
} |
||
@Test
public void testHWRuleEx1() {
// From
// http://www.archives.gov/research_room/genealogy/census/soundex.html:
// Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1
// for the F). It is not coded A-226.
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft"));
Assert.assertEquals("Y330", this.getStringEncoder().encode("yehudit"));
Assert.assertEquals("Y330", this.getStringEncoder().encode("yhwdyt"));
} | org.apache.commons.codec.language.SoundexTest::testHWRuleEx1 | src/test/java/org/apache/commons/codec/language/SoundexTest.java | 232 | src/test/java/org/apache/commons/codec/language/SoundexTest.java | testHWRuleEx1 | /*
* 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.
*/
// (FYI: Formatted and sorted with Eclipse)
package org.apache.commons.codec.language;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringEncoderAbstractTest;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests {@link Soundex}.
*
* <p>Keep this file in UTF-8 encoding for proper Javadoc processing.</p>
*
* @version $Id$
*/
public class SoundexTest extends StringEncoderAbstractTest<Soundex> {
@Override
protected Soundex createStringEncoder() {
return new Soundex();
}
@Test
public void testB650() throws EncoderException {
this.checkEncodingVariations("B650", new String[]{
"BARHAM",
"BARONE",
"BARRON",
"BERNA",
"BIRNEY",
"BIRNIE",
"BOOROM",
"BOREN",
"BORN",
"BOURN",
"BOURNE",
"BOWRON",
"BRAIN",
"BRAME",
"BRANN",
"BRAUN",
"BREEN",
"BRIEN",
"BRIM",
"BRIMM",
"BRINN",
"BRION",
"BROOM",
"BROOME",
"BROWN",
"BROWNE",
"BRUEN",
"BRUHN",
"BRUIN",
"BRUMM",
"BRUN",
"BRUNO",
"BRYAN",
"BURIAN",
"BURN",
"BURNEY",
"BYRAM",
"BYRNE",
"BYRON",
"BYRUM"});
}
@Test
public void testBadCharacters() {
Assert.assertEquals("H452", this.getStringEncoder().encode("HOL>MES"));
}
@Test
public void testDifference() throws EncoderException {
// Edge cases
Assert.assertEquals(0, this.getStringEncoder().difference(null, null));
Assert.assertEquals(0, this.getStringEncoder().difference("", ""));
Assert.assertEquals(0, this.getStringEncoder().difference(" ", " "));
// Normal cases
Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe"));
Assert.assertEquals(2, this.getStringEncoder().difference("Ann", "Andrew"));
Assert.assertEquals(1, this.getStringEncoder().difference("Margaret", "Andrew"));
Assert.assertEquals(0, this.getStringEncoder().difference("Janet", "Margaret"));
// Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp
Assert.assertEquals(4, this.getStringEncoder().difference("Green", "Greene"));
Assert.assertEquals(0, this.getStringEncoder().difference("Blotchet-Halls", "Greene"));
// Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp
Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe"));
Assert.assertEquals(4, this.getStringEncoder().difference("Smithers", "Smythers"));
Assert.assertEquals(2, this.getStringEncoder().difference("Anothers", "Brothers"));
}
@Test
public void testEncodeBasic() {
Assert.assertEquals("T235", this.getStringEncoder().encode("testing"));
Assert.assertEquals("T000", this.getStringEncoder().encode("The"));
Assert.assertEquals("Q200", this.getStringEncoder().encode("quick"));
Assert.assertEquals("B650", this.getStringEncoder().encode("brown"));
Assert.assertEquals("F200", this.getStringEncoder().encode("fox"));
Assert.assertEquals("J513", this.getStringEncoder().encode("jumped"));
Assert.assertEquals("O160", this.getStringEncoder().encode("over"));
Assert.assertEquals("T000", this.getStringEncoder().encode("the"));
Assert.assertEquals("L200", this.getStringEncoder().encode("lazy"));
Assert.assertEquals("D200", this.getStringEncoder().encode("dogs"));
}
/**
* Examples from http://www.bradandkathy.com/genealogy/overviewofsoundex.html
*/
@Test
public void testEncodeBatch2() {
Assert.assertEquals("A462", this.getStringEncoder().encode("Allricht"));
Assert.assertEquals("E166", this.getStringEncoder().encode("Eberhard"));
Assert.assertEquals("E521", this.getStringEncoder().encode("Engebrethson"));
Assert.assertEquals("H512", this.getStringEncoder().encode("Heimbach"));
Assert.assertEquals("H524", this.getStringEncoder().encode("Hanselmann"));
Assert.assertEquals("H431", this.getStringEncoder().encode("Hildebrand"));
Assert.assertEquals("K152", this.getStringEncoder().encode("Kavanagh"));
Assert.assertEquals("L530", this.getStringEncoder().encode("Lind"));
Assert.assertEquals("L222", this.getStringEncoder().encode("Lukaschowsky"));
Assert.assertEquals("M235", this.getStringEncoder().encode("McDonnell"));
Assert.assertEquals("M200", this.getStringEncoder().encode("McGee"));
Assert.assertEquals("O155", this.getStringEncoder().encode("Opnian"));
Assert.assertEquals("O155", this.getStringEncoder().encode("Oppenheimer"));
Assert.assertEquals("R355", this.getStringEncoder().encode("Riedemanas"));
Assert.assertEquals("Z300", this.getStringEncoder().encode("Zita"));
Assert.assertEquals("Z325", this.getStringEncoder().encode("Zitzmeinn"));
}
/**
* Examples from http://www.archives.gov/research_room/genealogy/census/soundex.html
*/
@Test
public void testEncodeBatch3() {
Assert.assertEquals("W252", this.getStringEncoder().encode("Washington"));
Assert.assertEquals("L000", this.getStringEncoder().encode("Lee"));
Assert.assertEquals("G362", this.getStringEncoder().encode("Gutierrez"));
Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister"));
Assert.assertEquals("J250", this.getStringEncoder().encode("Jackson"));
Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak"));
// For VanDeusen: D-250 (D, 2 for the S, 5 for the N, 0 added) is also
// possible.
Assert.assertEquals("V532", this.getStringEncoder().encode("VanDeusen"));
}
/**
* Examples from: http://www.myatt.demon.co.uk/sxalg.htm
*/
@Test
public void testEncodeBatch4() {
Assert.assertEquals("H452", this.getStringEncoder().encode("HOLMES"));
Assert.assertEquals("A355", this.getStringEncoder().encode("ADOMOMI"));
Assert.assertEquals("V536", this.getStringEncoder().encode("VONDERLEHR"));
Assert.assertEquals("B400", this.getStringEncoder().encode("BALL"));
Assert.assertEquals("S000", this.getStringEncoder().encode("SHAW"));
Assert.assertEquals("J250", this.getStringEncoder().encode("JACKSON"));
Assert.assertEquals("S545", this.getStringEncoder().encode("SCANLON"));
Assert.assertEquals("S532", this.getStringEncoder().encode("SAINTJOHN"));
}
@Test
public void testEncodeIgnoreApostrophes() throws EncoderException {
this.checkEncodingVariations("O165", new String[]{
"OBrien",
"'OBrien",
"O'Brien",
"OB'rien",
"OBr'ien",
"OBri'en",
"OBrie'n",
"OBrien'"});
}
/**
* Test data from http://www.myatt.demon.co.uk/sxalg.htm
*
* @throws EncoderException
*/
@Test
public void testEncodeIgnoreHyphens() throws EncoderException {
this.checkEncodingVariations("K525", new String[]{
"KINGSMITH",
"-KINGSMITH",
"K-INGSMITH",
"KI-NGSMITH",
"KIN-GSMITH",
"KING-SMITH",
"KINGS-MITH",
"KINGSM-ITH",
"KINGSMI-TH",
"KINGSMIT-H",
"KINGSMITH-"});
}
@Test
public void testEncodeIgnoreTrimmable() {
Assert.assertEquals("W252", this.getStringEncoder().encode(" \t\n\r Washington \t\n\r "));
}
/**
* Consonants from the same code group separated by W or H are treated as one.
*/
@Test
public void testHWRuleEx1() {
// From
// http://www.archives.gov/research_room/genealogy/census/soundex.html:
// Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1
// for the F). It is not coded A-226.
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft"));
Assert.assertEquals("Y330", this.getStringEncoder().encode("yehudit"));
Assert.assertEquals("Y330", this.getStringEncoder().encode("yhwdyt"));
}
/**
* Consonants from the same code group separated by W or H are treated as one.
*
* Test data from http://www.myatt.demon.co.uk/sxalg.htm
*/
@Test
public void testHWRuleEx2() {
Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTHDAVIS"));
Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTH-DAVIS"));
}
/**
* Consonants from the same code group separated by W or H are treated as one.
*
* @throws EncoderException
*/
@Test
public void testHWRuleEx3() throws EncoderException {
Assert.assertEquals("S460", this.getStringEncoder().encode("Sgler"));
Assert.assertEquals("S460", this.getStringEncoder().encode("Swhgler"));
// Also S460:
this.checkEncodingVariations("S460", new String[]{
"SAILOR",
"SALYER",
"SAYLOR",
"SCHALLER",
"SCHELLER",
"SCHILLER",
"SCHOOLER",
"SCHULER",
"SCHUYLER",
"SEILER",
"SEYLER",
"SHOLAR",
"SHULER",
"SILAR",
"SILER",
"SILLER"});
}
/**
* Examples for MS SQLServer from
* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp
*/
@Test
public void testMsSqlServer1() {
Assert.assertEquals("S530", this.getStringEncoder().encode("Smith"));
Assert.assertEquals("S530", this.getStringEncoder().encode("Smythe"));
}
/**
* Examples for MS SQLServer from
* http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support
* /kb/articles/Q100/3/65.asp&NoWebContent=1
*
* @throws EncoderException
*/
@Test
public void testMsSqlServer2() throws EncoderException {
this.checkEncodingVariations("E625", new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"});
}
/**
* Examples for MS SQLServer from http://databases.about.com/library/weekly/aa042901a.htm
*/
@Test
public void testMsSqlServer3() {
Assert.assertEquals("A500", this.getStringEncoder().encode("Ann"));
Assert.assertEquals("A536", this.getStringEncoder().encode("Andrew"));
Assert.assertEquals("J530", this.getStringEncoder().encode("Janet"));
Assert.assertEquals("M626", this.getStringEncoder().encode("Margaret"));
Assert.assertEquals("S315", this.getStringEncoder().encode("Steven"));
Assert.assertEquals("M240", this.getStringEncoder().encode("Michael"));
Assert.assertEquals("R163", this.getStringEncoder().encode("Robert"));
Assert.assertEquals("L600", this.getStringEncoder().encode("Laura"));
Assert.assertEquals("A500", this.getStringEncoder().encode("Anne"));
}
/**
* https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56
*/
@Test
public void testNewInstance() {
Assert.assertEquals("W452", new Soundex().soundex("Williams"));
}
@Test
public void testNewInstance2() {
Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("Williams"));
}
@Test
public void testNewInstance3() {
Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING).soundex("Williams"));
}
@Test
public void testSoundexUtilsConstructable() {
new SoundexUtils();
}
@Test
public void testSoundexUtilsNullBehaviour() {
Assert.assertEquals(null, SoundexUtils.clean(null));
Assert.assertEquals("", SoundexUtils.clean(""));
Assert.assertEquals(0, SoundexUtils.differenceEncoded(null, ""));
Assert.assertEquals(0, SoundexUtils.differenceEncoded("", null));
}
/**
* https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56
*/
@Test
public void testUsEnglishStatic() {
Assert.assertEquals("W452", Soundex.US_ENGLISH.soundex("Williams"));
}
/**
* Fancy characters are not mapped by the default US mapping.
*
* http://issues.apache.org/bugzilla/show_bug.cgi?id=29080
*/
@Test
public void testUsMappingEWithAcute() {
Assert.assertEquals("E000", this.getStringEncoder().encode("e"));
if (Character.isLetter('\u00e9')) { // e-acute
try {
// uppercase E-acute
Assert.assertEquals("\u00c9000", this.getStringEncoder().encode("\u00e9"));
Assert.fail("Expected IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
// expected
}
} else {
Assert.assertEquals("", this.getStringEncoder().encode("\u00e9"));
}
}
/**
* Fancy characters are not mapped by the default US mapping.
*
* http://issues.apache.org/bugzilla/show_bug.cgi?id=29080
*/
@Test
public void testUsMappingOWithDiaeresis() {
Assert.assertEquals("O000", this.getStringEncoder().encode("o"));
if (Character.isLetter('\u00f6')) { // o-umlaut
try {
// uppercase O-umlaut
Assert.assertEquals("\u00d6000", this.getStringEncoder().encode("\u00f6"));
Assert.fail("Expected IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
// expected
}
} else {
Assert.assertEquals("", this.getStringEncoder().encode("\u00f6"));
}
}
/**
* Tests example from http://en.wikipedia.org/wiki/Soundex#American_Soundex as of 2015-03-22.
*/
@Test
public void testWikipediaAmericanSoundex() {
Assert.assertEquals("R163", this.getStringEncoder().encode("Robert"));
Assert.assertEquals("R163", this.getStringEncoder().encode("Rupert"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft"));
Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak"));
Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister"));
}
} | // You are a professional Java test case writer, please create a test case named `testHWRuleEx1` for the issue `Codec-CODEC-199`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-199
//
// ## Issue-Title:
// Bug in HW rule in Soundex
//
// ## Issue-Description:
//
// The Soundex algorithm says that if two characters that map to the same code are separated by H or W, the second one is not encoded.
//
// However, in the implementation (in Soundex.getMappingCode() line 191), a character that is preceded by two characters that are either H or W, is not encoded, regardless of what the last consonant was.
//
// Source: <http://en.wikipedia.org/wiki/Soundex#American_Soundex>
//
//
//
//
//
@Test
public void testHWRuleEx1() {
| 232 | /**
* Consonants from the same code group separated by W or H are treated as one.
*/ | 15 | 222 | src/test/java/org/apache/commons/codec/language/SoundexTest.java | src/test/java | ```markdown
## Issue-ID: Codec-CODEC-199
## Issue-Title:
Bug in HW rule in Soundex
## Issue-Description:
The Soundex algorithm says that if two characters that map to the same code are separated by H or W, the second one is not encoded.
However, in the implementation (in Soundex.getMappingCode() line 191), a character that is preceded by two characters that are either H or W, is not encoded, regardless of what the last consonant was.
Source: <http://en.wikipedia.org/wiki/Soundex#American_Soundex>
```
You are a professional Java test case writer, please create a test case named `testHWRuleEx1` for the issue `Codec-CODEC-199`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testHWRuleEx1() {
```
| 222 | [
"org.apache.commons.codec.language.Soundex"
] | 5f6f8bceffc1d4afee0c7559fcfa2296cf3ee3233158d3a916ab76b309e1feb0 | @Test
public void testHWRuleEx1() | // You are a professional Java test case writer, please create a test case named `testHWRuleEx1` for the issue `Codec-CODEC-199`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Codec-CODEC-199
//
// ## Issue-Title:
// Bug in HW rule in Soundex
//
// ## Issue-Description:
//
// The Soundex algorithm says that if two characters that map to the same code are separated by H or W, the second one is not encoded.
//
// However, in the implementation (in Soundex.getMappingCode() line 191), a character that is preceded by two characters that are either H or W, is not encoded, regardless of what the last consonant was.
//
// Source: <http://en.wikipedia.org/wiki/Soundex#American_Soundex>
//
//
//
//
//
| 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.
*/
// (FYI: Formatted and sorted with Eclipse)
package org.apache.commons.codec.language;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.StringEncoderAbstractTest;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests {@link Soundex}.
*
* <p>Keep this file in UTF-8 encoding for proper Javadoc processing.</p>
*
* @version $Id$
*/
public class SoundexTest extends StringEncoderAbstractTest<Soundex> {
@Override
protected Soundex createStringEncoder() {
return new Soundex();
}
@Test
public void testB650() throws EncoderException {
this.checkEncodingVariations("B650", new String[]{
"BARHAM",
"BARONE",
"BARRON",
"BERNA",
"BIRNEY",
"BIRNIE",
"BOOROM",
"BOREN",
"BORN",
"BOURN",
"BOURNE",
"BOWRON",
"BRAIN",
"BRAME",
"BRANN",
"BRAUN",
"BREEN",
"BRIEN",
"BRIM",
"BRIMM",
"BRINN",
"BRION",
"BROOM",
"BROOME",
"BROWN",
"BROWNE",
"BRUEN",
"BRUHN",
"BRUIN",
"BRUMM",
"BRUN",
"BRUNO",
"BRYAN",
"BURIAN",
"BURN",
"BURNEY",
"BYRAM",
"BYRNE",
"BYRON",
"BYRUM"});
}
@Test
public void testBadCharacters() {
Assert.assertEquals("H452", this.getStringEncoder().encode("HOL>MES"));
}
@Test
public void testDifference() throws EncoderException {
// Edge cases
Assert.assertEquals(0, this.getStringEncoder().difference(null, null));
Assert.assertEquals(0, this.getStringEncoder().difference("", ""));
Assert.assertEquals(0, this.getStringEncoder().difference(" ", " "));
// Normal cases
Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe"));
Assert.assertEquals(2, this.getStringEncoder().difference("Ann", "Andrew"));
Assert.assertEquals(1, this.getStringEncoder().difference("Margaret", "Andrew"));
Assert.assertEquals(0, this.getStringEncoder().difference("Janet", "Margaret"));
// Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp
Assert.assertEquals(4, this.getStringEncoder().difference("Green", "Greene"));
Assert.assertEquals(0, this.getStringEncoder().difference("Blotchet-Halls", "Greene"));
// Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp
Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe"));
Assert.assertEquals(4, this.getStringEncoder().difference("Smithers", "Smythers"));
Assert.assertEquals(2, this.getStringEncoder().difference("Anothers", "Brothers"));
}
@Test
public void testEncodeBasic() {
Assert.assertEquals("T235", this.getStringEncoder().encode("testing"));
Assert.assertEquals("T000", this.getStringEncoder().encode("The"));
Assert.assertEquals("Q200", this.getStringEncoder().encode("quick"));
Assert.assertEquals("B650", this.getStringEncoder().encode("brown"));
Assert.assertEquals("F200", this.getStringEncoder().encode("fox"));
Assert.assertEquals("J513", this.getStringEncoder().encode("jumped"));
Assert.assertEquals("O160", this.getStringEncoder().encode("over"));
Assert.assertEquals("T000", this.getStringEncoder().encode("the"));
Assert.assertEquals("L200", this.getStringEncoder().encode("lazy"));
Assert.assertEquals("D200", this.getStringEncoder().encode("dogs"));
}
/**
* Examples from http://www.bradandkathy.com/genealogy/overviewofsoundex.html
*/
@Test
public void testEncodeBatch2() {
Assert.assertEquals("A462", this.getStringEncoder().encode("Allricht"));
Assert.assertEquals("E166", this.getStringEncoder().encode("Eberhard"));
Assert.assertEquals("E521", this.getStringEncoder().encode("Engebrethson"));
Assert.assertEquals("H512", this.getStringEncoder().encode("Heimbach"));
Assert.assertEquals("H524", this.getStringEncoder().encode("Hanselmann"));
Assert.assertEquals("H431", this.getStringEncoder().encode("Hildebrand"));
Assert.assertEquals("K152", this.getStringEncoder().encode("Kavanagh"));
Assert.assertEquals("L530", this.getStringEncoder().encode("Lind"));
Assert.assertEquals("L222", this.getStringEncoder().encode("Lukaschowsky"));
Assert.assertEquals("M235", this.getStringEncoder().encode("McDonnell"));
Assert.assertEquals("M200", this.getStringEncoder().encode("McGee"));
Assert.assertEquals("O155", this.getStringEncoder().encode("Opnian"));
Assert.assertEquals("O155", this.getStringEncoder().encode("Oppenheimer"));
Assert.assertEquals("R355", this.getStringEncoder().encode("Riedemanas"));
Assert.assertEquals("Z300", this.getStringEncoder().encode("Zita"));
Assert.assertEquals("Z325", this.getStringEncoder().encode("Zitzmeinn"));
}
/**
* Examples from http://www.archives.gov/research_room/genealogy/census/soundex.html
*/
@Test
public void testEncodeBatch3() {
Assert.assertEquals("W252", this.getStringEncoder().encode("Washington"));
Assert.assertEquals("L000", this.getStringEncoder().encode("Lee"));
Assert.assertEquals("G362", this.getStringEncoder().encode("Gutierrez"));
Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister"));
Assert.assertEquals("J250", this.getStringEncoder().encode("Jackson"));
Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak"));
// For VanDeusen: D-250 (D, 2 for the S, 5 for the N, 0 added) is also
// possible.
Assert.assertEquals("V532", this.getStringEncoder().encode("VanDeusen"));
}
/**
* Examples from: http://www.myatt.demon.co.uk/sxalg.htm
*/
@Test
public void testEncodeBatch4() {
Assert.assertEquals("H452", this.getStringEncoder().encode("HOLMES"));
Assert.assertEquals("A355", this.getStringEncoder().encode("ADOMOMI"));
Assert.assertEquals("V536", this.getStringEncoder().encode("VONDERLEHR"));
Assert.assertEquals("B400", this.getStringEncoder().encode("BALL"));
Assert.assertEquals("S000", this.getStringEncoder().encode("SHAW"));
Assert.assertEquals("J250", this.getStringEncoder().encode("JACKSON"));
Assert.assertEquals("S545", this.getStringEncoder().encode("SCANLON"));
Assert.assertEquals("S532", this.getStringEncoder().encode("SAINTJOHN"));
}
@Test
public void testEncodeIgnoreApostrophes() throws EncoderException {
this.checkEncodingVariations("O165", new String[]{
"OBrien",
"'OBrien",
"O'Brien",
"OB'rien",
"OBr'ien",
"OBri'en",
"OBrie'n",
"OBrien'"});
}
/**
* Test data from http://www.myatt.demon.co.uk/sxalg.htm
*
* @throws EncoderException
*/
@Test
public void testEncodeIgnoreHyphens() throws EncoderException {
this.checkEncodingVariations("K525", new String[]{
"KINGSMITH",
"-KINGSMITH",
"K-INGSMITH",
"KI-NGSMITH",
"KIN-GSMITH",
"KING-SMITH",
"KINGS-MITH",
"KINGSM-ITH",
"KINGSMI-TH",
"KINGSMIT-H",
"KINGSMITH-"});
}
@Test
public void testEncodeIgnoreTrimmable() {
Assert.assertEquals("W252", this.getStringEncoder().encode(" \t\n\r Washington \t\n\r "));
}
/**
* Consonants from the same code group separated by W or H are treated as one.
*/
@Test
public void testHWRuleEx1() {
// From
// http://www.archives.gov/research_room/genealogy/census/soundex.html:
// Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1
// for the F). It is not coded A-226.
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft"));
Assert.assertEquals("Y330", this.getStringEncoder().encode("yehudit"));
Assert.assertEquals("Y330", this.getStringEncoder().encode("yhwdyt"));
}
/**
* Consonants from the same code group separated by W or H are treated as one.
*
* Test data from http://www.myatt.demon.co.uk/sxalg.htm
*/
@Test
public void testHWRuleEx2() {
Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTHDAVIS"));
Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTH-DAVIS"));
}
/**
* Consonants from the same code group separated by W or H are treated as one.
*
* @throws EncoderException
*/
@Test
public void testHWRuleEx3() throws EncoderException {
Assert.assertEquals("S460", this.getStringEncoder().encode("Sgler"));
Assert.assertEquals("S460", this.getStringEncoder().encode("Swhgler"));
// Also S460:
this.checkEncodingVariations("S460", new String[]{
"SAILOR",
"SALYER",
"SAYLOR",
"SCHALLER",
"SCHELLER",
"SCHILLER",
"SCHOOLER",
"SCHULER",
"SCHUYLER",
"SEILER",
"SEYLER",
"SHOLAR",
"SHULER",
"SILAR",
"SILER",
"SILLER"});
}
/**
* Examples for MS SQLServer from
* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp
*/
@Test
public void testMsSqlServer1() {
Assert.assertEquals("S530", this.getStringEncoder().encode("Smith"));
Assert.assertEquals("S530", this.getStringEncoder().encode("Smythe"));
}
/**
* Examples for MS SQLServer from
* http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support
* /kb/articles/Q100/3/65.asp&NoWebContent=1
*
* @throws EncoderException
*/
@Test
public void testMsSqlServer2() throws EncoderException {
this.checkEncodingVariations("E625", new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"});
}
/**
* Examples for MS SQLServer from http://databases.about.com/library/weekly/aa042901a.htm
*/
@Test
public void testMsSqlServer3() {
Assert.assertEquals("A500", this.getStringEncoder().encode("Ann"));
Assert.assertEquals("A536", this.getStringEncoder().encode("Andrew"));
Assert.assertEquals("J530", this.getStringEncoder().encode("Janet"));
Assert.assertEquals("M626", this.getStringEncoder().encode("Margaret"));
Assert.assertEquals("S315", this.getStringEncoder().encode("Steven"));
Assert.assertEquals("M240", this.getStringEncoder().encode("Michael"));
Assert.assertEquals("R163", this.getStringEncoder().encode("Robert"));
Assert.assertEquals("L600", this.getStringEncoder().encode("Laura"));
Assert.assertEquals("A500", this.getStringEncoder().encode("Anne"));
}
/**
* https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56
*/
@Test
public void testNewInstance() {
Assert.assertEquals("W452", new Soundex().soundex("Williams"));
}
@Test
public void testNewInstance2() {
Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("Williams"));
}
@Test
public void testNewInstance3() {
Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING).soundex("Williams"));
}
@Test
public void testSoundexUtilsConstructable() {
new SoundexUtils();
}
@Test
public void testSoundexUtilsNullBehaviour() {
Assert.assertEquals(null, SoundexUtils.clean(null));
Assert.assertEquals("", SoundexUtils.clean(""));
Assert.assertEquals(0, SoundexUtils.differenceEncoded(null, ""));
Assert.assertEquals(0, SoundexUtils.differenceEncoded("", null));
}
/**
* https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56
*/
@Test
public void testUsEnglishStatic() {
Assert.assertEquals("W452", Soundex.US_ENGLISH.soundex("Williams"));
}
/**
* Fancy characters are not mapped by the default US mapping.
*
* http://issues.apache.org/bugzilla/show_bug.cgi?id=29080
*/
@Test
public void testUsMappingEWithAcute() {
Assert.assertEquals("E000", this.getStringEncoder().encode("e"));
if (Character.isLetter('\u00e9')) { // e-acute
try {
// uppercase E-acute
Assert.assertEquals("\u00c9000", this.getStringEncoder().encode("\u00e9"));
Assert.fail("Expected IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
// expected
}
} else {
Assert.assertEquals("", this.getStringEncoder().encode("\u00e9"));
}
}
/**
* Fancy characters are not mapped by the default US mapping.
*
* http://issues.apache.org/bugzilla/show_bug.cgi?id=29080
*/
@Test
public void testUsMappingOWithDiaeresis() {
Assert.assertEquals("O000", this.getStringEncoder().encode("o"));
if (Character.isLetter('\u00f6')) { // o-umlaut
try {
// uppercase O-umlaut
Assert.assertEquals("\u00d6000", this.getStringEncoder().encode("\u00f6"));
Assert.fail("Expected IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
// expected
}
} else {
Assert.assertEquals("", this.getStringEncoder().encode("\u00f6"));
}
}
/**
* Tests example from http://en.wikipedia.org/wiki/Soundex#American_Soundex as of 2015-03-22.
*/
@Test
public void testWikipediaAmericanSoundex() {
Assert.assertEquals("R163", this.getStringEncoder().encode("Robert"));
Assert.assertEquals("R163", this.getStringEncoder().encode("Rupert"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft"));
Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft"));
Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak"));
Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister"));
}
} |
|
public void testMapValueEquality() {
assertXPathValue(context, "map/b != map/a", Boolean.TRUE);
assertXPathValue(context, "map/a != map/b", Boolean.TRUE);
assertXPathValue(context, "map/a != map/c", Boolean.FALSE);
assertXPathValue(context, "map/a = map/b", Boolean.FALSE);
assertXPathValue(context, "map/a = map/c", Boolean.TRUE);
assertXPathValue(context, "not(map/a = map/b)", Boolean.TRUE);
assertXPathValue(context, "not(map/a = map/c)", Boolean.FALSE);
} | org.apache.commons.jxpath.ri.model.JXPath151Test::testMapValueEquality | src/test/org/apache/commons/jxpath/ri/model/JXPath151Test.java | 49 | src/test/org/apache/commons/jxpath/ri/model/JXPath151Test.java | testMapValueEquality | /*
* 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.model;
import java.util.HashMap;
import java.util.Locale;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.TestBean;
public class JXPath151Test extends JXPathTestCase {
private JXPathContext context;
public void setUp() {
TestBean testBean = new TestBean();
HashMap m = new HashMap();
m.put("a", Integer.valueOf(1));
m.put("b", null);
m.put("c", Integer.valueOf(1));
m.put("d", Integer.valueOf(0));
testBean.setMap(m);
context = JXPathContext.newContext(testBean);
context.setLocale(Locale.US);
}
public void testMapValueEquality() {
assertXPathValue(context, "map/b != map/a", Boolean.TRUE);
assertXPathValue(context, "map/a != map/b", Boolean.TRUE);
assertXPathValue(context, "map/a != map/c", Boolean.FALSE);
assertXPathValue(context, "map/a = map/b", Boolean.FALSE);
assertXPathValue(context, "map/a = map/c", Boolean.TRUE);
assertXPathValue(context, "not(map/a = map/b)", Boolean.TRUE);
assertXPathValue(context, "not(map/a = map/c)", Boolean.FALSE);
}
public void testMapValueEqualityUsingNameAttribute() {
assertXPathValue(context, "map[@name = 'b'] != map[@name = 'c']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'a'] != map[@name = 'b']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'a'] != map[@name = 'c']", Boolean.FALSE);
assertXPathValue(context, "map[@name = 'a'] = map[@name = 'b']", Boolean.FALSE);
assertXPathValue(context, "map[@name = 'a'] = map[@name = 'c']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'd'] = map[@name = 'b']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'd'] = map[@name = 'b']", Boolean.TRUE);
assertXPathValue(context, "not(map[@name = 'a'] = map[@name = 'b'])", Boolean.TRUE);
assertXPathValue(context, "not(map[@name = 'a'] = map[@name = 'c'])", Boolean.FALSE);
}
} | // You are a professional Java test case writer, please create a test case named `testMapValueEquality` for the issue `JxPath-JXPATH-151`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-151
//
// ## Issue-Title:
// null handling is inconsistent
//
// ## Issue-Description:
//
// Comparing a vaule to null using unequals (!=) yields false!
//
//
//
//
// ```
// Map<String, Integer> m = new HashMap<String, Integer>();
// m.put("a", 1);
// m.put("b", null);
// m.put("c", 1);
// JXPathContext c = JXPathContext.newContext(m);
// System.out.println(c.getValue("a != b") + " should be true");
// System.out.println(c.getValue("a != c") + " should be false");
// System.out.println(c.getValue("a = b") + " should be false");
// System.out.println(c.getValue("a = c") + " should be true");
// System.out.println(c.getValue("not(a = b)") + " should be true");
// System.out.println(c.getValue("not(a = c)") + " should be false");
//
// ```
//
//
// Output using 1.3:
//
// false should be true
//
// false should be false
//
// false should be false
//
// true should be true
//
// true should be true
//
// false should be false
//
//
// In 1.2 it works correctly!
//
//
//
//
//
public void testMapValueEquality() {
| 49 | 21 | 41 | src/test/org/apache/commons/jxpath/ri/model/JXPath151Test.java | src/test | ```markdown
## Issue-ID: JxPath-JXPATH-151
## Issue-Title:
null handling is inconsistent
## Issue-Description:
Comparing a vaule to null using unequals (!=) yields false!
```
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("a", 1);
m.put("b", null);
m.put("c", 1);
JXPathContext c = JXPathContext.newContext(m);
System.out.println(c.getValue("a != b") + " should be true");
System.out.println(c.getValue("a != c") + " should be false");
System.out.println(c.getValue("a = b") + " should be false");
System.out.println(c.getValue("a = c") + " should be true");
System.out.println(c.getValue("not(a = b)") + " should be true");
System.out.println(c.getValue("not(a = c)") + " should be false");
```
Output using 1.3:
false should be true
false should be false
false should be false
true should be true
true should be true
false should be false
In 1.2 it works correctly!
```
You are a professional Java test case writer, please create a test case named `testMapValueEquality` for the issue `JxPath-JXPATH-151`, utilizing the provided issue report information and the following function signature.
```java
public void testMapValueEquality() {
```
| 41 | [
"org.apache.commons.jxpath.ri.model.beans.PropertyPointer"
] | 6068a808bc8bf4a66653b9822cdc5c8d73fa455eedb7eea23c973535f04980d3 | public void testMapValueEquality() | // You are a professional Java test case writer, please create a test case named `testMapValueEquality` for the issue `JxPath-JXPATH-151`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JxPath-JXPATH-151
//
// ## Issue-Title:
// null handling is inconsistent
//
// ## Issue-Description:
//
// Comparing a vaule to null using unequals (!=) yields false!
//
//
//
//
// ```
// Map<String, Integer> m = new HashMap<String, Integer>();
// m.put("a", 1);
// m.put("b", null);
// m.put("c", 1);
// JXPathContext c = JXPathContext.newContext(m);
// System.out.println(c.getValue("a != b") + " should be true");
// System.out.println(c.getValue("a != c") + " should be false");
// System.out.println(c.getValue("a = b") + " should be false");
// System.out.println(c.getValue("a = c") + " should be true");
// System.out.println(c.getValue("not(a = b)") + " should be true");
// System.out.println(c.getValue("not(a = c)") + " should be false");
//
// ```
//
//
// Output using 1.3:
//
// false should be true
//
// false should be false
//
// false should be false
//
// true should be true
//
// true should be true
//
// false should be false
//
//
// In 1.2 it works correctly!
//
//
//
//
//
| 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.model;
import java.util.HashMap;
import java.util.Locale;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathTestCase;
import org.apache.commons.jxpath.TestBean;
public class JXPath151Test extends JXPathTestCase {
private JXPathContext context;
public void setUp() {
TestBean testBean = new TestBean();
HashMap m = new HashMap();
m.put("a", Integer.valueOf(1));
m.put("b", null);
m.put("c", Integer.valueOf(1));
m.put("d", Integer.valueOf(0));
testBean.setMap(m);
context = JXPathContext.newContext(testBean);
context.setLocale(Locale.US);
}
public void testMapValueEquality() {
assertXPathValue(context, "map/b != map/a", Boolean.TRUE);
assertXPathValue(context, "map/a != map/b", Boolean.TRUE);
assertXPathValue(context, "map/a != map/c", Boolean.FALSE);
assertXPathValue(context, "map/a = map/b", Boolean.FALSE);
assertXPathValue(context, "map/a = map/c", Boolean.TRUE);
assertXPathValue(context, "not(map/a = map/b)", Boolean.TRUE);
assertXPathValue(context, "not(map/a = map/c)", Boolean.FALSE);
}
public void testMapValueEqualityUsingNameAttribute() {
assertXPathValue(context, "map[@name = 'b'] != map[@name = 'c']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'a'] != map[@name = 'b']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'a'] != map[@name = 'c']", Boolean.FALSE);
assertXPathValue(context, "map[@name = 'a'] = map[@name = 'b']", Boolean.FALSE);
assertXPathValue(context, "map[@name = 'a'] = map[@name = 'c']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'd'] = map[@name = 'b']", Boolean.TRUE);
assertXPathValue(context, "map[@name = 'd'] = map[@name = 'b']", Boolean.TRUE);
assertXPathValue(context, "not(map[@name = 'a'] = map[@name = 'b'])", Boolean.TRUE);
assertXPathValue(context, "not(map[@name = 'a'] = map[@name = 'c'])", Boolean.FALSE);
}
} |
||
@Test
public void shouldKnowIfObjectsAreEqual() throws Exception {
int[] arr = new int[] {1, 2};
assertTrue(areEqual(arr, arr));
assertTrue(areEqual(new int[] {1, 2}, new int[] {1, 2}));
assertTrue(areEqual(new Double[] {1.0}, new Double[] {1.0}));
assertTrue(areEqual(new String[0], new String[0]));
assertTrue(areEqual(new Object[10], new Object[10]));
assertTrue(areEqual(new int[] {1}, new Integer[] {1}));
assertTrue(areEqual(new Object[] {"1"}, new String[] {"1"}));
Object badequals=new BadEquals();
assertTrue(areEqual(badequals,badequals));
assertFalse(areEqual(new Object[9], new Object[10]));
assertFalse(areEqual(new int[] {1, 2}, new int[] {1}));
assertFalse(areEqual(new int[] {1}, new double[] {1.0}));
} | org.mockito.internal.matchers.EqualityTest::shouldKnowIfObjectsAreEqual | test/org/mockito/internal/matchers/EqualityTest.java | 28 | test/org/mockito/internal/matchers/EqualityTest.java | shouldKnowIfObjectsAreEqual | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.matchers;
import org.mockitoutil.TestBase;
import org.junit.Test;
import static org.mockito.internal.matchers.Equality.areEqual;
public class EqualityTest extends TestBase {
@Test
public void shouldKnowIfObjectsAreEqual() throws Exception {
int[] arr = new int[] {1, 2};
assertTrue(areEqual(arr, arr));
assertTrue(areEqual(new int[] {1, 2}, new int[] {1, 2}));
assertTrue(areEqual(new Double[] {1.0}, new Double[] {1.0}));
assertTrue(areEqual(new String[0], new String[0]));
assertTrue(areEqual(new Object[10], new Object[10]));
assertTrue(areEqual(new int[] {1}, new Integer[] {1}));
assertTrue(areEqual(new Object[] {"1"}, new String[] {"1"}));
Object badequals=new BadEquals();
assertTrue(areEqual(badequals,badequals));
assertFalse(areEqual(new Object[9], new Object[10]));
assertFalse(areEqual(new int[] {1, 2}, new int[] {1}));
assertFalse(areEqual(new int[] {1}, new double[] {1.0}));
}
private final class BadEquals {
@Override
public boolean equals (Object oth) {
throw new RuntimeException();
}
}
} | // You are a professional Java test case writer, please create a test case named `shouldKnowIfObjectsAreEqual` for the issue `Mockito-484`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-484
//
// ## Issue-Title:
// Can not Return deep stubs from generic method that returns generic type
//
// ## Issue-Description:
// Hey,
//
//
// if I try to mock a generic method which a generic returntype, where the returntype is derived from the generic type of the method using deep stubs I get a `ClassCastException` when calling `when` on it.
//
//
//
// ```
// interface I {
// <T> Supplier<T> m(Class<T> type);
// }
// @Test
// public void test() throws Exception {
// I i = mock(I.class, RETURNS_DEEP_STUBS);
// when(i.m(Boolean.class).get()); // <- ClassCastException
// }
//
// ```
//
// When you don't use deep stubs and a raw `Supplier` mock to pass around it works:
//
//
//
// ```
// I i = mock(I.class);
// Supplier s = mock(Supplier.class);
// when(i.m(Boolean.class)).thenReturn(s);
// when(i.m(Boolean.class).get());
//
// ```
//
// The `ClassCastException`:
//
//
//
// ```
// java.lang.ClassCastException: org.mockito.internal.creation.cglib.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$cdb13154 cannot be cast to java.lang.String
// at MockitoGenerics.test(MockitoGenerics.java:21)
// at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
// at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
// at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
// at java.lang.reflect.Method.invoke(Method.java:483)
// at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
// at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
// at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
// at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
// at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
// at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
// at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
// at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
// at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
// at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
// at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
// at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
// at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
// at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
// at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
//
// ```
//
// Tested
@Test
public void shouldKnowIfObjectsAreEqual() throws Exception {
| 28 | 22 | 12 | test/org/mockito/internal/matchers/EqualityTest.java | test | ```markdown
## Issue-ID: Mockito-484
## Issue-Title:
Can not Return deep stubs from generic method that returns generic type
## Issue-Description:
Hey,
if I try to mock a generic method which a generic returntype, where the returntype is derived from the generic type of the method using deep stubs I get a `ClassCastException` when calling `when` on it.
```
interface I {
<T> Supplier<T> m(Class<T> type);
}
@Test
public void test() throws Exception {
I i = mock(I.class, RETURNS_DEEP_STUBS);
when(i.m(Boolean.class).get()); // <- ClassCastException
}
```
When you don't use deep stubs and a raw `Supplier` mock to pass around it works:
```
I i = mock(I.class);
Supplier s = mock(Supplier.class);
when(i.m(Boolean.class)).thenReturn(s);
when(i.m(Boolean.class).get());
```
The `ClassCastException`:
```
java.lang.ClassCastException: org.mockito.internal.creation.cglib.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$cdb13154 cannot be cast to java.lang.String
at MockitoGenerics.test(MockitoGenerics.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
```
Tested
```
You are a professional Java test case writer, please create a test case named `shouldKnowIfObjectsAreEqual` for the issue `Mockito-484`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void shouldKnowIfObjectsAreEqual() throws Exception {
```
| 12 | [
"org.mockito.internal.matchers.Equality"
] | 6135dddb4e2ee780c9e8f243d64cedf2df573fc95a961e8e78f02e3202413b44 | @Test
public void shouldKnowIfObjectsAreEqual() throws Exception | // You are a professional Java test case writer, please create a test case named `shouldKnowIfObjectsAreEqual` for the issue `Mockito-484`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-484
//
// ## Issue-Title:
// Can not Return deep stubs from generic method that returns generic type
//
// ## Issue-Description:
// Hey,
//
//
// if I try to mock a generic method which a generic returntype, where the returntype is derived from the generic type of the method using deep stubs I get a `ClassCastException` when calling `when` on it.
//
//
//
// ```
// interface I {
// <T> Supplier<T> m(Class<T> type);
// }
// @Test
// public void test() throws Exception {
// I i = mock(I.class, RETURNS_DEEP_STUBS);
// when(i.m(Boolean.class).get()); // <- ClassCastException
// }
//
// ```
//
// When you don't use deep stubs and a raw `Supplier` mock to pass around it works:
//
//
//
// ```
// I i = mock(I.class);
// Supplier s = mock(Supplier.class);
// when(i.m(Boolean.class)).thenReturn(s);
// when(i.m(Boolean.class).get());
//
// ```
//
// The `ClassCastException`:
//
//
//
// ```
// java.lang.ClassCastException: org.mockito.internal.creation.cglib.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$cdb13154 cannot be cast to java.lang.String
// at MockitoGenerics.test(MockitoGenerics.java:21)
// at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
// at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
// at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
// at java.lang.reflect.Method.invoke(Method.java:483)
// at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
// at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
// at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
// at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
// at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
// at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
// at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
// at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
// at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
// at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
// at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
// at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
// at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
// at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
// at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
// at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
//
// ```
//
// Tested
| Mockito | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.matchers;
import org.mockitoutil.TestBase;
import org.junit.Test;
import static org.mockito.internal.matchers.Equality.areEqual;
public class EqualityTest extends TestBase {
@Test
public void shouldKnowIfObjectsAreEqual() throws Exception {
int[] arr = new int[] {1, 2};
assertTrue(areEqual(arr, arr));
assertTrue(areEqual(new int[] {1, 2}, new int[] {1, 2}));
assertTrue(areEqual(new Double[] {1.0}, new Double[] {1.0}));
assertTrue(areEqual(new String[0], new String[0]));
assertTrue(areEqual(new Object[10], new Object[10]));
assertTrue(areEqual(new int[] {1}, new Integer[] {1}));
assertTrue(areEqual(new Object[] {"1"}, new String[] {"1"}));
Object badequals=new BadEquals();
assertTrue(areEqual(badequals,badequals));
assertFalse(areEqual(new Object[9], new Object[10]));
assertFalse(areEqual(new int[] {1, 2}, new int[] {1}));
assertFalse(areEqual(new int[] {1}, new double[] {1.0}));
}
private final class BadEquals {
@Override
public boolean equals (Object oth) {
throw new RuntimeException();
}
}
} |
||
@Test
public void pure_mockito_should_not_depend_JUnit() throws Exception {
ClassLoader classLoader_without_JUnit = ClassLoaders.excludingClassLoader()
.withCodeSourceUrlOf(
Mockito.class,
Matcher.class,
Enhancer.class,
Objenesis.class
)
.without("junit", "org.junit")
.build();
Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit").listOwnedClasses();
for (String pureMockitoAPIClass : pureMockitoAPIClasses) {
checkDependency(classLoader_without_JUnit, pureMockitoAPIClass);
}
} | org.mockitointegration.NoJUnitDependenciesTest::pure_mockito_should_not_depend_JUnit | test/org/mockitointegration/NoJUnitDependenciesTest.java | 29 | test/org/mockitointegration/NoJUnitDependenciesTest.java | pure_mockito_should_not_depend_JUnit | package org.mockitointegration;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.cglib.proxy.Enhancer;
import org.mockitoutil.ClassLoaders;
import org.objenesis.Objenesis;
import java.util.Set;
public class NoJUnitDependenciesTest {
@Test
public void pure_mockito_should_not_depend_JUnit() throws Exception {
ClassLoader classLoader_without_JUnit = ClassLoaders.excludingClassLoader()
.withCodeSourceUrlOf(
Mockito.class,
Matcher.class,
Enhancer.class,
Objenesis.class
)
.without("junit", "org.junit")
.build();
Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit").listOwnedClasses();
for (String pureMockitoAPIClass : pureMockitoAPIClasses) {
checkDependency(classLoader_without_JUnit, pureMockitoAPIClass);
}
}
private void checkDependency(ClassLoader classLoader_without_JUnit, String pureMockitoAPIClass) throws ClassNotFoundException {
try {
Class.forName(pureMockitoAPIClass, true, classLoader_without_JUnit);
} catch (Throwable e) {
throw new AssertionError(String.format("'%s' has some dependency to JUnit", pureMockitoAPIClass), e);
}
}
} | // You are a professional Java test case writer, please create a test case named `pure_mockito_should_not_depend_JUnit` for the issue `Mockito-152`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-152
//
// ## Issue-Title:
// Mockito 1.10.x timeout verification needs JUnit classes (VerifyError, NoClassDefFoundError)
//
// ## Issue-Description:
// If JUnit is not on the classpath and mockito is version 1.10.x (as of now 1.10.1 up to 1.10.19) and the code is using the timeout verification which is not supposed to be related to JUnit, then the JVM may fail with a `VerifyError` or a `NoClassDefFoundError`.
//
//
// This issue has been reported on the [mailing list](https://groups.google.com/forum/#!topic/mockito/A6D7myKiD5k) and on [StackOverflow](http://stackoverflow.com/questions/27721621/java-lang-verifyerror-with-mockito-1-10-17)
//
//
// A simple test like that with **TestNG** (and no JUnit in the class path of course) exposes the issue:
//
//
//
// ```
// import org.testng.annotations.Test;
// import java.util.Observable;
// import static org.mockito.Mockito.*;
//
// public class VerifyErrorOnVerificationWithTimeoutTest {
// @Test public void should_not_throw_VerifyError() {
// verify(mock(Observable.class), timeout(500)).countObservers();
// }
// }
//
// ```
//
// With TestNG 5.13.1, the stack trace is :
//
//
//
// ```
// java.lang.VerifyError: (class: org/mockito/internal/verification/VerificationOverTimeImpl, method: verify signature: (Lorg/mockito/internal/verification/api/VerificationData;)V) Incompatible argument to function
// at org.mockito.verification.Timeout.<init>(Timeout.java:32)
// at org.mockito.verification.Timeout.<init>(Timeout.java:25)
// at org.mockito.Mockito.timeout(Mockito.java:2103)
// at com.example.UserServiceImplTest.test(UserServiceImplTest.java:26)
//
// ```
//
// TestNG includes a dependency on JUnit 3.8.1, which has the `junit.framework.ComparisonFailure`, but the JVM cannot perform the linking at runtime (`VerifyError` extends `LinkageError`), probably because for the JVM there's some incompatible changes in this class between version 3.x and 4.x.
//
// Note that Mockito is compiled against JUnit 4.x. This also reveal that Mockito is not anymore compatible with JUnit 3.x.
//
//
// With TestNG 6.8.13, the stack trace is :
//
//
//
// ```
// java.lang.NoClassDefFoundError: junit/framework/ComparisonFailure
// at java.lang.ClassLoader.defineClass1(Native Method)
// at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
// at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
// at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
// at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
// at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
// at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
// at java.security.AccessController.doPrivileged(Native Method)
// at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
// at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
// at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
// at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
// at org.mockito.verification.Timeout.<init>(Timeout.java:32)
// at org.mockito.verification.Timeout.<init>(Timeout.java:25)
// at org.mockito
@Test
public void pure_mockito_should_not_depend_JUnit() throws Exception {
| 29 | 5 | 12 | test/org/mockitointegration/NoJUnitDependenciesTest.java | test | ```markdown
## Issue-ID: Mockito-152
## Issue-Title:
Mockito 1.10.x timeout verification needs JUnit classes (VerifyError, NoClassDefFoundError)
## Issue-Description:
If JUnit is not on the classpath and mockito is version 1.10.x (as of now 1.10.1 up to 1.10.19) and the code is using the timeout verification which is not supposed to be related to JUnit, then the JVM may fail with a `VerifyError` or a `NoClassDefFoundError`.
This issue has been reported on the [mailing list](https://groups.google.com/forum/#!topic/mockito/A6D7myKiD5k) and on [StackOverflow](http://stackoverflow.com/questions/27721621/java-lang-verifyerror-with-mockito-1-10-17)
A simple test like that with **TestNG** (and no JUnit in the class path of course) exposes the issue:
```
import org.testng.annotations.Test;
import java.util.Observable;
import static org.mockito.Mockito.*;
public class VerifyErrorOnVerificationWithTimeoutTest {
@Test public void should_not_throw_VerifyError() {
verify(mock(Observable.class), timeout(500)).countObservers();
}
}
```
With TestNG 5.13.1, the stack trace is :
```
java.lang.VerifyError: (class: org/mockito/internal/verification/VerificationOverTimeImpl, method: verify signature: (Lorg/mockito/internal/verification/api/VerificationData;)V) Incompatible argument to function
at org.mockito.verification.Timeout.<init>(Timeout.java:32)
at org.mockito.verification.Timeout.<init>(Timeout.java:25)
at org.mockito.Mockito.timeout(Mockito.java:2103)
at com.example.UserServiceImplTest.test(UserServiceImplTest.java:26)
```
TestNG includes a dependency on JUnit 3.8.1, which has the `junit.framework.ComparisonFailure`, but the JVM cannot perform the linking at runtime (`VerifyError` extends `LinkageError`), probably because for the JVM there's some incompatible changes in this class between version 3.x and 4.x.
Note that Mockito is compiled against JUnit 4.x. This also reveal that Mockito is not anymore compatible with JUnit 3.x.
With TestNG 6.8.13, the stack trace is :
```
java.lang.NoClassDefFoundError: junit/framework/ComparisonFailure
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at org.mockito.verification.Timeout.<init>(Timeout.java:32)
at org.mockito.verification.Timeout.<init>(Timeout.java:25)
at org.mockito
```
You are a professional Java test case writer, please create a test case named `pure_mockito_should_not_depend_JUnit` for the issue `Mockito-152`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void pure_mockito_should_not_depend_JUnit() throws Exception {
```
| 12 | [
"org.mockito.internal.verification.VerificationOverTimeImpl"
] | 615026ee187d94a702d0a18aab7053b758a71ec4cfde6ec016ddc02c3a1e42eb | @Test
public void pure_mockito_should_not_depend_JUnit() throws Exception | // You are a professional Java test case writer, please create a test case named `pure_mockito_should_not_depend_JUnit` for the issue `Mockito-152`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-152
//
// ## Issue-Title:
// Mockito 1.10.x timeout verification needs JUnit classes (VerifyError, NoClassDefFoundError)
//
// ## Issue-Description:
// If JUnit is not on the classpath and mockito is version 1.10.x (as of now 1.10.1 up to 1.10.19) and the code is using the timeout verification which is not supposed to be related to JUnit, then the JVM may fail with a `VerifyError` or a `NoClassDefFoundError`.
//
//
// This issue has been reported on the [mailing list](https://groups.google.com/forum/#!topic/mockito/A6D7myKiD5k) and on [StackOverflow](http://stackoverflow.com/questions/27721621/java-lang-verifyerror-with-mockito-1-10-17)
//
//
// A simple test like that with **TestNG** (and no JUnit in the class path of course) exposes the issue:
//
//
//
// ```
// import org.testng.annotations.Test;
// import java.util.Observable;
// import static org.mockito.Mockito.*;
//
// public class VerifyErrorOnVerificationWithTimeoutTest {
// @Test public void should_not_throw_VerifyError() {
// verify(mock(Observable.class), timeout(500)).countObservers();
// }
// }
//
// ```
//
// With TestNG 5.13.1, the stack trace is :
//
//
//
// ```
// java.lang.VerifyError: (class: org/mockito/internal/verification/VerificationOverTimeImpl, method: verify signature: (Lorg/mockito/internal/verification/api/VerificationData;)V) Incompatible argument to function
// at org.mockito.verification.Timeout.<init>(Timeout.java:32)
// at org.mockito.verification.Timeout.<init>(Timeout.java:25)
// at org.mockito.Mockito.timeout(Mockito.java:2103)
// at com.example.UserServiceImplTest.test(UserServiceImplTest.java:26)
//
// ```
//
// TestNG includes a dependency on JUnit 3.8.1, which has the `junit.framework.ComparisonFailure`, but the JVM cannot perform the linking at runtime (`VerifyError` extends `LinkageError`), probably because for the JVM there's some incompatible changes in this class between version 3.x and 4.x.
//
// Note that Mockito is compiled against JUnit 4.x. This also reveal that Mockito is not anymore compatible with JUnit 3.x.
//
//
// With TestNG 6.8.13, the stack trace is :
//
//
//
// ```
// java.lang.NoClassDefFoundError: junit/framework/ComparisonFailure
// at java.lang.ClassLoader.defineClass1(Native Method)
// at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
// at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
// at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
// at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
// at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
// at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
// at java.security.AccessController.doPrivileged(Native Method)
// at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
// at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
// at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
// at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
// at org.mockito.verification.Timeout.<init>(Timeout.java:32)
// at org.mockito.verification.Timeout.<init>(Timeout.java:25)
// at org.mockito
| Mockito | package org.mockitointegration;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.cglib.proxy.Enhancer;
import org.mockitoutil.ClassLoaders;
import org.objenesis.Objenesis;
import java.util.Set;
public class NoJUnitDependenciesTest {
@Test
public void pure_mockito_should_not_depend_JUnit() throws Exception {
ClassLoader classLoader_without_JUnit = ClassLoaders.excludingClassLoader()
.withCodeSourceUrlOf(
Mockito.class,
Matcher.class,
Enhancer.class,
Objenesis.class
)
.without("junit", "org.junit")
.build();
Set<String> pureMockitoAPIClasses = ClassLoaders.in(classLoader_without_JUnit).omit("runners", "junit", "JUnit").listOwnedClasses();
for (String pureMockitoAPIClass : pureMockitoAPIClasses) {
checkDependency(classLoader_without_JUnit, pureMockitoAPIClass);
}
}
private void checkDependency(ClassLoader classLoader_without_JUnit, String pureMockitoAPIClass) throws ClassNotFoundException {
try {
Class.forName(pureMockitoAPIClass, true, classLoader_without_JUnit);
} catch (Throwable e) {
throw new AssertionError(String.format("'%s' has some dependency to JUnit", pureMockitoAPIClass), e);
}
}
} |
||
public void testSafeMultiplyLongInt() {
assertEquals(0L, FieldUtils.safeMultiply(0L, 0));
assertEquals(1L, FieldUtils.safeMultiply(1L, 1));
assertEquals(3L, FieldUtils.safeMultiply(1L, 3));
assertEquals(3L, FieldUtils.safeMultiply(3L, 1));
assertEquals(6L, FieldUtils.safeMultiply(2L, 3));
assertEquals(-6L, FieldUtils.safeMultiply(2L, -3));
assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3));
assertEquals(6L, FieldUtils.safeMultiply(-2L, -3));
assertEquals(-1L * Integer.MIN_VALUE, FieldUtils.safeMultiply(-1L, Integer.MIN_VALUE));
assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1));
assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1));
assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1));
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MAX_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
} | org.joda.time.field.TestFieldUtils::testSafeMultiplyLongInt | src/test/java/org/joda/time/field/TestFieldUtils.java | 281 | src/test/java/org/joda/time/field/TestFieldUtils.java | testSafeMultiplyLongInt | /*
* Copyright 2001-2005 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.field;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*
*
* @author Brian S O'Neill
*/
public class TestFieldUtils extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestFieldUtils.class);
}
public TestFieldUtils(String name) {
super(name);
}
public void testSafeAddInt() {
assertEquals(0, FieldUtils.safeAdd(0, 0));
assertEquals(5, FieldUtils.safeAdd(2, 3));
assertEquals(-1, FieldUtils.safeAdd(2, -3));
assertEquals(1, FieldUtils.safeAdd(-2, 3));
assertEquals(-5, FieldUtils.safeAdd(-2, -3));
assertEquals(Integer.MAX_VALUE - 1, FieldUtils.safeAdd(Integer.MAX_VALUE, -1));
assertEquals(Integer.MIN_VALUE + 1, FieldUtils.safeAdd(Integer.MIN_VALUE, 1));
assertEquals(-1, FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MAX_VALUE));
assertEquals(-1, FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MIN_VALUE));
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, 1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, -100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
public void testSafeAddLong() {
assertEquals(0L, FieldUtils.safeAdd(0L, 0L));
assertEquals(5L, FieldUtils.safeAdd(2L, 3L));
assertEquals(-1L, FieldUtils.safeAdd(2L, -3L));
assertEquals(1L, FieldUtils.safeAdd(-2L, 3L));
assertEquals(-5L, FieldUtils.safeAdd(-2L, -3L));
assertEquals(Long.MAX_VALUE - 1, FieldUtils.safeAdd(Long.MAX_VALUE, -1L));
assertEquals(Long.MIN_VALUE + 1, FieldUtils.safeAdd(Long.MIN_VALUE, 1L));
assertEquals(-1, FieldUtils.safeAdd(Long.MIN_VALUE, Long.MAX_VALUE));
assertEquals(-1, FieldUtils.safeAdd(Long.MAX_VALUE, Long.MIN_VALUE));
try {
FieldUtils.safeAdd(Long.MAX_VALUE, 1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MAX_VALUE, 100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MAX_VALUE, Long.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MIN_VALUE, -1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MIN_VALUE, -100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MIN_VALUE, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
public void testSafeSubtractLong() {
assertEquals(0L, FieldUtils.safeSubtract(0L, 0L));
assertEquals(-1L, FieldUtils.safeSubtract(2L, 3L));
assertEquals(5L, FieldUtils.safeSubtract(2L, -3L));
assertEquals(-5L, FieldUtils.safeSubtract(-2L, 3L));
assertEquals(1L, FieldUtils.safeSubtract(-2L, -3L));
assertEquals(Long.MAX_VALUE - 1, FieldUtils.safeSubtract(Long.MAX_VALUE, 1L));
assertEquals(Long.MIN_VALUE + 1, FieldUtils.safeSubtract(Long.MIN_VALUE, -1L));
assertEquals(0, FieldUtils.safeSubtract(Long.MIN_VALUE, Long.MIN_VALUE));
assertEquals(0, FieldUtils.safeSubtract(Long.MAX_VALUE, Long.MAX_VALUE));
try {
FieldUtils.safeSubtract(Long.MIN_VALUE, 1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MIN_VALUE, 100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MIN_VALUE, Long.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MAX_VALUE, -1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MAX_VALUE, -100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MAX_VALUE, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
//-----------------------------------------------------------------------
public void testSafeMultiplyLongLong() {
assertEquals(0L, FieldUtils.safeMultiply(0L, 0L));
assertEquals(1L, FieldUtils.safeMultiply(1L, 1L));
assertEquals(3L, FieldUtils.safeMultiply(1L, 3L));
assertEquals(3L, FieldUtils.safeMultiply(3L, 1L));
assertEquals(6L, FieldUtils.safeMultiply(2L, 3L));
assertEquals(-6L, FieldUtils.safeMultiply(2L, -3L));
assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3L));
assertEquals(6L, FieldUtils.safeMultiply(-2L, -3L));
assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1L));
assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1L));
assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1L));
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, -1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(-1L, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, 100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, Long.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MAX_VALUE, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
//-----------------------------------------------------------------------
public void testSafeMultiplyLongInt() {
assertEquals(0L, FieldUtils.safeMultiply(0L, 0));
assertEquals(1L, FieldUtils.safeMultiply(1L, 1));
assertEquals(3L, FieldUtils.safeMultiply(1L, 3));
assertEquals(3L, FieldUtils.safeMultiply(3L, 1));
assertEquals(6L, FieldUtils.safeMultiply(2L, 3));
assertEquals(-6L, FieldUtils.safeMultiply(2L, -3));
assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3));
assertEquals(6L, FieldUtils.safeMultiply(-2L, -3));
assertEquals(-1L * Integer.MIN_VALUE, FieldUtils.safeMultiply(-1L, Integer.MIN_VALUE));
assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1));
assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1));
assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1));
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MAX_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
}
| // You are a professional Java test case writer, please create a test case named `testSafeMultiplyLongInt` for the issue `Time-147`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-147
//
// ## Issue-Title:
// #147 possibly a bug in org.joda.time.field.FieldUtils.safeMultipl
//
//
//
//
//
// ## Issue-Description:
// It seems to me that as currently written in joda-time-2.1.jar
//
// org.joda.time.field.FieldUtils.safeMultiply(long val1, int scalar)
//
// doesn't detect the overflow if the long val1 == Long.MIN\_VALUE and the int scalar == -1.
//
//
// The attached file demonstrates what I think is the bug and suggests a patch.
//
//
// I looked at the Joda Time bugs list in SourceForge but couldn't see anything that looked relevant: my apologies if I've missed something, or if I'm making a mistake with this bug report.
//
//
// Colin Bartlett
//
//
//
//
public void testSafeMultiplyLongInt() {
| 281 | //----------------------------------------------------------------------- | 15 | 240 | src/test/java/org/joda/time/field/TestFieldUtils.java | src/test/java | ```markdown
## Issue-ID: Time-147
## Issue-Title:
#147 possibly a bug in org.joda.time.field.FieldUtils.safeMultipl
## Issue-Description:
It seems to me that as currently written in joda-time-2.1.jar
org.joda.time.field.FieldUtils.safeMultiply(long val1, int scalar)
doesn't detect the overflow if the long val1 == Long.MIN\_VALUE and the int scalar == -1.
The attached file demonstrates what I think is the bug and suggests a patch.
I looked at the Joda Time bugs list in SourceForge but couldn't see anything that looked relevant: my apologies if I've missed something, or if I'm making a mistake with this bug report.
Colin Bartlett
```
You are a professional Java test case writer, please create a test case named `testSafeMultiplyLongInt` for the issue `Time-147`, utilizing the provided issue report information and the following function signature.
```java
public void testSafeMultiplyLongInt() {
```
| 240 | [
"org.joda.time.field.FieldUtils"
] | 619e3bc29683e00428e4160723540b7b5f8e62e400dc70cbdae516511a689a71 | public void testSafeMultiplyLongInt() | // You are a professional Java test case writer, please create a test case named `testSafeMultiplyLongInt` for the issue `Time-147`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-147
//
// ## Issue-Title:
// #147 possibly a bug in org.joda.time.field.FieldUtils.safeMultipl
//
//
//
//
//
// ## Issue-Description:
// It seems to me that as currently written in joda-time-2.1.jar
//
// org.joda.time.field.FieldUtils.safeMultiply(long val1, int scalar)
//
// doesn't detect the overflow if the long val1 == Long.MIN\_VALUE and the int scalar == -1.
//
//
// The attached file demonstrates what I think is the bug and suggests a patch.
//
//
// I looked at the Joda Time bugs list in SourceForge but couldn't see anything that looked relevant: my apologies if I've missed something, or if I'm making a mistake with this bug report.
//
//
// Colin Bartlett
//
//
//
//
| Time | /*
* Copyright 2001-2005 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.field;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*
*
* @author Brian S O'Neill
*/
public class TestFieldUtils extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestFieldUtils.class);
}
public TestFieldUtils(String name) {
super(name);
}
public void testSafeAddInt() {
assertEquals(0, FieldUtils.safeAdd(0, 0));
assertEquals(5, FieldUtils.safeAdd(2, 3));
assertEquals(-1, FieldUtils.safeAdd(2, -3));
assertEquals(1, FieldUtils.safeAdd(-2, 3));
assertEquals(-5, FieldUtils.safeAdd(-2, -3));
assertEquals(Integer.MAX_VALUE - 1, FieldUtils.safeAdd(Integer.MAX_VALUE, -1));
assertEquals(Integer.MIN_VALUE + 1, FieldUtils.safeAdd(Integer.MIN_VALUE, 1));
assertEquals(-1, FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MAX_VALUE));
assertEquals(-1, FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MIN_VALUE));
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, 1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, -100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
public void testSafeAddLong() {
assertEquals(0L, FieldUtils.safeAdd(0L, 0L));
assertEquals(5L, FieldUtils.safeAdd(2L, 3L));
assertEquals(-1L, FieldUtils.safeAdd(2L, -3L));
assertEquals(1L, FieldUtils.safeAdd(-2L, 3L));
assertEquals(-5L, FieldUtils.safeAdd(-2L, -3L));
assertEquals(Long.MAX_VALUE - 1, FieldUtils.safeAdd(Long.MAX_VALUE, -1L));
assertEquals(Long.MIN_VALUE + 1, FieldUtils.safeAdd(Long.MIN_VALUE, 1L));
assertEquals(-1, FieldUtils.safeAdd(Long.MIN_VALUE, Long.MAX_VALUE));
assertEquals(-1, FieldUtils.safeAdd(Long.MAX_VALUE, Long.MIN_VALUE));
try {
FieldUtils.safeAdd(Long.MAX_VALUE, 1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MAX_VALUE, 100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MAX_VALUE, Long.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MIN_VALUE, -1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MIN_VALUE, -100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Long.MIN_VALUE, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
public void testSafeSubtractLong() {
assertEquals(0L, FieldUtils.safeSubtract(0L, 0L));
assertEquals(-1L, FieldUtils.safeSubtract(2L, 3L));
assertEquals(5L, FieldUtils.safeSubtract(2L, -3L));
assertEquals(-5L, FieldUtils.safeSubtract(-2L, 3L));
assertEquals(1L, FieldUtils.safeSubtract(-2L, -3L));
assertEquals(Long.MAX_VALUE - 1, FieldUtils.safeSubtract(Long.MAX_VALUE, 1L));
assertEquals(Long.MIN_VALUE + 1, FieldUtils.safeSubtract(Long.MIN_VALUE, -1L));
assertEquals(0, FieldUtils.safeSubtract(Long.MIN_VALUE, Long.MIN_VALUE));
assertEquals(0, FieldUtils.safeSubtract(Long.MAX_VALUE, Long.MAX_VALUE));
try {
FieldUtils.safeSubtract(Long.MIN_VALUE, 1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MIN_VALUE, 100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MIN_VALUE, Long.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MAX_VALUE, -1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MAX_VALUE, -100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeSubtract(Long.MAX_VALUE, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
//-----------------------------------------------------------------------
public void testSafeMultiplyLongLong() {
assertEquals(0L, FieldUtils.safeMultiply(0L, 0L));
assertEquals(1L, FieldUtils.safeMultiply(1L, 1L));
assertEquals(3L, FieldUtils.safeMultiply(1L, 3L));
assertEquals(3L, FieldUtils.safeMultiply(3L, 1L));
assertEquals(6L, FieldUtils.safeMultiply(2L, 3L));
assertEquals(-6L, FieldUtils.safeMultiply(2L, -3L));
assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3L));
assertEquals(6L, FieldUtils.safeMultiply(-2L, -3L));
assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1L));
assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1L));
assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1L));
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, -1L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(-1L, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, 100L);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, Long.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MAX_VALUE, Long.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
//-----------------------------------------------------------------------
public void testSafeMultiplyLongInt() {
assertEquals(0L, FieldUtils.safeMultiply(0L, 0));
assertEquals(1L, FieldUtils.safeMultiply(1L, 1));
assertEquals(3L, FieldUtils.safeMultiply(1L, 3));
assertEquals(3L, FieldUtils.safeMultiply(3L, 1));
assertEquals(6L, FieldUtils.safeMultiply(2L, 3));
assertEquals(-6L, FieldUtils.safeMultiply(2L, -3));
assertEquals(-6L, FieldUtils.safeMultiply(-2L, 3));
assertEquals(6L, FieldUtils.safeMultiply(-2L, -3));
assertEquals(-1L * Integer.MIN_VALUE, FieldUtils.safeMultiply(-1L, Integer.MIN_VALUE));
assertEquals(Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, 1));
assertEquals(Long.MIN_VALUE, FieldUtils.safeMultiply(Long.MIN_VALUE, 1));
assertEquals(-Long.MAX_VALUE, FieldUtils.safeMultiply(Long.MAX_VALUE, -1));
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MIN_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeMultiply(Long.MAX_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
}
|
|
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);
} | org.joda.time.format.TestDateTimeFormatter::testParseInto_monthOnly_baseStartYear | src/test/java/org/joda/time/format/TestDateTimeFormatter.java | 877 | src/test/java/org/joda/time/format/TestDateTimeFormatter.java | testParseInto_monthOnly_baseStartYear | /*
* 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_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 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_monthOnly_baseStartYear` for the issue `Time-148`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-148
//
// ## Issue-Title:
// #148 DateTimeFormatter.parseInto broken when no year in format
//
//
//
//
//
// ## Issue-Description:
// In Joda Time 2.0, the default year was set to 2000 so that Feb 29 could be parsed correctly. However, parseInto now overwrites the given instant's year with 2000 (or whatever iDefaultYear is set to). The correct behavior would seem to be to use the given instant's year instead of iDefaultYear.
//
// This does mean that Feb 29 might not be parseable if the instant's year is not a leap year, but in this case the caller asked for that in a sense.
//
//
//
//
public void testParseInto_monthOnly_baseStartYear() {
| 877 | 16 | 872 | src/test/java/org/joda/time/format/TestDateTimeFormatter.java | src/test/java | ```markdown
## Issue-ID: Time-148
## Issue-Title:
#148 DateTimeFormatter.parseInto broken when no year in format
## Issue-Description:
In Joda Time 2.0, the default year was set to 2000 so that Feb 29 could be parsed correctly. However, parseInto now overwrites the given instant's year with 2000 (or whatever iDefaultYear is set to). The correct behavior would seem to be to use the given instant's year instead of iDefaultYear.
This does mean that Feb 29 might not be parseable if the instant's year is not a leap year, but in this case the caller asked for that in a sense.
```
You are a professional Java test case writer, please create a test case named `testParseInto_monthOnly_baseStartYear` for the issue `Time-148`, utilizing the provided issue report information and the following function signature.
```java
public void testParseInto_monthOnly_baseStartYear() {
```
| 872 | [
"org.joda.time.format.DateTimeFormatter"
] | 62ae19f27460693c8211fb2e37d570a47d4d16d4cd043edab190ec0b8338ff42 | public void testParseInto_monthOnly_baseStartYear() | // You are a professional Java test case writer, please create a test case named `testParseInto_monthOnly_baseStartYear` for the issue `Time-148`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-148
//
// ## Issue-Title:
// #148 DateTimeFormatter.parseInto broken when no year in format
//
//
//
//
//
// ## Issue-Description:
// In Joda Time 2.0, the default year was set to 2000 so that Feb 29 could be parsed correctly. However, parseInto now overwrites the given instant's year with 2000 (or whatever iDefaultYear is set to). The correct behavior would seem to be to use the given instant's year instead of iDefaultYear.
//
// This does mean that Feb 29 might not be parseable if the instant's year is not a leap year, but in this case the caller asked for that in a sense.
//
//
//
//
| 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_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 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));
// }
} |
||
@Test
public void testCOMPRESS178() throws Exception {
final File input = getFile("COMPRESS-178.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
try {
in.getNextEntry();
fail("Expected IOException");
} catch (IOException e) {
Throwable t = e.getCause();
assertTrue("Expected cause = IllegalArgumentException", t instanceof IllegalArgumentException);
}
in.close();
} | org.apache.commons.compress.archivers.TarTestCase::testCOMPRESS178 | src/test/java/org/apache/commons/compress/archivers/TarTestCase.java | 330 | src/test/java/org/apache/commons/compress/archivers/TarTestCase.java | testCOMPRESS178 | /*
* 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 static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.AbstractTestCase;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.CharsetNames;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
public final class TarTestCase extends AbstractTestCase {
@Test
public void testTarArchiveCreation() throws Exception {
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml");
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
}
@Test
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes(CharsetNames.UTF_8);
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(file1);
IOUtils.copy(in, os);
os.closeArchiveEntry();
os.close();
out.close();
in.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os2.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
os2.closeArchiveEntry();
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.close();
}
}
}
@Test
public void testTarUnarchive() throws Exception {
final File input = getFile("bla.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
final TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
final OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
IOUtils.copy(in, out);
in.close();
out.close();
}
@Test
public void testCOMPRESS114() throws Exception {
final File input = getFile("COMPRESS-114.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new TarArchiveInputStream(is,
CharsetNames.ISO_8859_1);
TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
assertEquals("3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA", entry.getName());
entry = (TarArchiveEntry)in.getNextEntry();
assertEquals("0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA",entry.getName());
in.close();
}
@Test
public void testDirectoryEntryFromFile() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
long beforeArchiveWrite = tmp[0].lastModified();
TarArchiveEntry in = new TarArchiveEntry(tmp[0], "foo");
tos.putArchiveEntry(in);
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
// TAR stores time with a granularity of 1 second
assertEquals(beforeArchiveWrite / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertTrue(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitDirectoryEntry() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
long beforeArchiveWrite = tmp[0].lastModified();
TarArchiveEntry in = new TarArchiveEntry("foo/");
in.setModTime(beforeArchiveWrite);
tos.putArchiveEntry(in);
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
assertEquals(beforeArchiveWrite / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertTrue(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testFileEntryFromFile() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
TarArchiveEntry in = new TarArchiveEntry(tmp[1], "foo");
tos.putArchiveEntry(in);
byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
tos.write(b);
}
fis.close();
fis = null;
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertFalse(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitFileEntry() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
TarArchiveEntry in = new TarArchiveEntry("foo");
in.setModTime(tmp[1].lastModified());
in.setSize(tmp[1].length());
tos.putArchiveEntry(in);
byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
tos.write(b);
}
fis.close();
fis = null;
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertFalse(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testCOMPRESS178() throws Exception {
final File input = getFile("COMPRESS-178.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
try {
in.getNextEntry();
fail("Expected IOException");
} catch (IOException e) {
Throwable t = e.getCause();
assertTrue("Expected cause = IllegalArgumentException", t instanceof IllegalArgumentException);
}
in.close();
}
} | // You are a professional Java test case writer, please create a test case named `testCOMPRESS178` for the issue `Compress-COMPRESS-301`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-301
//
// ## Issue-Title:
// Illegal argument exception when extracting .tgz file
//
// ## Issue-Description:
//
// When attempting to unpack a .tgz file, I am receiving the illegal argument exception: java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '05412
//
//
// {NUL}11' len=8. This is causing a java.io.IOException: Error detected parsing the header error.
//
//
//
// This is being thrown when the function TarArchiveInputStream.getNextTarEntry() is called.
//
//
//
// Here is the code I am using.
//
//
//
// ```
// TarArchiveInputStream tarIn = new TarArchiveInputStream(
// new GZIPInputStream(
// new BufferedInputStream(
// new FileInputStream(
// tempDirPath + fileName))));
//
// TarArchiveEntry entry = tarIn.getNextTarEntry();
//
// while (entry != null) {
// File path = new File(tempDirPath, entry.getName());
// if (entry.isDirectory()) {
// path.mkdirs();
// } else {
// path.createNewFile();
// byte[] read = new byte[2048];
// BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(path));
// int len;
// while ((len = tarIn.read(read)) != -1) {
// bout.write(read, 0, len);
// System.out.print(new String(read, "UTF-8"));
// }
// bout.close();
// read = null;
// }
// entry = tarIn.getNextTarEntry();
// }
// tarIn.close();
//
// ```
//
//
//
//
//
// Here is the full stack trace:
//
//
//
// [2015-02-12T23:17:31.944+0000] [glassfish 4.0] [SEVERE] [] [] [tid: \_ThreadID=123 \_ThreadName=Thread-4] [timeMillis: 1423783051944] [levelValue: 1000] [[
//
// java.io.IOException: Error detected parsing the header
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:257)
@Test
public void testCOMPRESS178() throws Exception {
| 330 | 31 | 317 | src/test/java/org/apache/commons/compress/archivers/TarTestCase.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-301
## Issue-Title:
Illegal argument exception when extracting .tgz file
## Issue-Description:
When attempting to unpack a .tgz file, I am receiving the illegal argument exception: java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '05412
{NUL}11' len=8. This is causing a java.io.IOException: Error detected parsing the header error.
This is being thrown when the function TarArchiveInputStream.getNextTarEntry() is called.
Here is the code I am using.
```
TarArchiveInputStream tarIn = new TarArchiveInputStream(
new GZIPInputStream(
new BufferedInputStream(
new FileInputStream(
tempDirPath + fileName))));
TarArchiveEntry entry = tarIn.getNextTarEntry();
while (entry != null) {
File path = new File(tempDirPath, entry.getName());
if (entry.isDirectory()) {
path.mkdirs();
} else {
path.createNewFile();
byte[] read = new byte[2048];
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(path));
int len;
while ((len = tarIn.read(read)) != -1) {
bout.write(read, 0, len);
System.out.print(new String(read, "UTF-8"));
}
bout.close();
read = null;
}
entry = tarIn.getNextTarEntry();
}
tarIn.close();
```
Here is the full stack trace:
[2015-02-12T23:17:31.944+0000] [glassfish 4.0] [SEVERE] [] [] [tid: \_ThreadID=123 \_ThreadName=Thread-4] [timeMillis: 1423783051944] [levelValue: 1000] [[
java.io.IOException: Error detected parsing the header
at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:257)
```
You are a professional Java test case writer, please create a test case named `testCOMPRESS178` for the issue `Compress-COMPRESS-301`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testCOMPRESS178() throws Exception {
```
| 317 | [
"org.apache.commons.compress.archivers.tar.TarUtils"
] | 62eb4ad67cf40c260b841eff10c544998bd0f372acc47c4544ee709d8c2fc9f7 | @Test
public void testCOMPRESS178() throws Exception | // You are a professional Java test case writer, please create a test case named `testCOMPRESS178` for the issue `Compress-COMPRESS-301`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-301
//
// ## Issue-Title:
// Illegal argument exception when extracting .tgz file
//
// ## Issue-Description:
//
// When attempting to unpack a .tgz file, I am receiving the illegal argument exception: java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '05412
//
//
// {NUL}11' len=8. This is causing a java.io.IOException: Error detected parsing the header error.
//
//
//
// This is being thrown when the function TarArchiveInputStream.getNextTarEntry() is called.
//
//
//
// Here is the code I am using.
//
//
//
// ```
// TarArchiveInputStream tarIn = new TarArchiveInputStream(
// new GZIPInputStream(
// new BufferedInputStream(
// new FileInputStream(
// tempDirPath + fileName))));
//
// TarArchiveEntry entry = tarIn.getNextTarEntry();
//
// while (entry != null) {
// File path = new File(tempDirPath, entry.getName());
// if (entry.isDirectory()) {
// path.mkdirs();
// } else {
// path.createNewFile();
// byte[] read = new byte[2048];
// BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(path));
// int len;
// while ((len = tarIn.read(read)) != -1) {
// bout.write(read, 0, len);
// System.out.print(new String(read, "UTF-8"));
// }
// bout.close();
// read = null;
// }
// entry = tarIn.getNextTarEntry();
// }
// tarIn.close();
//
// ```
//
//
//
//
//
// Here is the full stack trace:
//
//
//
// [2015-02-12T23:17:31.944+0000] [glassfish 4.0] [SEVERE] [] [] [tid: \_ThreadID=123 \_ThreadName=Thread-4] [timeMillis: 1423783051944] [levelValue: 1000] [[
//
// java.io.IOException: Error detected parsing the header
//
// at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:257)
| 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 static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.AbstractTestCase;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.CharsetNames;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
public final class TarTestCase extends AbstractTestCase {
@Test
public void testTarArchiveCreation() throws Exception {
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml");
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
}
@Test
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes(CharsetNames.UTF_8);
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(file1);
IOUtils.copy(in, os);
os.closeArchiveEntry();
os.close();
out.close();
in.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os2.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
os2.closeArchiveEntry();
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.close();
}
}
}
@Test
public void testTarUnarchive() throws Exception {
final File input = getFile("bla.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
final TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
final OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
IOUtils.copy(in, out);
in.close();
out.close();
}
@Test
public void testCOMPRESS114() throws Exception {
final File input = getFile("COMPRESS-114.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new TarArchiveInputStream(is,
CharsetNames.ISO_8859_1);
TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
assertEquals("3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA", entry.getName());
entry = (TarArchiveEntry)in.getNextEntry();
assertEquals("0302-0601-3\u00b1\u00b1\u00b1F06\u00b1W2345\u00b1ZB\u00b1la\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1\u00b1BLA",entry.getName());
in.close();
}
@Test
public void testDirectoryEntryFromFile() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
long beforeArchiveWrite = tmp[0].lastModified();
TarArchiveEntry in = new TarArchiveEntry(tmp[0], "foo");
tos.putArchiveEntry(in);
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
// TAR stores time with a granularity of 1 second
assertEquals(beforeArchiveWrite / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertTrue(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitDirectoryEntry() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
long beforeArchiveWrite = tmp[0].lastModified();
TarArchiveEntry in = new TarArchiveEntry("foo/");
in.setModTime(beforeArchiveWrite);
tos.putArchiveEntry(in);
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
assertEquals(beforeArchiveWrite / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertTrue(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testFileEntryFromFile() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
TarArchiveEntry in = new TarArchiveEntry(tmp[1], "foo");
tos.putArchiveEntry(in);
byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
tos.write(b);
}
fis.close();
fis = null;
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertFalse(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitFileEntry() throws Exception {
File[] tmp = createTempDirAndFile();
File archive = null;
TarArchiveOutputStream tos = null;
TarArchiveInputStream tis = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".tar", tmp[0]);
archive.deleteOnExit();
tos = new TarArchiveOutputStream(new FileOutputStream(archive));
TarArchiveEntry in = new TarArchiveEntry("foo");
in.setModTime(tmp[1].lastModified());
in.setSize(tmp[1].length());
tos.putArchiveEntry(in);
byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
tos.write(b);
}
fis.close();
fis = null;
tos.closeArchiveEntry();
tos.close();
tos = null;
tis = new TarArchiveInputStream(new FileInputStream(archive));
TarArchiveEntry out = tis.getNextTarEntry();
tis.close();
tis = null;
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 1000,
out.getLastModifiedDate().getTime() / 1000);
assertFalse(out.isDirectory());
} finally {
if (tis != null) {
tis.close();
}
if (tos != null) {
tos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testCOMPRESS178() throws Exception {
final File input = getFile("COMPRESS-178.tar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", is);
try {
in.getNextEntry();
fail("Expected IOException");
} catch (IOException e) {
Throwable t = e.getCause();
assertTrue("Expected cause = IllegalArgumentException", t instanceof IllegalArgumentException);
}
in.close();
}
} |
||
@Test
public void testListAllFilesWithNestedArchive() throws Exception {
final File input = getFile("OSX_ArchiveWithNestedArchive.zip");
final List<String> results = new ArrayList<>();
final List<ZipException> expectedExceptions = new ArrayList<>();
final InputStream is = new FileInputStream(input);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
results.add(entry.getName());
final ArchiveInputStream nestedIn = new ArchiveStreamFactory().createArchiveInputStream("zip", in);
try {
ZipArchiveEntry nestedEntry = null;
while ((nestedEntry = (ZipArchiveEntry) nestedIn.getNextEntry()) != null) {
results.add(nestedEntry.getName());
}
} catch (ZipException ex) {
// expected since you cannot create a final ArchiveInputStream from test3.xml
expectedExceptions.add(ex);
}
// nested stream must not be closed here
}
} finally {
if (in != null) {
in.close();
}
}
is.close();
assertTrue(results.contains("NestedArchiv.zip"));
assertTrue(results.contains("test1.xml"));
assertTrue(results.contains("test2.xml"));
assertTrue(results.contains("test3.xml"));
assertEquals(1, expectedExceptions.size());
} | org.apache.commons.compress.archivers.ZipTestCase::testListAllFilesWithNestedArchive | src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java | 281 | src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java | testListAllFilesWithNestedArchive | /*
* 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 static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import org.apache.commons.compress.AbstractTestCase;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.archivers.zip.ZipMethod;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
import org.junit.Assert;
import org.junit.Test;
public final class ZipTestCase extends AbstractTestCase {
/**
* Archives 2 files and unarchives it again. If the file length of result
* and source is the same, it looks like the operations have worked
* @throws Exception
*/
@Test
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
}
}
out.close();
// Unarchive the same
final List<File> results = new ArrayList<>();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
final File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
try (OutputStream o = new FileOutputStream(outfile)) {
IOUtils.copy(in, o);
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
}
}
is.close();
assertEquals(results.size(), 2);
File result = results.get(0);
assertEquals(file1.length(), result.length());
result = results.get(1);
assertEquals(file2.length(), result.length());
}
/**
* Archives 2 files and unarchives it again. If the file contents of result
* and source is the same, it looks like the operations have worked
* @throws Exception
*/
@Test
public void testZipArchiveCreationInMemory() throws Exception {
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final byte[] file1Contents = new byte[(int) file1.length()];
final byte[] file2Contents = new byte[(int) file2.length()];
IOUtils.readFully(new FileInputStream(file1), file1Contents);
IOUtils.readFully(new FileInputStream(file2), file2Contents);
SeekableInMemoryByteChannel c = new SeekableInMemoryByteChannel();
try (ZipArchiveOutputStream os = new ZipArchiveOutputStream(c)) {
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
os.write(file1Contents);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
os.write(file2Contents);
os.closeArchiveEntry();
}
// Unarchive the same
final List<byte[]> results = new ArrayList<>();
try (ArchiveInputStream in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", new ByteArrayInputStream(c.array()))) {
ZipArchiveEntry entry;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
byte[] result = new byte[(int) entry.getSize()];
IOUtils.readFully(in, result);
results.add(result);
}
}
assertArrayEquals(results.get(0), file1Contents);
assertArrayEquals(results.get(1), file2Contents);
}
/**
* Simple unarchive test. Asserts nothing.
* @throws Exception
*/
@Test
public void testZipUnarchive() throws Exception {
final File input = getFile("bla.zip");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
final ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();
final OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
IOUtils.copy(in, out);
out.close();
in.close();
}
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-208"
* >COMPRESS-208</a>.
*/
@Test
public void testSkipsPK00Prefix() throws Exception {
final File input = getFile("COMPRESS-208.zip");
final ArrayList<String> al = new ArrayList<>();
al.add("test1.xml");
al.add("test2.xml");
try (InputStream is = new FileInputStream(input)) {
checkArchiveContent(new ZipArchiveInputStream(is), al);
}
}
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-93"
* >COMPRESS-93</a>.
*/
@Test
public void testSupportedCompressionMethod() throws IOException {
/*
ZipFile bla = new ZipFile(getFile("bla.zip"));
assertTrue(bla.canReadEntryData(bla.getEntry("test1.xml")));
bla.close();
*/
final ZipFile moby = new ZipFile(getFile("moby.zip"));
final ZipArchiveEntry entry = moby.getEntry("README");
assertEquals("method", ZipMethod.TOKENIZATION.getCode(), entry.getMethod());
assertFalse(moby.canReadEntryData(entry));
moby.close();
}
/**
* Test case for being able to skip an entry in an
* {@link ZipArchiveInputStream} even if the compression method of that
* entry is unsupported.
*
* @see <a href="https://issues.apache.org/jira/browse/COMPRESS-93"
* >COMPRESS-93</a>
*/
@Test
public void testSkipEntryWithUnsupportedCompressionMethod()
throws IOException {
try (ZipArchiveInputStream zip = new ZipArchiveInputStream(new FileInputStream(getFile("moby.zip")))) {
final ZipArchiveEntry entry = zip.getNextZipEntry();
assertEquals("method", ZipMethod.TOKENIZATION.getCode(), entry.getMethod());
assertEquals("README", entry.getName());
assertFalse(zip.canReadEntryData(entry));
try {
assertNull(zip.getNextZipEntry());
} catch (final IOException e) {
e.printStackTrace();
fail("COMPRESS-93: Unable to skip an unsupported zip entry");
}
}
}
/**
* Checks if all entries from a nested archive can be read.
* The archive: OSX_ArchiveWithNestedArchive.zip contains:
* NestedArchiv.zip and test.xml3.
*
* The nested archive: NestedArchive.zip contains test1.xml and test2.xml
*
* @throws Exception
*/
@Test
public void testListAllFilesWithNestedArchive() throws Exception {
final File input = getFile("OSX_ArchiveWithNestedArchive.zip");
final List<String> results = new ArrayList<>();
final List<ZipException> expectedExceptions = new ArrayList<>();
final InputStream is = new FileInputStream(input);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
results.add(entry.getName());
final ArchiveInputStream nestedIn = new ArchiveStreamFactory().createArchiveInputStream("zip", in);
try {
ZipArchiveEntry nestedEntry = null;
while ((nestedEntry = (ZipArchiveEntry) nestedIn.getNextEntry()) != null) {
results.add(nestedEntry.getName());
}
} catch (ZipException ex) {
// expected since you cannot create a final ArchiveInputStream from test3.xml
expectedExceptions.add(ex);
}
// nested stream must not be closed here
}
} finally {
if (in != null) {
in.close();
}
}
is.close();
assertTrue(results.contains("NestedArchiv.zip"));
assertTrue(results.contains("test1.xml"));
assertTrue(results.contains("test2.xml"));
assertTrue(results.contains("test3.xml"));
assertEquals(1, expectedExceptions.size());
}
@Test
public void testDirectoryEntryFromFile() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final long beforeArchiveWrite = tmp[0].lastModified();
final ZipArchiveEntry in = new ZipArchiveEntry(tmp[0], "foo");
zos.putArchiveEntry(in);
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo/");
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
// ZIP stores time with a granularity of 2 seconds
assertEquals(beforeArchiveWrite / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertTrue(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitDirectoryEntry() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final long beforeArchiveWrite = tmp[0].lastModified();
final ZipArchiveEntry in = new ZipArchiveEntry("foo/");
in.setTime(beforeArchiveWrite);
zos.putArchiveEntry(in);
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo/");
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
assertEquals(beforeArchiveWrite / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertTrue(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
String first_payload = "ABBA";
String second_payload = "AAAAAAAAAAAA";
ZipArchiveEntryPredicate allFilesPredicate = new ZipArchiveEntryPredicate() {
@Override
public boolean test(final ZipArchiveEntry zipArchiveEntry) {
return true;
}
};
@Test
public void testCopyRawEntriesFromFile()
throws IOException {
final File[] tmp = createTempDirAndFile();
final File reference = createReferenceFile(tmp[0], Zip64Mode.Never, "expected.");
final File a1 = File.createTempFile("src1.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(a1);
zos.setUseZip64(Zip64Mode.Never);
createFirstEntry(zos).close();
final File a2 = File.createTempFile("src2.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos1 = new ZipArchiveOutputStream(a2);
zos1.setUseZip64(Zip64Mode.Never);
createSecondEntry(zos1).close();
final ZipFile zf1 = new ZipFile(a1);
final ZipFile zf2 = new ZipFile(a2);
final File fileResult = File.createTempFile("file-actual.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos2 = new ZipArchiveOutputStream(fileResult);
zf1.copyRawEntries(zos2, allFilesPredicate);
zf2.copyRawEntries(zos2, allFilesPredicate);
zos2.close();
// copyRawEntries does not add superfluous zip64 header like regular zip output stream
// does when using Zip64Mode.AsNeeded so all the source material has to be Zip64Mode.Never,
// if exact binary equality is to be achieved
assertSameFileContents(reference, fileResult);
zf1.close();
zf2.close();
}
@Test
public void testCopyRawZip64EntryFromFile()
throws IOException {
final File[] tmp = createTempDirAndFile();
final File reference = File.createTempFile("z64reference.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos1 = new ZipArchiveOutputStream(reference);
zos1.setUseZip64(Zip64Mode.Always);
createFirstEntry(zos1);
zos1.close();
final File a1 = File.createTempFile("zip64src.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(a1);
zos.setUseZip64(Zip64Mode.Always);
createFirstEntry(zos).close();
final ZipFile zf1 = new ZipFile(a1);
final File fileResult = File.createTempFile("file-actual.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos2 = new ZipArchiveOutputStream(fileResult);
zos2.setUseZip64(Zip64Mode.Always);
zf1.copyRawEntries(zos2, allFilesPredicate);
zos2.close();
assertSameFileContents(reference, fileResult);
zf1.close();
}
@Test
public void testUnixModeInAddRaw() throws IOException {
final File[] tmp = createTempDirAndFile();
final File a1 = File.createTempFile("unixModeBits.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(a1);
final ZipArchiveEntry archiveEntry = new ZipArchiveEntry("fred");
archiveEntry.setUnixMode(0664);
archiveEntry.setMethod(ZipEntry.DEFLATED);
zos.addRawArchiveEntry(archiveEntry, new ByteArrayInputStream("fud".getBytes()));
zos.close();
final ZipFile zf1 = new ZipFile(a1);
final ZipArchiveEntry fred = zf1.getEntry("fred");
assertEquals(0664, fred.getUnixMode());
zf1.close();
}
private File createReferenceFile(final File directory, final Zip64Mode zipMode, final String prefix) throws IOException {
final File reference = File.createTempFile(prefix, ".zip", directory);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(reference);
zos.setUseZip64(zipMode);
createFirstEntry(zos);
createSecondEntry(zos);
zos.close();
return reference;
}
private ZipArchiveOutputStream createFirstEntry(final ZipArchiveOutputStream zos) throws IOException {
createArchiveEntry(first_payload, zos, "file1.txt");
return zos;
}
private ZipArchiveOutputStream createSecondEntry(final ZipArchiveOutputStream zos) throws IOException {
createArchiveEntry(second_payload, zos, "file2.txt");
return zos;
}
private void assertSameFileContents(final File expectedFile, final File actualFile) throws IOException {
final int size = (int) Math.max(expectedFile.length(), actualFile.length());
final ZipFile expected = new ZipFile(expectedFile);
final ZipFile actual = new ZipFile(actualFile);
final byte[] expectedBuf = new byte[size];
final byte[] actualBuf = new byte[size];
final Enumeration<ZipArchiveEntry> actualInOrder = actual.getEntriesInPhysicalOrder();
final Enumeration<ZipArchiveEntry> expectedInOrder = expected.getEntriesInPhysicalOrder();
while (actualInOrder.hasMoreElements()){
final ZipArchiveEntry actualElement = actualInOrder.nextElement();
final ZipArchiveEntry expectedElement = expectedInOrder.nextElement();
assertEquals( expectedElement.getName(), actualElement.getName());
// Don't compare timestamps since they may vary;
// there's no support for stubbed out clock (TimeSource) in ZipArchiveOutputStream
assertEquals( expectedElement.getMethod(), actualElement.getMethod());
assertEquals( expectedElement.getGeneralPurposeBit(), actualElement.getGeneralPurposeBit());
assertEquals( expectedElement.getCrc(), actualElement.getCrc());
assertEquals( expectedElement.getCompressedSize(), actualElement.getCompressedSize());
assertEquals( expectedElement.getSize(), actualElement.getSize());
assertEquals( expectedElement.getExternalAttributes(), actualElement.getExternalAttributes());
assertEquals( expectedElement.getInternalAttributes(), actualElement.getInternalAttributes());
final InputStream actualIs = actual.getInputStream(actualElement);
final InputStream expectedIs = expected.getInputStream(expectedElement);
IOUtils.readFully(expectedIs, expectedBuf);
IOUtils.readFully(actualIs, actualBuf);
expectedIs.close();
actualIs.close();
Assert.assertArrayEquals(expectedBuf, actualBuf); // Buffers are larger than payload. dont care
}
expected.close();
actual.close();
}
private void createArchiveEntry(final String payload, final ZipArchiveOutputStream zos, final String name)
throws IOException {
final ZipArchiveEntry in = new ZipArchiveEntry(name);
zos.putArchiveEntry(in);
zos.write(payload.getBytes());
zos.closeArchiveEntry();
}
@Test
public void testFileEntryFromFile() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final ZipArchiveEntry in = new ZipArchiveEntry(tmp[1], "foo");
zos.putArchiveEntry(in);
final byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
zos.write(b);
}
fis.close();
fis = null;
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo");
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertFalse(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitFileEntry() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final ZipArchiveEntry in = new ZipArchiveEntry("foo");
in.setTime(tmp[1].lastModified());
in.setSize(tmp[1].length());
zos.putArchiveEntry(in);
final byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
zos.write(b);
}
fis.close();
fis = null;
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo");
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertFalse(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
} | // You are a professional Java test case writer, please create a test case named `testListAllFilesWithNestedArchive` for the issue `Compress-COMPRESS-367`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-367
//
// ## Issue-Title:
// ZipArchiveInputStream.getNextZipEntry() should differentiate between "invalid entry encountered" and "no more entries"
//
// ## Issue-Description:
//
// ZipArchiveInputStream.getNextZipEntry() currently returns null if an invalid entry is encountered. Thus, it's not possible to differentiate between "no more entries" and "invalid entry encountered" conditions.
//
//
// Instead, it should throw an exception if an invalid entry is encountered.
//
//
// I've created a test case and fix. I will submit a pull request shortly.
//
//
//
//
//
@Test
public void testListAllFilesWithNestedArchive() throws Exception {
| 281 | /**
* Checks if all entries from a nested archive can be read.
* The archive: OSX_ArchiveWithNestedArchive.zip contains:
* NestedArchiv.zip and test.xml3.
*
* The nested archive: NestedArchive.zip contains test1.xml and test2.xml
*
* @throws Exception
*/ | 41 | 241 | src/test/java/org/apache/commons/compress/archivers/ZipTestCase.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-367
## Issue-Title:
ZipArchiveInputStream.getNextZipEntry() should differentiate between "invalid entry encountered" and "no more entries"
## Issue-Description:
ZipArchiveInputStream.getNextZipEntry() currently returns null if an invalid entry is encountered. Thus, it's not possible to differentiate between "no more entries" and "invalid entry encountered" conditions.
Instead, it should throw an exception if an invalid entry is encountered.
I've created a test case and fix. I will submit a pull request shortly.
```
You are a professional Java test case writer, please create a test case named `testListAllFilesWithNestedArchive` for the issue `Compress-COMPRESS-367`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testListAllFilesWithNestedArchive() throws Exception {
```
| 241 | [
"org.apache.commons.compress.archivers.zip.ZipArchiveInputStream"
] | 63320fce95c80deea144efc3aed252d5dc944fc7026c049d2b9a2dd14d75a0c9 | @Test
public void testListAllFilesWithNestedArchive() throws Exception | // You are a professional Java test case writer, please create a test case named `testListAllFilesWithNestedArchive` for the issue `Compress-COMPRESS-367`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-367
//
// ## Issue-Title:
// ZipArchiveInputStream.getNextZipEntry() should differentiate between "invalid entry encountered" and "no more entries"
//
// ## Issue-Description:
//
// ZipArchiveInputStream.getNextZipEntry() currently returns null if an invalid entry is encountered. Thus, it's not possible to differentiate between "no more entries" and "invalid entry encountered" conditions.
//
//
// Instead, it should throw an exception if an invalid entry is encountered.
//
//
// I've created a test case and fix. I will submit a pull request shortly.
//
//
//
//
//
| 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 static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import org.apache.commons.compress.AbstractTestCase;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.archivers.zip.ZipMethod;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
import org.junit.Assert;
import org.junit.Test;
public final class ZipTestCase extends AbstractTestCase {
/**
* Archives 2 files and unarchives it again. If the file length of result
* and source is the same, it looks like the operations have worked
* @throws Exception
*/
@Test
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
}
}
out.close();
// Unarchive the same
final List<File> results = new ArrayList<>();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
final File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
try (OutputStream o = new FileOutputStream(outfile)) {
IOUtils.copy(in, o);
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
}
}
is.close();
assertEquals(results.size(), 2);
File result = results.get(0);
assertEquals(file1.length(), result.length());
result = results.get(1);
assertEquals(file2.length(), result.length());
}
/**
* Archives 2 files and unarchives it again. If the file contents of result
* and source is the same, it looks like the operations have worked
* @throws Exception
*/
@Test
public void testZipArchiveCreationInMemory() throws Exception {
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final byte[] file1Contents = new byte[(int) file1.length()];
final byte[] file2Contents = new byte[(int) file2.length()];
IOUtils.readFully(new FileInputStream(file1), file1Contents);
IOUtils.readFully(new FileInputStream(file2), file2Contents);
SeekableInMemoryByteChannel c = new SeekableInMemoryByteChannel();
try (ZipArchiveOutputStream os = new ZipArchiveOutputStream(c)) {
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
os.write(file1Contents);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
os.write(file2Contents);
os.closeArchiveEntry();
}
// Unarchive the same
final List<byte[]> results = new ArrayList<>();
try (ArchiveInputStream in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", new ByteArrayInputStream(c.array()))) {
ZipArchiveEntry entry;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
byte[] result = new byte[(int) entry.getSize()];
IOUtils.readFully(in, result);
results.add(result);
}
}
assertArrayEquals(results.get(0), file1Contents);
assertArrayEquals(results.get(1), file2Contents);
}
/**
* Simple unarchive test. Asserts nothing.
* @throws Exception
*/
@Test
public void testZipUnarchive() throws Exception {
final File input = getFile("bla.zip");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
final ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();
final OutputStream out = new FileOutputStream(new File(dir, entry.getName()));
IOUtils.copy(in, out);
out.close();
in.close();
}
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-208"
* >COMPRESS-208</a>.
*/
@Test
public void testSkipsPK00Prefix() throws Exception {
final File input = getFile("COMPRESS-208.zip");
final ArrayList<String> al = new ArrayList<>();
al.add("test1.xml");
al.add("test2.xml");
try (InputStream is = new FileInputStream(input)) {
checkArchiveContent(new ZipArchiveInputStream(is), al);
}
}
/**
* Test case for
* <a href="https://issues.apache.org/jira/browse/COMPRESS-93"
* >COMPRESS-93</a>.
*/
@Test
public void testSupportedCompressionMethod() throws IOException {
/*
ZipFile bla = new ZipFile(getFile("bla.zip"));
assertTrue(bla.canReadEntryData(bla.getEntry("test1.xml")));
bla.close();
*/
final ZipFile moby = new ZipFile(getFile("moby.zip"));
final ZipArchiveEntry entry = moby.getEntry("README");
assertEquals("method", ZipMethod.TOKENIZATION.getCode(), entry.getMethod());
assertFalse(moby.canReadEntryData(entry));
moby.close();
}
/**
* Test case for being able to skip an entry in an
* {@link ZipArchiveInputStream} even if the compression method of that
* entry is unsupported.
*
* @see <a href="https://issues.apache.org/jira/browse/COMPRESS-93"
* >COMPRESS-93</a>
*/
@Test
public void testSkipEntryWithUnsupportedCompressionMethod()
throws IOException {
try (ZipArchiveInputStream zip = new ZipArchiveInputStream(new FileInputStream(getFile("moby.zip")))) {
final ZipArchiveEntry entry = zip.getNextZipEntry();
assertEquals("method", ZipMethod.TOKENIZATION.getCode(), entry.getMethod());
assertEquals("README", entry.getName());
assertFalse(zip.canReadEntryData(entry));
try {
assertNull(zip.getNextZipEntry());
} catch (final IOException e) {
e.printStackTrace();
fail("COMPRESS-93: Unable to skip an unsupported zip entry");
}
}
}
/**
* Checks if all entries from a nested archive can be read.
* The archive: OSX_ArchiveWithNestedArchive.zip contains:
* NestedArchiv.zip and test.xml3.
*
* The nested archive: NestedArchive.zip contains test1.xml and test2.xml
*
* @throws Exception
*/
@Test
public void testListAllFilesWithNestedArchive() throws Exception {
final File input = getFile("OSX_ArchiveWithNestedArchive.zip");
final List<String> results = new ArrayList<>();
final List<ZipException> expectedExceptions = new ArrayList<>();
final InputStream is = new FileInputStream(input);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
results.add(entry.getName());
final ArchiveInputStream nestedIn = new ArchiveStreamFactory().createArchiveInputStream("zip", in);
try {
ZipArchiveEntry nestedEntry = null;
while ((nestedEntry = (ZipArchiveEntry) nestedIn.getNextEntry()) != null) {
results.add(nestedEntry.getName());
}
} catch (ZipException ex) {
// expected since you cannot create a final ArchiveInputStream from test3.xml
expectedExceptions.add(ex);
}
// nested stream must not be closed here
}
} finally {
if (in != null) {
in.close();
}
}
is.close();
assertTrue(results.contains("NestedArchiv.zip"));
assertTrue(results.contains("test1.xml"));
assertTrue(results.contains("test2.xml"));
assertTrue(results.contains("test3.xml"));
assertEquals(1, expectedExceptions.size());
}
@Test
public void testDirectoryEntryFromFile() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final long beforeArchiveWrite = tmp[0].lastModified();
final ZipArchiveEntry in = new ZipArchiveEntry(tmp[0], "foo");
zos.putArchiveEntry(in);
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo/");
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
// ZIP stores time with a granularity of 2 seconds
assertEquals(beforeArchiveWrite / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertTrue(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitDirectoryEntry() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final long beforeArchiveWrite = tmp[0].lastModified();
final ZipArchiveEntry in = new ZipArchiveEntry("foo/");
in.setTime(beforeArchiveWrite);
zos.putArchiveEntry(in);
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo/");
assertNotNull(out);
assertEquals("foo/", out.getName());
assertEquals(0, out.getSize());
assertEquals(beforeArchiveWrite / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertTrue(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
String first_payload = "ABBA";
String second_payload = "AAAAAAAAAAAA";
ZipArchiveEntryPredicate allFilesPredicate = new ZipArchiveEntryPredicate() {
@Override
public boolean test(final ZipArchiveEntry zipArchiveEntry) {
return true;
}
};
@Test
public void testCopyRawEntriesFromFile()
throws IOException {
final File[] tmp = createTempDirAndFile();
final File reference = createReferenceFile(tmp[0], Zip64Mode.Never, "expected.");
final File a1 = File.createTempFile("src1.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(a1);
zos.setUseZip64(Zip64Mode.Never);
createFirstEntry(zos).close();
final File a2 = File.createTempFile("src2.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos1 = new ZipArchiveOutputStream(a2);
zos1.setUseZip64(Zip64Mode.Never);
createSecondEntry(zos1).close();
final ZipFile zf1 = new ZipFile(a1);
final ZipFile zf2 = new ZipFile(a2);
final File fileResult = File.createTempFile("file-actual.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos2 = new ZipArchiveOutputStream(fileResult);
zf1.copyRawEntries(zos2, allFilesPredicate);
zf2.copyRawEntries(zos2, allFilesPredicate);
zos2.close();
// copyRawEntries does not add superfluous zip64 header like regular zip output stream
// does when using Zip64Mode.AsNeeded so all the source material has to be Zip64Mode.Never,
// if exact binary equality is to be achieved
assertSameFileContents(reference, fileResult);
zf1.close();
zf2.close();
}
@Test
public void testCopyRawZip64EntryFromFile()
throws IOException {
final File[] tmp = createTempDirAndFile();
final File reference = File.createTempFile("z64reference.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos1 = new ZipArchiveOutputStream(reference);
zos1.setUseZip64(Zip64Mode.Always);
createFirstEntry(zos1);
zos1.close();
final File a1 = File.createTempFile("zip64src.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(a1);
zos.setUseZip64(Zip64Mode.Always);
createFirstEntry(zos).close();
final ZipFile zf1 = new ZipFile(a1);
final File fileResult = File.createTempFile("file-actual.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos2 = new ZipArchiveOutputStream(fileResult);
zos2.setUseZip64(Zip64Mode.Always);
zf1.copyRawEntries(zos2, allFilesPredicate);
zos2.close();
assertSameFileContents(reference, fileResult);
zf1.close();
}
@Test
public void testUnixModeInAddRaw() throws IOException {
final File[] tmp = createTempDirAndFile();
final File a1 = File.createTempFile("unixModeBits.", ".zip", tmp[0]);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(a1);
final ZipArchiveEntry archiveEntry = new ZipArchiveEntry("fred");
archiveEntry.setUnixMode(0664);
archiveEntry.setMethod(ZipEntry.DEFLATED);
zos.addRawArchiveEntry(archiveEntry, new ByteArrayInputStream("fud".getBytes()));
zos.close();
final ZipFile zf1 = new ZipFile(a1);
final ZipArchiveEntry fred = zf1.getEntry("fred");
assertEquals(0664, fred.getUnixMode());
zf1.close();
}
private File createReferenceFile(final File directory, final Zip64Mode zipMode, final String prefix) throws IOException {
final File reference = File.createTempFile(prefix, ".zip", directory);
final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(reference);
zos.setUseZip64(zipMode);
createFirstEntry(zos);
createSecondEntry(zos);
zos.close();
return reference;
}
private ZipArchiveOutputStream createFirstEntry(final ZipArchiveOutputStream zos) throws IOException {
createArchiveEntry(first_payload, zos, "file1.txt");
return zos;
}
private ZipArchiveOutputStream createSecondEntry(final ZipArchiveOutputStream zos) throws IOException {
createArchiveEntry(second_payload, zos, "file2.txt");
return zos;
}
private void assertSameFileContents(final File expectedFile, final File actualFile) throws IOException {
final int size = (int) Math.max(expectedFile.length(), actualFile.length());
final ZipFile expected = new ZipFile(expectedFile);
final ZipFile actual = new ZipFile(actualFile);
final byte[] expectedBuf = new byte[size];
final byte[] actualBuf = new byte[size];
final Enumeration<ZipArchiveEntry> actualInOrder = actual.getEntriesInPhysicalOrder();
final Enumeration<ZipArchiveEntry> expectedInOrder = expected.getEntriesInPhysicalOrder();
while (actualInOrder.hasMoreElements()){
final ZipArchiveEntry actualElement = actualInOrder.nextElement();
final ZipArchiveEntry expectedElement = expectedInOrder.nextElement();
assertEquals( expectedElement.getName(), actualElement.getName());
// Don't compare timestamps since they may vary;
// there's no support for stubbed out clock (TimeSource) in ZipArchiveOutputStream
assertEquals( expectedElement.getMethod(), actualElement.getMethod());
assertEquals( expectedElement.getGeneralPurposeBit(), actualElement.getGeneralPurposeBit());
assertEquals( expectedElement.getCrc(), actualElement.getCrc());
assertEquals( expectedElement.getCompressedSize(), actualElement.getCompressedSize());
assertEquals( expectedElement.getSize(), actualElement.getSize());
assertEquals( expectedElement.getExternalAttributes(), actualElement.getExternalAttributes());
assertEquals( expectedElement.getInternalAttributes(), actualElement.getInternalAttributes());
final InputStream actualIs = actual.getInputStream(actualElement);
final InputStream expectedIs = expected.getInputStream(expectedElement);
IOUtils.readFully(expectedIs, expectedBuf);
IOUtils.readFully(actualIs, actualBuf);
expectedIs.close();
actualIs.close();
Assert.assertArrayEquals(expectedBuf, actualBuf); // Buffers are larger than payload. dont care
}
expected.close();
actual.close();
}
private void createArchiveEntry(final String payload, final ZipArchiveOutputStream zos, final String name)
throws IOException {
final ZipArchiveEntry in = new ZipArchiveEntry(name);
zos.putArchiveEntry(in);
zos.write(payload.getBytes());
zos.closeArchiveEntry();
}
@Test
public void testFileEntryFromFile() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final ZipArchiveEntry in = new ZipArchiveEntry(tmp[1], "foo");
zos.putArchiveEntry(in);
final byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
zos.write(b);
}
fis.close();
fis = null;
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo");
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertFalse(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
@Test
public void testExplicitFileEntry() throws Exception {
final File[] tmp = createTempDirAndFile();
File archive = null;
ZipArchiveOutputStream zos = null;
ZipFile zf = null;
FileInputStream fis = null;
try {
archive = File.createTempFile("test.", ".zip", tmp[0]);
archive.deleteOnExit();
zos = new ZipArchiveOutputStream(archive);
final ZipArchiveEntry in = new ZipArchiveEntry("foo");
in.setTime(tmp[1].lastModified());
in.setSize(tmp[1].length());
zos.putArchiveEntry(in);
final byte[] b = new byte[(int) tmp[1].length()];
fis = new FileInputStream(tmp[1]);
while (fis.read(b) > 0) {
zos.write(b);
}
fis.close();
fis = null;
zos.closeArchiveEntry();
zos.close();
zos = null;
zf = new ZipFile(archive);
final ZipArchiveEntry out = zf.getEntry("foo");
assertNotNull(out);
assertEquals("foo", out.getName());
assertEquals(tmp[1].length(), out.getSize());
assertEquals(tmp[1].lastModified() / 2000,
out.getLastModifiedDate().getTime() / 2000);
assertFalse(out.isDirectory());
} finally {
ZipFile.closeQuietly(zf);
if (zos != null) {
zos.close();
}
tryHardToDelete(archive);
if (fis != null) {
fis.close();
}
tryHardToDelete(tmp[1]);
rmdir(tmp[0]);
}
}
} |
|
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: f, x", 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 roxspring@apache.org
* @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: f, x", e.getMessage());
}
}
}
| // You are a professional Java test case writer, please create a test case named `testMissingOptionsException` for the issue `Cli-CLI-149`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-149
//
// ## Issue-Title:
// MissingOptionException.getMessage() changed from CLI 1.0 > 1.1
//
// ## Issue-Description:
//
// The MissingOptionException.getMessage() string changed from CLI 1.0 > 1.1.
//
//
// CLI 1.0 was poorly formatted but readable:
//
// Missing required options: -format-source-properties
//
//
// CLI 1.1 is almost unreadable:
//
// Missing required options: formatsourceproperties
//
//
// In CLI 1.0 Options.addOption(Option) prefixed the stored options with a "-" and in CLI 1.1 it doesn't.
//
//
// I would suggest changing Parser.checkRequiredOptions() to add the options to the error message with a prefix of " -":
//
//
// OLD:
//
// // loop through the required options
//
// while (iter.hasNext())
//
//
// {
// buff.append(iter.next());
// }
//
// NEW:
//
// // loop through the required options
//
// while (iter.hasNext())
//
//
// {
// buff.append(" -" + iter.next());
// }
//
// Resulting in:
//
// Missing required options: -format -source -properties
//
//
//
//
//
public void testMissingOptionsException() throws ParseException {
| 117 | 9 | 107 | src/test/org/apache/commons/cli/OptionsTest.java | src/test | ```markdown
## Issue-ID: Cli-CLI-149
## Issue-Title:
MissingOptionException.getMessage() changed from CLI 1.0 > 1.1
## Issue-Description:
The MissingOptionException.getMessage() string changed from CLI 1.0 > 1.1.
CLI 1.0 was poorly formatted but readable:
Missing required options: -format-source-properties
CLI 1.1 is almost unreadable:
Missing required options: formatsourceproperties
In CLI 1.0 Options.addOption(Option) prefixed the stored options with a "-" and in CLI 1.1 it doesn't.
I would suggest changing Parser.checkRequiredOptions() to add the options to the error message with a prefix of " -":
OLD:
// loop through the required options
while (iter.hasNext())
{
buff.append(iter.next());
}
NEW:
// loop through the required options
while (iter.hasNext())
{
buff.append(" -" + iter.next());
}
Resulting in:
Missing required options: -format -source -properties
```
You are a professional Java test case writer, please create a test case named `testMissingOptionsException` for the issue `Cli-CLI-149`, utilizing the provided issue report information and the following function signature.
```java
public void testMissingOptionsException() throws ParseException {
```
| 107 | [
"org.apache.commons.cli.Parser"
] | 635d5ffc9a82a1a0bdf2c26f83b31ce8bb20c1fcc1385f0b84e127aafc4ba4a9 | 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-149`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Cli-CLI-149
//
// ## Issue-Title:
// MissingOptionException.getMessage() changed from CLI 1.0 > 1.1
//
// ## Issue-Description:
//
// The MissingOptionException.getMessage() string changed from CLI 1.0 > 1.1.
//
//
// CLI 1.0 was poorly formatted but readable:
//
// Missing required options: -format-source-properties
//
//
// CLI 1.1 is almost unreadable:
//
// Missing required options: formatsourceproperties
//
//
// In CLI 1.0 Options.addOption(Option) prefixed the stored options with a "-" and in CLI 1.1 it doesn't.
//
//
// I would suggest changing Parser.checkRequiredOptions() to add the options to the error message with a prefix of " -":
//
//
// OLD:
//
// // loop through the required options
//
// while (iter.hasNext())
//
//
// {
// buff.append(iter.next());
// }
//
// NEW:
//
// // loop through the required options
//
// while (iter.hasNext())
//
//
// {
// buff.append(" -" + iter.next());
// }
//
// Resulting in:
//
// Missing required options: -format -source -properties
//
//
//
//
//
| 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 roxspring@apache.org
* @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: f, x", e.getMessage());
}
}
}
|
||
@Test
public void aiffFilesAreNoTARs() throws Exception {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream("src/test/resources/testAIFF.aif"));
new ArchiveStreamFactory().createArchiveInputStream(is);
fail("created an input stream for a non-archive");
} catch (ArchiveException ae) {
assertTrue(ae.getMessage().startsWith("No Archiver found"));
} finally {
if (is != null) {
is.close();
}
}
} | org.apache.commons.compress.archivers.ArchiveStreamFactoryTest::aiffFilesAreNoTARs | src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java | 63 | src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java | aiffFilesAreNoTARs | /*
* 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 static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import org.junit.Test;
public class ArchiveStreamFactoryTest {
/**
* see https://issues.apache.org/jira/browse/COMPRESS-171
*/
@Test
public void shortTextFilesAreNoTARs() throws Exception {
try {
new ArchiveStreamFactory()
.createArchiveInputStream(new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes()));
fail("created an input stream for a non-archive");
} catch (ArchiveException ae) {
assertTrue(ae.getMessage().startsWith("No Archiver found"));
}
}
/**
* see https://issues.apache.org/jira/browse/COMPRESS-191
*/
@Test
public void aiffFilesAreNoTARs() throws Exception {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream("src/test/resources/testAIFF.aif"));
new ArchiveStreamFactory().createArchiveInputStream(is);
fail("created an input stream for a non-archive");
} catch (ArchiveException ae) {
assertTrue(ae.getMessage().startsWith("No Archiver found"));
} finally {
if (is != null) {
is.close();
}
}
}
} | // You are a professional Java test case writer, please create a test case named `aiffFilesAreNoTARs` for the issue `Compress-COMPRESS-191`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-191
//
// ## Issue-Title:
// Too relaxed tar detection in ArchiveStreamFactory
//
// ## Issue-Description:
//
// The relaxed tar detection logic added in [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") unfortunately matches also some non-tar files like a [test AIFF file](https://svn.apache.org/repos/asf/tika/trunk/tika-parsers/src/test/resources/test-documents/testAIFF.aif) that Apache Tika uses. It would be good to improve the detection heuristics to still match files like the one in [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") but avoid false positives like the AIFF file in Tika.
//
//
//
//
//
@Test
public void aiffFilesAreNoTARs() throws Exception {
| 63 | /**
* see https://issues.apache.org/jira/browse/COMPRESS-191
*/ | 16 | 49 | src/test/java/org/apache/commons/compress/archivers/ArchiveStreamFactoryTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-191
## Issue-Title:
Too relaxed tar detection in ArchiveStreamFactory
## Issue-Description:
The relaxed tar detection logic added in [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") unfortunately matches also some non-tar files like a [test AIFF file](https://svn.apache.org/repos/asf/tika/trunk/tika-parsers/src/test/resources/test-documents/testAIFF.aif) that Apache Tika uses. It would be good to improve the detection heuristics to still match files like the one in [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") but avoid false positives like the AIFF file in Tika.
```
You are a professional Java test case writer, please create a test case named `aiffFilesAreNoTARs` for the issue `Compress-COMPRESS-191`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void aiffFilesAreNoTARs() throws Exception {
```
| 49 | [
"org.apache.commons.compress.archivers.ArchiveStreamFactory"
] | 63e03dd51a098763e3f4c1353fb267403303047b35235da8ef7bad8df92dd695 | @Test
public void aiffFilesAreNoTARs() throws Exception | // You are a professional Java test case writer, please create a test case named `aiffFilesAreNoTARs` for the issue `Compress-COMPRESS-191`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-191
//
// ## Issue-Title:
// Too relaxed tar detection in ArchiveStreamFactory
//
// ## Issue-Description:
//
// The relaxed tar detection logic added in [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") unfortunately matches also some non-tar files like a [test AIFF file](https://svn.apache.org/repos/asf/tika/trunk/tika-parsers/src/test/resources/test-documents/testAIFF.aif) that Apache Tika uses. It would be good to improve the detection heuristics to still match files like the one in [~~COMPRESS-117~~](https://issues.apache.org/jira/browse/COMPRESS-117 "Certain tar files not recognised by ArchiveStreamFactory") but avoid false positives like the AIFF file in Tika.
//
//
//
//
//
| 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 static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import org.junit.Test;
public class ArchiveStreamFactoryTest {
/**
* see https://issues.apache.org/jira/browse/COMPRESS-171
*/
@Test
public void shortTextFilesAreNoTARs() throws Exception {
try {
new ArchiveStreamFactory()
.createArchiveInputStream(new ByteArrayInputStream("This certainly is not a tar archive, really, no kidding".getBytes()));
fail("created an input stream for a non-archive");
} catch (ArchiveException ae) {
assertTrue(ae.getMessage().startsWith("No Archiver found"));
}
}
/**
* see https://issues.apache.org/jira/browse/COMPRESS-191
*/
@Test
public void aiffFilesAreNoTARs() throws Exception {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream("src/test/resources/testAIFF.aif"));
new ArchiveStreamFactory().createArchiveInputStream(is);
fail("created an input stream for a non-archive");
} catch (ArchiveException ae) {
assertTrue(ae.getMessage().startsWith("No Archiver found"));
} finally {
if (is != null) {
is.close();
}
}
}
} |
|
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testMath274() throws MathException {
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[][] {
{ 0.40434286, -0.09376327, 0.30328980, 0.04909388 },
{-0.09376327, 0.10400408, 0.07137959, 0.04762857 },
{ 0.30328980, 0.07137959, 0.30458776, 0.04882449 },
{ 0.04909388, 0.04762857, 0.04882449, 0.07543265 }
}));
} | org.apache.commons.math.linear.CholeskyDecompositionImplTest::testMath274 | src/test/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java | 89 | src/test/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java | testMath274 | /*
* 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.linear;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.math.MathException;
import org.apache.commons.math.linear.CholeskyDecomposition;
import org.apache.commons.math.linear.CholeskyDecompositionImpl;
import org.apache.commons.math.linear.MatrixUtils;
import org.apache.commons.math.linear.NonSquareMatrixException;
import org.apache.commons.math.linear.NotPositiveDefiniteMatrixException;
import org.apache.commons.math.linear.NotSymmetricMatrixException;
import org.apache.commons.math.linear.RealMatrix;
import org.junit.Test;
public class CholeskyDecompositionImplTest {
private double[][] testData = new double[][] {
{ 1, 2, 4, 7, 11 },
{ 2, 13, 23, 38, 58 },
{ 4, 23, 77, 122, 182 },
{ 7, 38, 122, 294, 430 },
{ 11, 58, 182, 430, 855 }
};
/** test dimensions */
@Test
public void testDimensions() throws MathException {
CholeskyDecomposition llt =
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(testData));
assertEquals(testData.length, llt.getL().getRowDimension());
assertEquals(testData.length, llt.getL().getColumnDimension());
assertEquals(testData.length, llt.getLT().getRowDimension());
assertEquals(testData.length, llt.getLT().getColumnDimension());
}
/** test non-square matrix */
@Test(expected = NonSquareMatrixException.class)
public void testNonSquare() throws MathException {
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[3][2]));
}
/** test non-symmetric matrix */
@Test(expected = NotSymmetricMatrixException.class)
public void testNotSymmetricMatrixException() throws MathException {
double[][] changed = testData.clone();
changed[0][changed[0].length - 1] += 1.0e-5;
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(changed));
}
/** test non positive definite matrix */
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testNotPositiveDefinite() throws MathException {
CholeskyDecomposition cd = new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[][] {
{ 14, 11, 13, 15, 24 },
{ 11, 34, 13, 8, 25 },
{ 13, 13, 14, 15, 21 },
{ 15, 8, 15, 18, 23 },
{ 24, 25, 21, 23, 45 }
}));
System.out.println(cd.getL().multiply(cd.getLT()));
}
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testMath274() throws MathException {
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[][] {
{ 0.40434286, -0.09376327, 0.30328980, 0.04909388 },
{-0.09376327, 0.10400408, 0.07137959, 0.04762857 },
{ 0.30328980, 0.07137959, 0.30458776, 0.04882449 },
{ 0.04909388, 0.04762857, 0.04882449, 0.07543265 }
}));
}
/** test A = LLT */
@Test
public void testAEqualLLT() throws MathException {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
CholeskyDecomposition llt = new CholeskyDecompositionImpl(matrix);
RealMatrix l = llt.getL();
RealMatrix lt = llt.getLT();
double norm = l.multiply(lt).subtract(matrix).getNorm();
assertEquals(0, norm, 1.0e-15);
}
/** test that L is lower triangular */
@Test
public void testLLowerTriangular() throws MathException {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
RealMatrix l = new CholeskyDecompositionImpl(matrix).getL();
for (int i = 0; i < l.getRowDimension(); i++) {
for (int j = i + 1; j < l.getColumnDimension(); j++) {
assertEquals(0.0, l.getEntry(i, j), 0.0);
}
}
}
/** test that LT is transpose of L */
@Test
public void testLTTransposed() throws MathException {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
CholeskyDecomposition llt = new CholeskyDecompositionImpl(matrix);
RealMatrix l = llt.getL();
RealMatrix lt = llt.getLT();
double norm = l.subtract(lt.transpose()).getNorm();
assertEquals(0, norm, 1.0e-15);
}
/** test matrices values */
@Test
public void testMatricesValues() throws MathException {
RealMatrix lRef = MatrixUtils.createRealMatrix(new double[][] {
{ 1, 0, 0, 0, 0 },
{ 2, 3, 0, 0, 0 },
{ 4, 5, 6, 0, 0 },
{ 7, 8, 9, 10, 0 },
{ 11, 12, 13, 14, 15 }
});
CholeskyDecomposition llt =
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(testData));
// check values against known references
RealMatrix l = llt.getL();
assertEquals(0, l.subtract(lRef).getNorm(), 1.0e-13);
RealMatrix lt = llt.getLT();
assertEquals(0, lt.subtract(lRef.transpose()).getNorm(), 1.0e-13);
// check the same cached instance is returned the second time
assertTrue(l == llt.getL());
assertTrue(lt == llt.getLT());
}
} | // You are a professional Java test case writer, please create a test case named `testMath274` for the issue `Math-MATH-274`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-274
//
// ## Issue-Title:
// testing for symmetric positive definite matrix in CholeskyDecomposition
//
// ## Issue-Description:
//
// I used this matrix:
//
//
// double[][] cv = {
//
//
//
//
// {0.40434286, 0.09376327, 0.30328980, 0.04909388}
// ,
//
//
//
//
// {0.09376327, 0.10400408, 0.07137959, 0.04762857}
// ,
//
//
//
//
// {0.30328980, 0.07137959, 0.30458776, 0.04882449},
//
// {0.04909388, 0.04762857, 0.04882449, 0.07543265}
//
// };
//
//
//
// And it works fine, because it is symmetric positive definite
//
//
//
// I tried this matrix:
//
//
//
// double[][] cv = {
//
// {0.40434286, -0.09376327, 0.30328980, 0.04909388},
//
// {-0.09376327, 0.10400408, 0.07137959, 0.04762857},
//
// {0.30328980, 0.07137959, 0.30458776, 0.04882449}
// ,
//
//
// {0.04909388, 0.04762857, 0.04882449, 0.07543265}
// };
//
//
// And it should throw an exception but it does not. I tested the matrix in R and R's cholesky decomposition method returns that the matrix is not symmetric positive definite.
//
//
// Obviously your code is not catching this appropriately.
//
//
// By the way (in my opinion) the use of exceptions to check these conditions is not the best design or use for exceptions. If you are going to force the use to try and catch these exceptions at least provide methods to test the conditions prior to the possibility of the exception.
//
//
//
//
//
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testMath274() throws MathException {
| 89 | 86 | 80 | src/test/org/apache/commons/math/linear/CholeskyDecompositionImplTest.java | src/test | ```markdown
## Issue-ID: Math-MATH-274
## Issue-Title:
testing for symmetric positive definite matrix in CholeskyDecomposition
## Issue-Description:
I used this matrix:
double[][] cv = {
{0.40434286, 0.09376327, 0.30328980, 0.04909388}
,
{0.09376327, 0.10400408, 0.07137959, 0.04762857}
,
{0.30328980, 0.07137959, 0.30458776, 0.04882449},
{0.04909388, 0.04762857, 0.04882449, 0.07543265}
};
And it works fine, because it is symmetric positive definite
I tried this matrix:
double[][] cv = {
{0.40434286, -0.09376327, 0.30328980, 0.04909388},
{-0.09376327, 0.10400408, 0.07137959, 0.04762857},
{0.30328980, 0.07137959, 0.30458776, 0.04882449}
,
{0.04909388, 0.04762857, 0.04882449, 0.07543265}
};
And it should throw an exception but it does not. I tested the matrix in R and R's cholesky decomposition method returns that the matrix is not symmetric positive definite.
Obviously your code is not catching this appropriately.
By the way (in my opinion) the use of exceptions to check these conditions is not the best design or use for exceptions. If you are going to force the use to try and catch these exceptions at least provide methods to test the conditions prior to the possibility of the exception.
```
You are a professional Java test case writer, please create a test case named `testMath274` for the issue `Math-MATH-274`, utilizing the provided issue report information and the following function signature.
```java
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testMath274() throws MathException {
```
| 80 | [
"org.apache.commons.math.linear.CholeskyDecompositionImpl"
] | 63e151798d1601378514485c75045bcb5b13259258494f6d1376c15ffdc51d79 | @Test(expected = NotPositiveDefiniteMatrixException.class)
public void testMath274() throws MathException | // You are a professional Java test case writer, please create a test case named `testMath274` for the issue `Math-MATH-274`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-274
//
// ## Issue-Title:
// testing for symmetric positive definite matrix in CholeskyDecomposition
//
// ## Issue-Description:
//
// I used this matrix:
//
//
// double[][] cv = {
//
//
//
//
// {0.40434286, 0.09376327, 0.30328980, 0.04909388}
// ,
//
//
//
//
// {0.09376327, 0.10400408, 0.07137959, 0.04762857}
// ,
//
//
//
//
// {0.30328980, 0.07137959, 0.30458776, 0.04882449},
//
// {0.04909388, 0.04762857, 0.04882449, 0.07543265}
//
// };
//
//
//
// And it works fine, because it is symmetric positive definite
//
//
//
// I tried this matrix:
//
//
//
// double[][] cv = {
//
// {0.40434286, -0.09376327, 0.30328980, 0.04909388},
//
// {-0.09376327, 0.10400408, 0.07137959, 0.04762857},
//
// {0.30328980, 0.07137959, 0.30458776, 0.04882449}
// ,
//
//
// {0.04909388, 0.04762857, 0.04882449, 0.07543265}
// };
//
//
// And it should throw an exception but it does not. I tested the matrix in R and R's cholesky decomposition method returns that the matrix is not symmetric positive definite.
//
//
// Obviously your code is not catching this appropriately.
//
//
// By the way (in my opinion) the use of exceptions to check these conditions is not the best design or use for exceptions. If you are going to force the use to try and catch these exceptions at least provide methods to test the conditions prior to the possibility of the exception.
//
//
//
//
//
| 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.linear;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.math.MathException;
import org.apache.commons.math.linear.CholeskyDecomposition;
import org.apache.commons.math.linear.CholeskyDecompositionImpl;
import org.apache.commons.math.linear.MatrixUtils;
import org.apache.commons.math.linear.NonSquareMatrixException;
import org.apache.commons.math.linear.NotPositiveDefiniteMatrixException;
import org.apache.commons.math.linear.NotSymmetricMatrixException;
import org.apache.commons.math.linear.RealMatrix;
import org.junit.Test;
public class CholeskyDecompositionImplTest {
private double[][] testData = new double[][] {
{ 1, 2, 4, 7, 11 },
{ 2, 13, 23, 38, 58 },
{ 4, 23, 77, 122, 182 },
{ 7, 38, 122, 294, 430 },
{ 11, 58, 182, 430, 855 }
};
/** test dimensions */
@Test
public void testDimensions() throws MathException {
CholeskyDecomposition llt =
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(testData));
assertEquals(testData.length, llt.getL().getRowDimension());
assertEquals(testData.length, llt.getL().getColumnDimension());
assertEquals(testData.length, llt.getLT().getRowDimension());
assertEquals(testData.length, llt.getLT().getColumnDimension());
}
/** test non-square matrix */
@Test(expected = NonSquareMatrixException.class)
public void testNonSquare() throws MathException {
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[3][2]));
}
/** test non-symmetric matrix */
@Test(expected = NotSymmetricMatrixException.class)
public void testNotSymmetricMatrixException() throws MathException {
double[][] changed = testData.clone();
changed[0][changed[0].length - 1] += 1.0e-5;
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(changed));
}
/** test non positive definite matrix */
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testNotPositiveDefinite() throws MathException {
CholeskyDecomposition cd = new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[][] {
{ 14, 11, 13, 15, 24 },
{ 11, 34, 13, 8, 25 },
{ 13, 13, 14, 15, 21 },
{ 15, 8, 15, 18, 23 },
{ 24, 25, 21, 23, 45 }
}));
System.out.println(cd.getL().multiply(cd.getLT()));
}
@Test(expected = NotPositiveDefiniteMatrixException.class)
public void testMath274() throws MathException {
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(new double[][] {
{ 0.40434286, -0.09376327, 0.30328980, 0.04909388 },
{-0.09376327, 0.10400408, 0.07137959, 0.04762857 },
{ 0.30328980, 0.07137959, 0.30458776, 0.04882449 },
{ 0.04909388, 0.04762857, 0.04882449, 0.07543265 }
}));
}
/** test A = LLT */
@Test
public void testAEqualLLT() throws MathException {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
CholeskyDecomposition llt = new CholeskyDecompositionImpl(matrix);
RealMatrix l = llt.getL();
RealMatrix lt = llt.getLT();
double norm = l.multiply(lt).subtract(matrix).getNorm();
assertEquals(0, norm, 1.0e-15);
}
/** test that L is lower triangular */
@Test
public void testLLowerTriangular() throws MathException {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
RealMatrix l = new CholeskyDecompositionImpl(matrix).getL();
for (int i = 0; i < l.getRowDimension(); i++) {
for (int j = i + 1; j < l.getColumnDimension(); j++) {
assertEquals(0.0, l.getEntry(i, j), 0.0);
}
}
}
/** test that LT is transpose of L */
@Test
public void testLTTransposed() throws MathException {
RealMatrix matrix = MatrixUtils.createRealMatrix(testData);
CholeskyDecomposition llt = new CholeskyDecompositionImpl(matrix);
RealMatrix l = llt.getL();
RealMatrix lt = llt.getLT();
double norm = l.subtract(lt.transpose()).getNorm();
assertEquals(0, norm, 1.0e-15);
}
/** test matrices values */
@Test
public void testMatricesValues() throws MathException {
RealMatrix lRef = MatrixUtils.createRealMatrix(new double[][] {
{ 1, 0, 0, 0, 0 },
{ 2, 3, 0, 0, 0 },
{ 4, 5, 6, 0, 0 },
{ 7, 8, 9, 10, 0 },
{ 11, 12, 13, 14, 15 }
});
CholeskyDecomposition llt =
new CholeskyDecompositionImpl(MatrixUtils.createRealMatrix(testData));
// check values against known references
RealMatrix l = llt.getL();
assertEquals(0, l.subtract(lRef).getNorm(), 1.0e-13);
RealMatrix lt = llt.getLT();
assertEquals(0, lt.subtract(lRef.transpose()).getNorm(), 1.0e-13);
// check the same cached instance is returned the second time
assertTrue(l == llt.getL());
assertTrue(lt == llt.getLT());
}
} |
||
@Test
public void should_spy_inner_class() throws Exception {
class WithMockAndSpy {
@Spy private InnerStrength strength;
@Mock private List<String> list;
abstract class InnerStrength {
private final String name;
InnerStrength() {
// Make sure that @Mock fields are always injected before @Spy fields.
assertNotNull(list);
// Make sure constructor is indeed called.
this.name = "inner";
}
abstract String strength();
String fullStrength() {
return name + " " + strength();
}
}
}
WithMockAndSpy outer = new WithMockAndSpy();
MockitoAnnotations.initMocks(outer);
when(outer.strength.strength()).thenReturn("strength");
assertEquals("inner strength", outer.strength.fullStrength());
} | org.mockitousage.annotation.SpyAnnotationTest::should_spy_inner_class | test/org/mockitousage/annotation/SpyAnnotationTest.java | 150 | test/org/mockitousage/annotation/SpyAnnotationTest.java | should_spy_inner_class | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockitousage.annotation;
import org.fest.assertions.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.exceptions.base.MockitoException;
import org.mockitoutil.TestBase;
import java.util.*;
import static org.mockito.Mockito.*;
@SuppressWarnings({"unchecked", "unused"})
public class SpyAnnotationTest extends TestBase {
@Spy final List spiedList = new ArrayList();
@Spy NestedClassWithNoArgConstructor staticTypeWithNoArgConstructor;
@Spy
NestedClassWithoutDefinedConstructor staticTypeWithoutDefinedConstructor;
@Rule public final ExpectedException shouldThrow = ExpectedException.none();
@Test
public void should_init_spy_by_instance() throws Exception {
doReturn("foo").when(spiedList).get(10);
assertEquals("foo", spiedList.get(10));
assertTrue(spiedList.isEmpty());
}
@Test
public void should_init_spy_and_automatically_create_instance() throws Exception {
when(staticTypeWithNoArgConstructor.toString()).thenReturn("x");
when(staticTypeWithoutDefinedConstructor.toString()).thenReturn("y");
assertEquals("x", staticTypeWithNoArgConstructor.toString());
assertEquals("y", staticTypeWithoutDefinedConstructor.toString());
}
@Test
public void should_prevent_spying_on_interfaces() throws Exception {
class WithSpy {
@Spy List<String> list;
}
WithSpy withSpy = new WithSpy();
try {
MockitoAnnotations.initMocks(withSpy);
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("is an interface and it cannot be spied on");
}
}
@Test
public void should_allow_spying_on_interfaces_when_instance_is_concrete() throws Exception {
class WithSpy {
@Spy List<String> list = new LinkedList<String>();
}
WithSpy withSpy = new WithSpy();
//when
MockitoAnnotations.initMocks(withSpy);
//then
verify(withSpy.list, never()).clear();
}
@Test
public void should_report_when_no_arg_less_constructor() throws Exception {
class FailingSpy {
@Spy
NoValidConstructor noValidConstructor;
}
try {
MockitoAnnotations.initMocks(new FailingSpy());
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("0-arg constructor");
}
}
@Test
public void should_report_when_constructor_is_explosive() throws Exception {
class FailingSpy {
@Spy
ThrowingConstructor throwingConstructor;
}
try {
MockitoAnnotations.initMocks(new FailingSpy());
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("Unable to create mock instance");
}
}
@Test
public void should_spy_abstract_class() throws Exception {
class SpyAbstractClass {
@Spy AbstractList<String> list;
List<String> asSingletonList(String s) {
when(list.size()).thenReturn(1);
when(list.get(0)).thenReturn(s);
return list;
}
}
SpyAbstractClass withSpy = new SpyAbstractClass();
MockitoAnnotations.initMocks(withSpy);
assertEquals(Arrays.asList("a"), withSpy.asSingletonList("a"));
}
@Test
public void should_spy_inner_class() throws Exception {
class WithMockAndSpy {
@Spy private InnerStrength strength;
@Mock private List<String> list;
abstract class InnerStrength {
private final String name;
InnerStrength() {
// Make sure that @Mock fields are always injected before @Spy fields.
assertNotNull(list);
// Make sure constructor is indeed called.
this.name = "inner";
}
abstract String strength();
String fullStrength() {
return name + " " + strength();
}
}
}
WithMockAndSpy outer = new WithMockAndSpy();
MockitoAnnotations.initMocks(outer);
when(outer.strength.strength()).thenReturn("strength");
assertEquals("inner strength", outer.strength.fullStrength());
}
@Test(expected = IndexOutOfBoundsException.class)
public void should_reset_spy() throws Exception {
spiedList.get(10); // see shouldInitSpy
}
@Test
public void should_report_when_encosing_instance_is_needed() throws Exception {
class Outer {
class Inner {}
}
class WithSpy {
@Spy private Outer.Inner inner;
}
try {
MockitoAnnotations.initMocks(new WithSpy());
fail();
} catch (MockitoException e) {
assertContains("@Spy annotation can only initialize inner classes", e.getMessage());
}
}
static class NestedClassWithoutDefinedConstructor { }
static class NestedClassWithNoArgConstructor {
NestedClassWithNoArgConstructor() { }
NestedClassWithNoArgConstructor(String f) { }
}
static class NoValidConstructor {
NoValidConstructor(String f) { }
}
static class ThrowingConstructor {
ThrowingConstructor() { throw new RuntimeException("boo!"); }
}
} | // You are a professional Java test case writer, please create a test case named `should_spy_inner_class` for the issue `Mockito-92`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-92
//
// ## Issue-Title:
// Allow convenient spying on abstract classes
//
// ## Issue-Description:
// I posted this in GoogleCode and was asked to submit in github.
//
//
// Mockito is easy to use when the test needs to provide canned values for a certain method.
//
//
// But it gets harder when a canned value isn't sufficient.
//
//
// ##### Example 1: Fake with trivial Logic
//
//
//
// ```
// interface UserAccount {
// List<String> getEmails();
// void addEmail(String email);
// // 12 other methods ...
// }
//
// ```
//
// When mocking such domain entity object, it's tedious to manually program getEmails()/addEmail() with when().thenReturn() and to make sure the two methods are logically consistent, that is, getEmails() returns all emails added.
//
//
// ##### Example 2: callback-style API
//
//
//
// ```
// interface AccountService {
// void getAccount(String id, AsyncCallback<UserAccount> callback);
// }
//
// ```
//
// Stubbing AccountService isn't easy. It'd require use of Answer, and the Answer API isn't statically type safe:
//
//
//
// ```
// when(service.getAccount(eq(id), any(AsyncCallback.class)).thenAnswer(new Answer<Void>() {
// AsyncCallback<UserAccount> callback = (AsyncCallback<UserAccount>) getArguments()[1];
// ...
// });
//
// ```
//
// ##### Example 3: Uninteresting parameters
//
//
//
// ```
// interface AccountRpcService {
// FutureAccount getAccount(RpcContext context, String id);
// }
//
// ```
//
// None of the tests care about the context object. It's an uninteresting parameter imposed by the framework.
//
//
// If AccountRpcService were directly mocked, all tests would have to use isA() to repetitively mention this uninteresting parameter, like this:
//
//
// `when(service.getAccount(isA(RpcContext.class), eq("id")).thenReturn(...);`
//
//
// And all other parameters are required to be wrapped in eq().
//
//
// #### Proposal
//
//
// I propose adding support for abstract classes to mockito to make it easier to deal with tests like above:
//
//
// ##### For example 1
//
//
//
// ```
// abstract class FakeUserAccount implements UserAccount {
// private final List<String> emails = new ArrayList<>();
//
// @Override public void addEmail(String email) {
// emails.add(email);
// }
// @Override List<String> getEmails() {
// return ImmutableList.copyOf(emails);
// }
// }
//
// @Fake private FakeUserAccount userAccount; // Mockito instantiates abstract class.
//
// ```
//
// ##### For example 2
//
//
//
// ```
// abstract class MockAccountService implements AccountService {
// @Override public void getAccount(String id, AsyncCallback<UserAccount> callback) {
// callback.onSuccess(getAccount(id));
// }
// abstract UserAccount getAccount(String id);
// }
//
// @Fake private MockAccountService service;
//
// ...
//
// when(service.getAccount("id")).thenReturn(account);
//
// ```
//
// ##### For example 3
//
//
//
// ```
// abstract class MockAccountRpcService implements AccountRpcService {
// @Override Future<Account> getAccount(RpcContext context, String id) {
// checkNotNull(context); // Common sanity test. Don't have to repeat it in tests.
// return getAccount(id);
// }
//
// abstract Future<Account> getAccount(String id);
// }
//
// @Fake private MockAccountRpcService service;
//
// when(service.getAccount("id")).thenReturn(...);
//
// ```
//
// My work place internally implemented a default Answer to support abstract classes. We found that the support of abstract classes helps us to avoid overusing mocks when we should be using fakes. And in situations like above we get cleaner test code.
//
//
// But because it's not integrated in the core Mockito, there are gotchas with our implementation (like, you can't have private/final methods in your fake).
//
//
// If the idea sounds okay to give a try, I'll volunteer to submit a patch.
//
//
// Thanks!
//
//
//
//
@Test
public void should_spy_inner_class() throws Exception {
| 150 | 20 | 122 | test/org/mockitousage/annotation/SpyAnnotationTest.java | test | ```markdown
## Issue-ID: Mockito-92
## Issue-Title:
Allow convenient spying on abstract classes
## Issue-Description:
I posted this in GoogleCode and was asked to submit in github.
Mockito is easy to use when the test needs to provide canned values for a certain method.
But it gets harder when a canned value isn't sufficient.
##### Example 1: Fake with trivial Logic
```
interface UserAccount {
List<String> getEmails();
void addEmail(String email);
// 12 other methods ...
}
```
When mocking such domain entity object, it's tedious to manually program getEmails()/addEmail() with when().thenReturn() and to make sure the two methods are logically consistent, that is, getEmails() returns all emails added.
##### Example 2: callback-style API
```
interface AccountService {
void getAccount(String id, AsyncCallback<UserAccount> callback);
}
```
Stubbing AccountService isn't easy. It'd require use of Answer, and the Answer API isn't statically type safe:
```
when(service.getAccount(eq(id), any(AsyncCallback.class)).thenAnswer(new Answer<Void>() {
AsyncCallback<UserAccount> callback = (AsyncCallback<UserAccount>) getArguments()[1];
...
});
```
##### Example 3: Uninteresting parameters
```
interface AccountRpcService {
FutureAccount getAccount(RpcContext context, String id);
}
```
None of the tests care about the context object. It's an uninteresting parameter imposed by the framework.
If AccountRpcService were directly mocked, all tests would have to use isA() to repetitively mention this uninteresting parameter, like this:
`when(service.getAccount(isA(RpcContext.class), eq("id")).thenReturn(...);`
And all other parameters are required to be wrapped in eq().
#### Proposal
I propose adding support for abstract classes to mockito to make it easier to deal with tests like above:
##### For example 1
```
abstract class FakeUserAccount implements UserAccount {
private final List<String> emails = new ArrayList<>();
@Override public void addEmail(String email) {
emails.add(email);
}
@Override List<String> getEmails() {
return ImmutableList.copyOf(emails);
}
}
@Fake private FakeUserAccount userAccount; // Mockito instantiates abstract class.
```
##### For example 2
```
abstract class MockAccountService implements AccountService {
@Override public void getAccount(String id, AsyncCallback<UserAccount> callback) {
callback.onSuccess(getAccount(id));
}
abstract UserAccount getAccount(String id);
}
@Fake private MockAccountService service;
...
when(service.getAccount("id")).thenReturn(account);
```
##### For example 3
```
abstract class MockAccountRpcService implements AccountRpcService {
@Override Future<Account> getAccount(RpcContext context, String id) {
checkNotNull(context); // Common sanity test. Don't have to repeat it in tests.
return getAccount(id);
}
abstract Future<Account> getAccount(String id);
}
@Fake private MockAccountRpcService service;
when(service.getAccount("id")).thenReturn(...);
```
My work place internally implemented a default Answer to support abstract classes. We found that the support of abstract classes helps us to avoid overusing mocks when we should be using fakes. And in situations like above we get cleaner test code.
But because it's not integrated in the core Mockito, there are gotchas with our implementation (like, you can't have private/final methods in your fake).
If the idea sounds okay to give a try, I'll volunteer to submit a patch.
Thanks!
```
You are a professional Java test case writer, please create a test case named `should_spy_inner_class` for the issue `Mockito-92`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void should_spy_inner_class() throws Exception {
```
| 122 | [
"org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker"
] | 64480f2dd9e55557c34ef4e7311fb676124dea3b0db219b15793d92ca01fa07d | @Test
public void should_spy_inner_class() throws Exception | // You are a professional Java test case writer, please create a test case named `should_spy_inner_class` for the issue `Mockito-92`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Mockito-92
//
// ## Issue-Title:
// Allow convenient spying on abstract classes
//
// ## Issue-Description:
// I posted this in GoogleCode and was asked to submit in github.
//
//
// Mockito is easy to use when the test needs to provide canned values for a certain method.
//
//
// But it gets harder when a canned value isn't sufficient.
//
//
// ##### Example 1: Fake with trivial Logic
//
//
//
// ```
// interface UserAccount {
// List<String> getEmails();
// void addEmail(String email);
// // 12 other methods ...
// }
//
// ```
//
// When mocking such domain entity object, it's tedious to manually program getEmails()/addEmail() with when().thenReturn() and to make sure the two methods are logically consistent, that is, getEmails() returns all emails added.
//
//
// ##### Example 2: callback-style API
//
//
//
// ```
// interface AccountService {
// void getAccount(String id, AsyncCallback<UserAccount> callback);
// }
//
// ```
//
// Stubbing AccountService isn't easy. It'd require use of Answer, and the Answer API isn't statically type safe:
//
//
//
// ```
// when(service.getAccount(eq(id), any(AsyncCallback.class)).thenAnswer(new Answer<Void>() {
// AsyncCallback<UserAccount> callback = (AsyncCallback<UserAccount>) getArguments()[1];
// ...
// });
//
// ```
//
// ##### Example 3: Uninteresting parameters
//
//
//
// ```
// interface AccountRpcService {
// FutureAccount getAccount(RpcContext context, String id);
// }
//
// ```
//
// None of the tests care about the context object. It's an uninteresting parameter imposed by the framework.
//
//
// If AccountRpcService were directly mocked, all tests would have to use isA() to repetitively mention this uninteresting parameter, like this:
//
//
// `when(service.getAccount(isA(RpcContext.class), eq("id")).thenReturn(...);`
//
//
// And all other parameters are required to be wrapped in eq().
//
//
// #### Proposal
//
//
// I propose adding support for abstract classes to mockito to make it easier to deal with tests like above:
//
//
// ##### For example 1
//
//
//
// ```
// abstract class FakeUserAccount implements UserAccount {
// private final List<String> emails = new ArrayList<>();
//
// @Override public void addEmail(String email) {
// emails.add(email);
// }
// @Override List<String> getEmails() {
// return ImmutableList.copyOf(emails);
// }
// }
//
// @Fake private FakeUserAccount userAccount; // Mockito instantiates abstract class.
//
// ```
//
// ##### For example 2
//
//
//
// ```
// abstract class MockAccountService implements AccountService {
// @Override public void getAccount(String id, AsyncCallback<UserAccount> callback) {
// callback.onSuccess(getAccount(id));
// }
// abstract UserAccount getAccount(String id);
// }
//
// @Fake private MockAccountService service;
//
// ...
//
// when(service.getAccount("id")).thenReturn(account);
//
// ```
//
// ##### For example 3
//
//
//
// ```
// abstract class MockAccountRpcService implements AccountRpcService {
// @Override Future<Account> getAccount(RpcContext context, String id) {
// checkNotNull(context); // Common sanity test. Don't have to repeat it in tests.
// return getAccount(id);
// }
//
// abstract Future<Account> getAccount(String id);
// }
//
// @Fake private MockAccountRpcService service;
//
// when(service.getAccount("id")).thenReturn(...);
//
// ```
//
// My work place internally implemented a default Answer to support abstract classes. We found that the support of abstract classes helps us to avoid overusing mocks when we should be using fakes. And in situations like above we get cleaner test code.
//
//
// But because it's not integrated in the core Mockito, there are gotchas with our implementation (like, you can't have private/final methods in your fake).
//
//
// If the idea sounds okay to give a try, I'll volunteer to submit a patch.
//
//
// Thanks!
//
//
//
//
| Mockito | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockitousage.annotation;
import org.fest.assertions.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.exceptions.base.MockitoException;
import org.mockitoutil.TestBase;
import java.util.*;
import static org.mockito.Mockito.*;
@SuppressWarnings({"unchecked", "unused"})
public class SpyAnnotationTest extends TestBase {
@Spy final List spiedList = new ArrayList();
@Spy NestedClassWithNoArgConstructor staticTypeWithNoArgConstructor;
@Spy
NestedClassWithoutDefinedConstructor staticTypeWithoutDefinedConstructor;
@Rule public final ExpectedException shouldThrow = ExpectedException.none();
@Test
public void should_init_spy_by_instance() throws Exception {
doReturn("foo").when(spiedList).get(10);
assertEquals("foo", spiedList.get(10));
assertTrue(spiedList.isEmpty());
}
@Test
public void should_init_spy_and_automatically_create_instance() throws Exception {
when(staticTypeWithNoArgConstructor.toString()).thenReturn("x");
when(staticTypeWithoutDefinedConstructor.toString()).thenReturn("y");
assertEquals("x", staticTypeWithNoArgConstructor.toString());
assertEquals("y", staticTypeWithoutDefinedConstructor.toString());
}
@Test
public void should_prevent_spying_on_interfaces() throws Exception {
class WithSpy {
@Spy List<String> list;
}
WithSpy withSpy = new WithSpy();
try {
MockitoAnnotations.initMocks(withSpy);
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("is an interface and it cannot be spied on");
}
}
@Test
public void should_allow_spying_on_interfaces_when_instance_is_concrete() throws Exception {
class WithSpy {
@Spy List<String> list = new LinkedList<String>();
}
WithSpy withSpy = new WithSpy();
//when
MockitoAnnotations.initMocks(withSpy);
//then
verify(withSpy.list, never()).clear();
}
@Test
public void should_report_when_no_arg_less_constructor() throws Exception {
class FailingSpy {
@Spy
NoValidConstructor noValidConstructor;
}
try {
MockitoAnnotations.initMocks(new FailingSpy());
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("0-arg constructor");
}
}
@Test
public void should_report_when_constructor_is_explosive() throws Exception {
class FailingSpy {
@Spy
ThrowingConstructor throwingConstructor;
}
try {
MockitoAnnotations.initMocks(new FailingSpy());
fail();
} catch (MockitoException e) {
Assertions.assertThat(e.getMessage()).contains("Unable to create mock instance");
}
}
@Test
public void should_spy_abstract_class() throws Exception {
class SpyAbstractClass {
@Spy AbstractList<String> list;
List<String> asSingletonList(String s) {
when(list.size()).thenReturn(1);
when(list.get(0)).thenReturn(s);
return list;
}
}
SpyAbstractClass withSpy = new SpyAbstractClass();
MockitoAnnotations.initMocks(withSpy);
assertEquals(Arrays.asList("a"), withSpy.asSingletonList("a"));
}
@Test
public void should_spy_inner_class() throws Exception {
class WithMockAndSpy {
@Spy private InnerStrength strength;
@Mock private List<String> list;
abstract class InnerStrength {
private final String name;
InnerStrength() {
// Make sure that @Mock fields are always injected before @Spy fields.
assertNotNull(list);
// Make sure constructor is indeed called.
this.name = "inner";
}
abstract String strength();
String fullStrength() {
return name + " " + strength();
}
}
}
WithMockAndSpy outer = new WithMockAndSpy();
MockitoAnnotations.initMocks(outer);
when(outer.strength.strength()).thenReturn("strength");
assertEquals("inner strength", outer.strength.fullStrength());
}
@Test(expected = IndexOutOfBoundsException.class)
public void should_reset_spy() throws Exception {
spiedList.get(10); // see shouldInitSpy
}
@Test
public void should_report_when_encosing_instance_is_needed() throws Exception {
class Outer {
class Inner {}
}
class WithSpy {
@Spy private Outer.Inner inner;
}
try {
MockitoAnnotations.initMocks(new WithSpy());
fail();
} catch (MockitoException e) {
assertContains("@Spy annotation can only initialize inner classes", e.getMessage());
}
}
static class NestedClassWithoutDefinedConstructor { }
static class NestedClassWithNoArgConstructor {
NestedClassWithNoArgConstructor() { }
NestedClassWithNoArgConstructor(String f) { }
}
static class NoValidConstructor {
NoValidConstructor(String f) { }
}
static class ThrowingConstructor {
ThrowingConstructor() { throw new RuntimeException("boo!"); }
}
} |
||
public void testLang300() {
NumberUtils.createNumber("-1l");
NumberUtils.createNumber("01l");
NumberUtils.createNumber("1l");
} | org.apache.commons.lang.math.NumberUtilsTest::testLang300 | src/test/org/apache/commons/lang/math/NumberUtilsTest.java | 1,371 | src/test/org/apache/commons/lang/math/NumberUtilsTest.java | testLang300 | /*
* 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.math;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
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.math.NumberUtils}.
*
* @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @author Eric Pugh
* @author Phil Steitz
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @version $Id$
*/
public class NumberUtilsTest extends TestCase {
public NumberUtilsTest(String name) {
super(name);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(NumberUtilsTest.class);
suite.setName("NumberUtils Tests");
return suite;
}
//-----------------------------------------------------------------------
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#stringToInt(String)}.
*/
public void testStringToIntString() {
assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345);
assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0);
assertTrue("stringToInt(empty) failed", NumberUtils.stringToInt("") == 0);
assertTrue("stringToInt(null) failed", NumberUtils.stringToInt(null) == 0);
}
/**
* 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#stringToInt(String, int)}.
*/
public void testStringToIntStringI() {
assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345);
assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 5) == 5);
}
/**
* 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);
}
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));
}
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
}
}
// equals tests
// ----------------------------------------------------------------------
public void testEqualsByte() {
byte[] array1 = null;
byte[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new byte[] { 50, 20 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new byte[] { 50, 20 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new byte[] { 20, 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new byte[] { 50, 20, 10 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new byte[] { 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsShort() {
short[] array1 = null;
short[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new short[] { 50, 20 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new short[] { 50, 20 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new short[] { 20, 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new short[] { 50, 20, 10 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new short[] { 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsInt() {
int[] array1 = null;
int[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new int[] { 50, 20 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new int[] { 50, 20 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new int[] { 20, 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new int[] { 50, 20, 10 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new int[] { 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsLong() {
long[] array1 = null;
long[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new long[] { 50L, 20L }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new long[] { 50L, 20L };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new long[] { 20L, 50L };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new long[] { 50L, 20L, 10L };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new long[] { 50L };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsFloat() {
float[] array1 = null;
float[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new float[] { 50.6f, 20.6f }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new float[] { 50.6f, 20.6f };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new float[] { 20.6f, 50.6f };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new float[] { 50.6f, 20.6f, 10.6f };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new float[] { 50.6f };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsDouble() {
double[] array1 = null;
double[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new double[] { 50.6, 20.6 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new double[] { 50.6, 20.6 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new double[] { 20.6, 50.6 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new double[] { 50.6, 20.6, 10.6 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new double[] { 50.6 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
// 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);
}
public void testCompareDouble() {
assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0);
assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0);
assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1);
assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0);
assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1);
assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0);
assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0);
assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0);
}
public void testCompareFloat() {
assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0);
assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0);
assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1);
assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0);
assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1);
assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0);
assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0);
assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.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));
}
private boolean checkCreateNumber(String val) {
try {
Object obj = NumberUtils.createNumber(val);
if (obj == null) {
return false;
}
return true;
} catch (NumberFormatException e) {
return false;
}
}
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");
}
} | // You are a professional Java test case writer, please create a test case named `testLang300` for the issue `Lang-LANG-300`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-300
//
// ## Issue-Title:
// NumberUtils.createNumber throws NumberFormatException for one digit long
//
// ## Issue-Description:
//
// NumberUtils.createNumber throws a NumberFormatException when parsing "1l", "2l" .. etc...
//
//
// It works fine if you try to parse "01l" or "02l". The condition isDigits(numeric.substring(1)), line 455 return false as numeric.substring(1) is an empty string for "1l"
//
//
//
//
//
public void testLang300() {
| 1,371 | 58 | 1,367 | src/test/org/apache/commons/lang/math/NumberUtilsTest.java | src/test | ```markdown
## Issue-ID: Lang-LANG-300
## Issue-Title:
NumberUtils.createNumber throws NumberFormatException for one digit long
## Issue-Description:
NumberUtils.createNumber throws a NumberFormatException when parsing "1l", "2l" .. etc...
It works fine if you try to parse "01l" or "02l". The condition isDigits(numeric.substring(1)), line 455 return false as numeric.substring(1) is an empty string for "1l"
```
You are a professional Java test case writer, please create a test case named `testLang300` for the issue `Lang-LANG-300`, utilizing the provided issue report information and the following function signature.
```java
public void testLang300() {
```
| 1,367 | [
"org.apache.commons.lang.math.NumberUtils"
] | 64901e2907988ea67a61ff13490d286fd4ef3f677a32f1326760b9aa6c69ca1a | public void testLang300() | // You are a professional Java test case writer, please create a test case named `testLang300` for the issue `Lang-LANG-300`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-300
//
// ## Issue-Title:
// NumberUtils.createNumber throws NumberFormatException for one digit long
//
// ## Issue-Description:
//
// NumberUtils.createNumber throws a NumberFormatException when parsing "1l", "2l" .. etc...
//
//
// It works fine if you try to parse "01l" or "02l". The condition isDigits(numeric.substring(1)), line 455 return false as numeric.substring(1) is an empty string for "1l"
//
//
//
//
//
| 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.math;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
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.math.NumberUtils}.
*
* @author <a href="mailto:rand_mcneely@yahoo.com">Rand McNeely</a>
* @author <a href="mailto:ridesmet@users.sourceforge.net">Ringo De Smet</a>
* @author Eric Pugh
* @author Phil Steitz
* @author Stephen Colebourne
* @author Matthew Hawthorne
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @version $Id$
*/
public class NumberUtilsTest extends TestCase {
public NumberUtilsTest(String name) {
super(name);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(NumberUtilsTest.class);
suite.setName("NumberUtils Tests");
return suite;
}
//-----------------------------------------------------------------------
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#stringToInt(String)}.
*/
public void testStringToIntString() {
assertTrue("stringToInt(String) 1 failed", NumberUtils.stringToInt("12345") == 12345);
assertTrue("stringToInt(String) 2 failed", NumberUtils.stringToInt("abc") == 0);
assertTrue("stringToInt(empty) failed", NumberUtils.stringToInt("") == 0);
assertTrue("stringToInt(null) failed", NumberUtils.stringToInt(null) == 0);
}
/**
* 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#stringToInt(String, int)}.
*/
public void testStringToIntStringI() {
assertTrue("stringToInt(String,int) 1 failed", NumberUtils.stringToInt("12345", 5) == 12345);
assertTrue("stringToInt(String,int) 2 failed", NumberUtils.stringToInt("1234.5", 5) == 5);
}
/**
* 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);
}
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));
}
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
}
}
// equals tests
// ----------------------------------------------------------------------
public void testEqualsByte() {
byte[] array1 = null;
byte[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new byte[] { 50, 20 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new byte[] { 50, 20 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new byte[] { 20, 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new byte[] { 50, 20, 10 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new byte[] { 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsShort() {
short[] array1 = null;
short[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new short[] { 50, 20 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new short[] { 50, 20 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new short[] { 20, 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new short[] { 50, 20, 10 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new short[] { 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsInt() {
int[] array1 = null;
int[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new int[] { 50, 20 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new int[] { 50, 20 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new int[] { 20, 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new int[] { 50, 20, 10 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new int[] { 50 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsLong() {
long[] array1 = null;
long[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new long[] { 50L, 20L }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new long[] { 50L, 20L };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new long[] { 20L, 50L };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new long[] { 50L, 20L, 10L };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new long[] { 50L };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsFloat() {
float[] array1 = null;
float[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new float[] { 50.6f, 20.6f }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new float[] { 50.6f, 20.6f };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new float[] { 20.6f, 50.6f };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new float[] { 50.6f, 20.6f, 10.6f };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new float[] { 50.6f };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
public void testEqualsDouble() {
double[] array1 = null;
double[] array2 = null;
assertEquals( true, NumberUtils.equals(array1, array2) );
assertEquals( true, NumberUtils.equals(array2, array1) );
array1 = new double[] { 50.6, 20.6 }; // array2 still null
assertEquals( false, NumberUtils.equals(array1, array2) );
assertEquals( false, NumberUtils.equals(array2, array1) );
// test same reference equivalence
array2 = array1;
assertEquals( true, NumberUtils.equals(array1, array2) );
// test object equivalence
array2 = new double[] { 50.6, 20.6 };
assertEquals( true, NumberUtils.equals(array1, array2) );
// test symmetry is not equivalent
array2 = new double[] { 20.6, 50.6 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test the whole length of rhs is tested against
array2 = new double[] { 50.6, 20.6, 10.6 };
assertEquals( false, NumberUtils.equals(array1, array2) );
// test whole length of lhs is tested against
array2 = new double[] { 50.6 };
assertEquals( false, NumberUtils.equals(array1, array2) );
}
// 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);
}
public void testCompareDouble() {
assertTrue(NumberUtils.compare(Double.NaN, Double.NaN) == 0);
assertTrue(NumberUtils.compare(Double.NaN, Double.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.NaN, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.NaN, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, 0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -0.0d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -1.2d) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2d, 1.2d) == 0);
assertTrue(NumberUtils.compare(1.2d, 0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -0.0d) == +1);
assertTrue(NumberUtils.compare(1.2d, -1.2d) == +1);
assertTrue(NumberUtils.compare(1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(0.0d, 0.0d) == 0);
assertTrue(NumberUtils.compare(0.0d, -0.0d) == +1);
assertTrue(NumberUtils.compare(0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-0.0d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-0.0d, -0.0d) == 0);
assertTrue(NumberUtils.compare(-0.0d, -1.2d) == +1);
assertTrue(NumberUtils.compare(-0.0d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2d, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2d, 1.2d) == -1);
assertTrue(NumberUtils.compare(-1.2d, 0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -0.0d) == -1);
assertTrue(NumberUtils.compare(-1.2d, -1.2d) == 0);
assertTrue(NumberUtils.compare(-1.2d, -Double.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2d, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NaN) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, 0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -0.0d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -1.2d) == -1);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, -Double.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Double.MAX_VALUE, Double.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NaN) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, 0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -0.0d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -1.2d) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, -Double.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY) == 0);
}
public void testCompareFloat() {
assertTrue(NumberUtils.compare(Float.NaN, Float.NaN) == 0);
assertTrue(NumberUtils.compare(Float.NaN, Float.POSITIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.NaN, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.NaN, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, 0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -0.0f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -1.2f) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(1.2f, 1.2f) == 0);
assertTrue(NumberUtils.compare(1.2f, 0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -0.0f) == +1);
assertTrue(NumberUtils.compare(1.2f, -1.2f) == +1);
assertTrue(NumberUtils.compare(1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(0.0f, 0.0f) == 0);
assertTrue(NumberUtils.compare(0.0f, -0.0f) == +1);
assertTrue(NumberUtils.compare(0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-0.0f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-0.0f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-0.0f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-0.0f, -0.0f) == 0);
assertTrue(NumberUtils.compare(-0.0f, -1.2f) == +1);
assertTrue(NumberUtils.compare(-0.0f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-0.0f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-1.2f, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-1.2f, 1.2f) == -1);
assertTrue(NumberUtils.compare(-1.2f, 0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -0.0f) == -1);
assertTrue(NumberUtils.compare(-1.2f, -1.2f) == 0);
assertTrue(NumberUtils.compare(-1.2f, -Float.MAX_VALUE) == +1);
assertTrue(NumberUtils.compare(-1.2f, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NaN) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, 0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -0.0f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -1.2f) == -1);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, -Float.MAX_VALUE) == 0);
assertTrue(NumberUtils.compare(-Float.MAX_VALUE, Float.NEGATIVE_INFINITY) == +1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.NaN) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, 0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -0.0f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -1.2f) == -1);
assertTrue(NumberUtils.compare(Float.NEGATIVE_INFINITY, -Float.MAX_VALUE) == -1);
assertTrue(NumberUtils.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));
}
private boolean checkCreateNumber(String val) {
try {
Object obj = NumberUtils.createNumber(val);
if (obj == null) {
return false;
}
return true;
} catch (NumberFormatException e) {
return false;
}
}
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");
}
} |
||
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
} | org.apache.commons.compress.archivers.tar.TarArchiveInputStreamTest::testCompress197 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | 137 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | testCompress197 | /*
* 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.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.compress.utils.CharsetNames;
import org.junit.Test;
public class TarArchiveInputStreamTest {
@Test
public void readSimplePaxHeader() throws Exception {
final TarArchiveInputStream tais = new TarArchiveInputStream(null);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
@Test
public void readPaxHeaderWithEmbeddedNewline() throws Exception {
final TarArchiveInputStream tais = new TarArchiveInputStream(null);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("line1\nline2\nand3", headers.get("comment"));
tais.close();
}
@Test
public void readNonAsciiPaxHeader() throws Exception {
String ae = "\u00e4";
String line = "11 path="+ ae + "\n";
assertEquals(11, line.getBytes(CharsetNames.UTF_8).length);
final TarArchiveInputStream tais = new TarArchiveInputStream(null);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals(ae, headers.get("path"));
tais.close();
}
@Test
public void workaroundForBrokenTimeHeader() throws Exception {
URL tar = getClass().getResource("/simple-aix-native-tar.tar");
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(new File(new URI(tar.toString()))));
TarArchiveEntry tae = in.getNextTarEntry();
tae = in.getNextTarEntry();
assertEquals("sample/link-to-txt-file.lnk", tae.getName());
assertEquals(new Date(0), tae.getLastModifiedDate());
assertTrue(tae.isSymbolicLink());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void datePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("/preepoch-star.tar");
}
@Test
public void datePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("/preepoch-posix.tar");
}
private void datePriorToEpoch(String archive) throws Exception {
URL tar = getClass().getResource(archive);
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(new File(new URI(tar.toString()))));
TarArchiveEntry tae = in.getNextTarEntry();
assertEquals("foo", tae.getName());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1969, 11, 31, 23, 59, 59);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(cal.getTime(), tae.getLastModifiedDate());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
}
private TarArchiveInputStream getTestStream(String name) {
return new TarArchiveInputStream(
TarArchiveInputStreamTest.class.getResourceAsStream(name));
}
} | // You are a professional Java test case writer, please create a test case named `testCompress197` for the issue `Compress-COMPRESS-197`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-197
//
// ## Issue-Title:
// Tar file for Android backup cannot be read
//
// ## Issue-Description:
//
// Attached tar file was generated by some kind of backup tool on Android. Normal tar utilities seem to handle it fine, but Commons Compress doesn't.
//
//
//
//
// ```
// java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '01750{NUL}{NUL}{NUL}' len=8
// at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:99)
// at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:788)
// at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:308)
//
// ```
//
//
//
//
//
@Test
public void testCompress197() throws Exception {
| 137 | 17 | 124 | src/test/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStreamTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-197
## Issue-Title:
Tar file for Android backup cannot be read
## Issue-Description:
Attached tar file was generated by some kind of backup tool on Android. Normal tar utilities seem to handle it fine, but Commons Compress doesn't.
```
java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '01750{NUL}{NUL}{NUL}' len=8
at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:99)
at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:788)
at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:308)
```
```
You are a professional Java test case writer, please create a test case named `testCompress197` for the issue `Compress-COMPRESS-197`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testCompress197() throws Exception {
```
| 124 | [
"org.apache.commons.compress.archivers.tar.TarUtils"
] | 64a62aac9d236dd040053cfee153fca20409adfb4829044f2aaef09517ea8129 | @Test
public void testCompress197() throws Exception | // You are a professional Java test case writer, please create a test case named `testCompress197` for the issue `Compress-COMPRESS-197`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-197
//
// ## Issue-Title:
// Tar file for Android backup cannot be read
//
// ## Issue-Description:
//
// Attached tar file was generated by some kind of backup tool on Android. Normal tar utilities seem to handle it fine, but Commons Compress doesn't.
//
//
//
//
// ```
// java.lang.IllegalArgumentException: Invalid byte 0 at offset 5 in '01750{NUL}{NUL}{NUL}' len=8
// at org.apache.commons.compress.archivers.tar.TarUtils.parseOctal(TarUtils.java:99)
// at org.apache.commons.compress.archivers.tar.TarArchiveEntry.parseTarHeader(TarArchiveEntry.java:788)
// at org.apache.commons.compress.archivers.tar.TarArchiveEntry.<init>(TarArchiveEntry.java:308)
//
// ```
//
//
//
//
//
| 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.assertTrue;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.compress.utils.CharsetNames;
import org.junit.Test;
public class TarArchiveInputStreamTest {
@Test
public void readSimplePaxHeader() throws Exception {
final TarArchiveInputStream tais = new TarArchiveInputStream(null);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
@Test
public void readPaxHeaderWithEmbeddedNewline() throws Exception {
final TarArchiveInputStream tais = new TarArchiveInputStream(null);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("28 comment=line1\nline2\nand3\n"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("line1\nline2\nand3", headers.get("comment"));
tais.close();
}
@Test
public void readNonAsciiPaxHeader() throws Exception {
String ae = "\u00e4";
String line = "11 path="+ ae + "\n";
assertEquals(11, line.getBytes(CharsetNames.UTF_8).length);
final TarArchiveInputStream tais = new TarArchiveInputStream(null);
Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream(line.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals(ae, headers.get("path"));
tais.close();
}
@Test
public void workaroundForBrokenTimeHeader() throws Exception {
URL tar = getClass().getResource("/simple-aix-native-tar.tar");
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(new File(new URI(tar.toString()))));
TarArchiveEntry tae = in.getNextTarEntry();
tae = in.getNextTarEntry();
assertEquals("sample/link-to-txt-file.lnk", tae.getName());
assertEquals(new Date(0), tae.getLastModifiedDate());
assertTrue(tae.isSymbolicLink());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void datePriorToEpochInGNUFormat() throws Exception {
datePriorToEpoch("/preepoch-star.tar");
}
@Test
public void datePriorToEpochInPAXFormat() throws Exception {
datePriorToEpoch("/preepoch-posix.tar");
}
private void datePriorToEpoch(String archive) throws Exception {
URL tar = getClass().getResource(archive);
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new FileInputStream(new File(new URI(tar.toString()))));
TarArchiveEntry tae = in.getNextTarEntry();
assertEquals("foo", tae.getName());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.set(1969, 11, 31, 23, 59, 59);
cal.set(Calendar.MILLISECOND, 0);
assertEquals(cal.getTime(), tae.getLastModifiedDate());
assertTrue(tae.isCheckSumOK());
} finally {
if (in != null) {
in.close();
}
}
}
@Test
public void testCompress197() throws Exception {
TarArchiveInputStream tar = getTestStream("/COMPRESS-197.tar");
try {
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
entry = tar.getNextTarEntry();
}
} catch (IOException e) {
fail("COMPRESS-197: " + e.getMessage());
} finally {
tar.close();
}
}
private TarArchiveInputStream getTestStream(String name) {
return new TarArchiveInputStream(
TarArchiveInputStreamTest.class.getResourceAsStream(name));
}
} |
||
public void testLang315() {
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(200);} catch (InterruptedException ex) {}
watch.suspend();
long suspendTime = watch.getTime();
try {Thread.sleep(200);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertTrue( suspendTime == totalTime );
} | org.apache.commons.lang.time.StopWatchTest::testLang315 | src/test/org/apache/commons/lang/time/StopWatchTest.java | 120 | src/test/org/apache/commons/lang/time/StopWatchTest.java | testLang315 | /*
* 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.time;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* TestCase for StopWatch.
*
* @author Stephen Colebourne
* @version $Id$
*/
public class StopWatchTest extends TestCase {
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(StopWatchTest.class);
suite.setName("StopWatch Tests");
return suite;
}
public StopWatchTest(String s) {
super(s);
}
//-----------------------------------------------------------------------
public void testStopWatchSimple(){
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.stop();
long time = watch.getTime();
assertEquals(time, watch.getTime());
assertTrue(time >= 500);
assertTrue(time < 700);
watch.reset();
assertEquals(0, watch.getTime());
}
public void testStopWatchSimpleGet(){
StopWatch watch = new StopWatch();
assertEquals(0, watch.getTime());
assertEquals("0:00:00.000", watch.toString());
watch.start();
try {Thread.sleep(500);} catch (InterruptedException ex) {}
assertTrue(watch.getTime() < 2000);
}
public void testStopWatchSplit(){
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.split();
long splitTime = watch.getSplitTime();
String splitStr = watch.toSplitString();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.unsplit();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertEquals("Formatted split string not the correct length",
splitStr.length(), 11);
assertTrue(splitTime >= 500);
assertTrue(splitTime < 700);
assertTrue(totalTime >= 1500);
assertTrue(totalTime < 1900);
}
public void testStopWatchSuspend(){
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.suspend();
long suspendTime = watch.getTime();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.resume();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertTrue(suspendTime >= 500);
assertTrue(suspendTime < 700);
assertTrue(totalTime >= 1000);
assertTrue(totalTime < 1300);
}
public void testLang315() {
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(200);} catch (InterruptedException ex) {}
watch.suspend();
long suspendTime = watch.getTime();
try {Thread.sleep(200);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertTrue( suspendTime == totalTime );
}
// test bad states
public void testBadStates() {
StopWatch watch = new StopWatch();
try {
watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.suspend();
fail("Calling suspend on an unstarted StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.split();
fail("Calling split on a non-running StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
watch.start();
try {
watch.start();
fail("Calling start on a started StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.getSplitTime();
fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
watch.stop();
try {
watch.start();
fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
} catch(IllegalStateException ise) {
// expected
}
}
} | // You are a professional Java test case writer, please create a test case named `testLang315` for the issue `Lang-LANG-315`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-315
//
// ## Issue-Title:
// StopWatch: suspend() acts as split(), if followed by stop()
//
// ## Issue-Description:
//
// In my opinion, it is a bug that suspend() acts as split(), if followed by stop(); see below:
//
//
// StopWatch sw = new StopWatch();
//
//
// sw.start();
//
// Thread.sleep(1000);
//
// sw.suspend();
//
// // Time 1 (ok)
//
// System.out.println(sw.getTime());
//
//
// Thread.sleep(2000);
//
// // Time 1 (again, ok)
//
// System.out.println(sw.getTime());
//
//
// sw.resume();
//
// Thread.sleep(3000);
//
// sw.suspend();
//
// // Time 2 (ok)
//
// System.out.println(sw.getTime());
//
//
// Thread.sleep(4000);
//
// // Time 2 (again, ok)
//
// System.out.println(sw.getTime());
//
//
// Thread.sleep(5000);
//
// sw.stop();
//
// // Time 2 (should be, but is Time 3 => NOT ok)
//
// System.out.println(sw.getTime());
//
//
// suspend/resume is like a pause, where time counter doesn't continue. So a following stop()-call shouldn't increase the time counter, should it?
//
//
//
//
//
public void testLang315() {
| 120 | 55 | 110 | src/test/org/apache/commons/lang/time/StopWatchTest.java | src/test | ```markdown
## Issue-ID: Lang-LANG-315
## Issue-Title:
StopWatch: suspend() acts as split(), if followed by stop()
## Issue-Description:
In my opinion, it is a bug that suspend() acts as split(), if followed by stop(); see below:
StopWatch sw = new StopWatch();
sw.start();
Thread.sleep(1000);
sw.suspend();
// Time 1 (ok)
System.out.println(sw.getTime());
Thread.sleep(2000);
// Time 1 (again, ok)
System.out.println(sw.getTime());
sw.resume();
Thread.sleep(3000);
sw.suspend();
// Time 2 (ok)
System.out.println(sw.getTime());
Thread.sleep(4000);
// Time 2 (again, ok)
System.out.println(sw.getTime());
Thread.sleep(5000);
sw.stop();
// Time 2 (should be, but is Time 3 => NOT ok)
System.out.println(sw.getTime());
suspend/resume is like a pause, where time counter doesn't continue. So a following stop()-call shouldn't increase the time counter, should it?
```
You are a professional Java test case writer, please create a test case named `testLang315` for the issue `Lang-LANG-315`, utilizing the provided issue report information and the following function signature.
```java
public void testLang315() {
```
| 110 | [
"org.apache.commons.lang.time.StopWatch"
] | 6525ebf8bd2a2a51a34d04923ab6f7c884be8447f8faad3efc6e236cb71949ef | public void testLang315() | // You are a professional Java test case writer, please create a test case named `testLang315` for the issue `Lang-LANG-315`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Lang-LANG-315
//
// ## Issue-Title:
// StopWatch: suspend() acts as split(), if followed by stop()
//
// ## Issue-Description:
//
// In my opinion, it is a bug that suspend() acts as split(), if followed by stop(); see below:
//
//
// StopWatch sw = new StopWatch();
//
//
// sw.start();
//
// Thread.sleep(1000);
//
// sw.suspend();
//
// // Time 1 (ok)
//
// System.out.println(sw.getTime());
//
//
// Thread.sleep(2000);
//
// // Time 1 (again, ok)
//
// System.out.println(sw.getTime());
//
//
// sw.resume();
//
// Thread.sleep(3000);
//
// sw.suspend();
//
// // Time 2 (ok)
//
// System.out.println(sw.getTime());
//
//
// Thread.sleep(4000);
//
// // Time 2 (again, ok)
//
// System.out.println(sw.getTime());
//
//
// Thread.sleep(5000);
//
// sw.stop();
//
// // Time 2 (should be, but is Time 3 => NOT ok)
//
// System.out.println(sw.getTime());
//
//
// suspend/resume is like a pause, where time counter doesn't continue. So a following stop()-call shouldn't increase the time counter, should it?
//
//
//
//
//
| 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.time;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
/**
* TestCase for StopWatch.
*
* @author Stephen Colebourne
* @version $Id$
*/
public class StopWatchTest extends TestCase {
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(StopWatchTest.class);
suite.setName("StopWatch Tests");
return suite;
}
public StopWatchTest(String s) {
super(s);
}
//-----------------------------------------------------------------------
public void testStopWatchSimple(){
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.stop();
long time = watch.getTime();
assertEquals(time, watch.getTime());
assertTrue(time >= 500);
assertTrue(time < 700);
watch.reset();
assertEquals(0, watch.getTime());
}
public void testStopWatchSimpleGet(){
StopWatch watch = new StopWatch();
assertEquals(0, watch.getTime());
assertEquals("0:00:00.000", watch.toString());
watch.start();
try {Thread.sleep(500);} catch (InterruptedException ex) {}
assertTrue(watch.getTime() < 2000);
}
public void testStopWatchSplit(){
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.split();
long splitTime = watch.getSplitTime();
String splitStr = watch.toSplitString();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.unsplit();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertEquals("Formatted split string not the correct length",
splitStr.length(), 11);
assertTrue(splitTime >= 500);
assertTrue(splitTime < 700);
assertTrue(totalTime >= 1500);
assertTrue(totalTime < 1900);
}
public void testStopWatchSuspend(){
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.suspend();
long suspendTime = watch.getTime();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.resume();
try {Thread.sleep(550);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertTrue(suspendTime >= 500);
assertTrue(suspendTime < 700);
assertTrue(totalTime >= 1000);
assertTrue(totalTime < 1300);
}
public void testLang315() {
StopWatch watch = new StopWatch();
watch.start();
try {Thread.sleep(200);} catch (InterruptedException ex) {}
watch.suspend();
long suspendTime = watch.getTime();
try {Thread.sleep(200);} catch (InterruptedException ex) {}
watch.stop();
long totalTime = watch.getTime();
assertTrue( suspendTime == totalTime );
}
// test bad states
public void testBadStates() {
StopWatch watch = new StopWatch();
try {
watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.suspend();
fail("Calling suspend on an unstarted StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.split();
fail("Calling split on a non-running StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
watch.start();
try {
watch.start();
fail("Calling start on a started StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.getSplitTime();
fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
try {
watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch(IllegalStateException ise) {
// expected
}
watch.stop();
try {
watch.start();
fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
} catch(IllegalStateException ise) {
// expected
}
}
} |
||
public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/apache-maven-2.2.1.zip.001");
FileInputStream archive = new FileInputStream(
new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive,null,false);
// these are the entries that are supposed to be processed
// correctly without any problems
for (int i = 0; i < ENTRIES.length; i++) {
assertEquals(ENTRIES[i], zi.getNextEntry().getName());
}
// this is the last entry that is truncated
ArchiveEntry lastEntry = zi.getNextEntry();
assertEquals(LAST_ENTRY_NAME, lastEntry.getName());
byte [] buffer = new byte [4096];
// before the fix, we'd get 0 bytes on this read and all
// subsequent reads thus a client application might enter
// an infinite loop after the fix, we should get an
// exception
try {
int read = 0;
while ((read = zi.read(buffer)) > 0) { }
fail("shouldn't be able to read from truncated entry");
} catch (IOException e) {
assertEquals("Truncated ZIP file", e.getMessage());
}
// and now we get another entry, which should also yield
// an exception
try {
zi.getNextEntry();
fail("shouldn't be able to read another entry from truncated"
+ " file");
} catch (IOException e) {
// this is to be expected
}
} finally {
if (zi != null) {
zi.close();
}
}
} | org.apache.commons.compress.archivers.zip.Maven221MultiVolumeTest::testRead7ZipMultiVolumeArchiveForStream | src/test/java/org/apache/commons/compress/archivers/zip/Maven221MultiVolumeTest.java | 115 | src/test/java/org/apache/commons/compress/archivers/zip/Maven221MultiVolumeTest.java | testRead7ZipMultiVolumeArchiveForStream | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.commons.compress.archivers.ArchiveEntry;
import junit.framework.TestCase;
/**
* JUnit 3 testcase for a multi-volume zip file.
*
* Some tools (like 7-zip) allow users to split a large archives into 'volumes'
* with a given size to fit them into multiple cds, usb drives, or emails with
* an attachment size limit. It's basically the same file split into chunks of
* exactly 65536 bytes length. Concatenating volumes yields exactly the original
* file. There is no mechanism in the ZIP algorithm to accommodate for this.
* Before commons-compress used to enter an infinite loop on the last entry for
* such a file. This test is intended to prove that this error doesn't occur
* anymore. All entries but the last one are returned correctly, the last entry
* yields an exception.
*
*/
public class Maven221MultiVolumeTest extends TestCase {
private static final String [] ENTRIES = new String [] {
"apache-maven-2.2.1/",
"apache-maven-2.2.1/LICENSE.txt",
"apache-maven-2.2.1/NOTICE.txt",
"apache-maven-2.2.1/README.txt",
"apache-maven-2.2.1/bin/",
"apache-maven-2.2.1/bin/m2.conf",
"apache-maven-2.2.1/bin/mvn",
"apache-maven-2.2.1/bin/mvn.bat",
"apache-maven-2.2.1/bin/mvnDebug",
"apache-maven-2.2.1/bin/mvnDebug.bat",
"apache-maven-2.2.1/boot/",
"apache-maven-2.2.1/boot/classworlds-1.1.jar",
"apache-maven-2.2.1/conf/",
"apache-maven-2.2.1/conf/settings.xml",
"apache-maven-2.2.1/lib/"
};
private static final String LAST_ENTRY_NAME =
"apache-maven-2.2.1/lib/maven-2.2.1-uber.jar";
public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/apache-maven-2.2.1.zip.001");
FileInputStream archive = new FileInputStream(
new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive,null,false);
// these are the entries that are supposed to be processed
// correctly without any problems
for (int i = 0; i < ENTRIES.length; i++) {
assertEquals(ENTRIES[i], zi.getNextEntry().getName());
}
// this is the last entry that is truncated
ArchiveEntry lastEntry = zi.getNextEntry();
assertEquals(LAST_ENTRY_NAME, lastEntry.getName());
byte [] buffer = new byte [4096];
// before the fix, we'd get 0 bytes on this read and all
// subsequent reads thus a client application might enter
// an infinite loop after the fix, we should get an
// exception
try {
int read = 0;
while ((read = zi.read(buffer)) > 0) { }
fail("shouldn't be able to read from truncated entry");
} catch (IOException e) {
assertEquals("Truncated ZIP file", e.getMessage());
}
// and now we get another entry, which should also yield
// an exception
try {
zi.getNextEntry();
fail("shouldn't be able to read another entry from truncated"
+ " file");
} catch (IOException e) {
// this is to be expected
}
} finally {
if (zi != null) {
zi.close();
}
}
}
public void testRead7ZipMultiVolumeArchiveForFile()
throws IOException, URISyntaxException {
URL zip = getClass().getResource("/apache-maven-2.2.1.zip.001");
File file = new File(new URI(zip.toString()));
try {
new ZipFile(file);
fail("Expected ZipFile to fail");
} catch (IOException ex) {
// expected
}
}
} | // You are a professional Java test case writer, please create a test case named `testRead7ZipMultiVolumeArchiveForStream` for the issue `Compress-COMPRESS-87`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-87
//
// ## Issue-Title:
// ZipArchiveInputStream doesn't report the end of a truncated archive
//
// ## Issue-Description:
//
// If a Zip archive is truncated, (e.g. because it is the first volume in a multi-volume archive) the ZipArchiveInputStream.read() method will not detect that fact. All calls to read() will return 0 bytes read. They will not return -1 (end of stream), nor will they throw any exception (which would seem like a good idea to me because the archive is truncated).
//
//
// I have tracked this problem to ZipArchiveInputStream.java, line 239. It contains a check
//
//
// if (read == 0 && inf.finished()) {
//
// return -1;
//
// }
//
//
// For truncated archives the read is always zero but the inf is never finished(). I suggest adding two lines below:
//
//
// if (read == 0 && inf.finished()) {
//
// return -1;
//
// } else if (read == 0 && lengthOfLastRead == -1) {
//
// throw new IOException("Truncated ZIP file");
//
// }
//
//
// This solves the problem in my tests.
//
//
//
//
//
public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
URISyntaxException {
| 115 | 5 | 68 | src/test/java/org/apache/commons/compress/archivers/zip/Maven221MultiVolumeTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-87
## Issue-Title:
ZipArchiveInputStream doesn't report the end of a truncated archive
## Issue-Description:
If a Zip archive is truncated, (e.g. because it is the first volume in a multi-volume archive) the ZipArchiveInputStream.read() method will not detect that fact. All calls to read() will return 0 bytes read. They will not return -1 (end of stream), nor will they throw any exception (which would seem like a good idea to me because the archive is truncated).
I have tracked this problem to ZipArchiveInputStream.java, line 239. It contains a check
if (read == 0 && inf.finished()) {
return -1;
}
For truncated archives the read is always zero but the inf is never finished(). I suggest adding two lines below:
if (read == 0 && inf.finished()) {
return -1;
} else if (read == 0 && lengthOfLastRead == -1) {
throw new IOException("Truncated ZIP file");
}
This solves the problem in my tests.
```
You are a professional Java test case writer, please create a test case named `testRead7ZipMultiVolumeArchiveForStream` for the issue `Compress-COMPRESS-87`, utilizing the provided issue report information and the following function signature.
```java
public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
URISyntaxException {
```
| 68 | [
"org.apache.commons.compress.archivers.zip.ZipArchiveInputStream"
] | 65af9a4eb58087e10916f21293938615fdd2bda78e1942b99969605d51537726 | public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
URISyntaxException | // You are a professional Java test case writer, please create a test case named `testRead7ZipMultiVolumeArchiveForStream` for the issue `Compress-COMPRESS-87`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-87
//
// ## Issue-Title:
// ZipArchiveInputStream doesn't report the end of a truncated archive
//
// ## Issue-Description:
//
// If a Zip archive is truncated, (e.g. because it is the first volume in a multi-volume archive) the ZipArchiveInputStream.read() method will not detect that fact. All calls to read() will return 0 bytes read. They will not return -1 (end of stream), nor will they throw any exception (which would seem like a good idea to me because the archive is truncated).
//
//
// I have tracked this problem to ZipArchiveInputStream.java, line 239. It contains a check
//
//
// if (read == 0 && inf.finished()) {
//
// return -1;
//
// }
//
//
// For truncated archives the read is always zero but the inf is never finished(). I suggest adding two lines below:
//
//
// if (read == 0 && inf.finished()) {
//
// return -1;
//
// } else if (read == 0 && lengthOfLastRead == -1) {
//
// throw new IOException("Truncated ZIP file");
//
// }
//
//
// This solves the problem in my tests.
//
//
//
//
//
| Compress | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.commons.compress.archivers.ArchiveEntry;
import junit.framework.TestCase;
/**
* JUnit 3 testcase for a multi-volume zip file.
*
* Some tools (like 7-zip) allow users to split a large archives into 'volumes'
* with a given size to fit them into multiple cds, usb drives, or emails with
* an attachment size limit. It's basically the same file split into chunks of
* exactly 65536 bytes length. Concatenating volumes yields exactly the original
* file. There is no mechanism in the ZIP algorithm to accommodate for this.
* Before commons-compress used to enter an infinite loop on the last entry for
* such a file. This test is intended to prove that this error doesn't occur
* anymore. All entries but the last one are returned correctly, the last entry
* yields an exception.
*
*/
public class Maven221MultiVolumeTest extends TestCase {
private static final String [] ENTRIES = new String [] {
"apache-maven-2.2.1/",
"apache-maven-2.2.1/LICENSE.txt",
"apache-maven-2.2.1/NOTICE.txt",
"apache-maven-2.2.1/README.txt",
"apache-maven-2.2.1/bin/",
"apache-maven-2.2.1/bin/m2.conf",
"apache-maven-2.2.1/bin/mvn",
"apache-maven-2.2.1/bin/mvn.bat",
"apache-maven-2.2.1/bin/mvnDebug",
"apache-maven-2.2.1/bin/mvnDebug.bat",
"apache-maven-2.2.1/boot/",
"apache-maven-2.2.1/boot/classworlds-1.1.jar",
"apache-maven-2.2.1/conf/",
"apache-maven-2.2.1/conf/settings.xml",
"apache-maven-2.2.1/lib/"
};
private static final String LAST_ENTRY_NAME =
"apache-maven-2.2.1/lib/maven-2.2.1-uber.jar";
public void testRead7ZipMultiVolumeArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/apache-maven-2.2.1.zip.001");
FileInputStream archive = new FileInputStream(
new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive,null,false);
// these are the entries that are supposed to be processed
// correctly without any problems
for (int i = 0; i < ENTRIES.length; i++) {
assertEquals(ENTRIES[i], zi.getNextEntry().getName());
}
// this is the last entry that is truncated
ArchiveEntry lastEntry = zi.getNextEntry();
assertEquals(LAST_ENTRY_NAME, lastEntry.getName());
byte [] buffer = new byte [4096];
// before the fix, we'd get 0 bytes on this read and all
// subsequent reads thus a client application might enter
// an infinite loop after the fix, we should get an
// exception
try {
int read = 0;
while ((read = zi.read(buffer)) > 0) { }
fail("shouldn't be able to read from truncated entry");
} catch (IOException e) {
assertEquals("Truncated ZIP file", e.getMessage());
}
// and now we get another entry, which should also yield
// an exception
try {
zi.getNextEntry();
fail("shouldn't be able to read another entry from truncated"
+ " file");
} catch (IOException e) {
// this is to be expected
}
} finally {
if (zi != null) {
zi.close();
}
}
}
public void testRead7ZipMultiVolumeArchiveForFile()
throws IOException, URISyntaxException {
URL zip = getClass().getResource("/apache-maven-2.2.1.zip.001");
File file = new File(new URI(zip.toString()));
try {
new ZipFile(file);
fail("Expected ZipFile to fail");
} catch (IOException ex) {
// expected
}
}
} |
||
public void testISO8601MissingSeconds() throws Exception
{
String inputStr;
Date inputDate;
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
inputStr = "1997-07-16T19:20+01:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1997, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(16, c.get(Calendar.DAY_OF_MONTH));
assertEquals(19 - 1, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
} | com.fasterxml.jackson.databind.deser.TestDateDeserialization::testISO8601MissingSeconds | src/test/java/com/fasterxml/jackson/databind/deser/TestDateDeserialization.java | 200 | src/test/java/com/fasterxml/jackson/databind/deser/TestDateDeserialization.java | testISO8601MissingSeconds | package com.fasterxml.jackson.databind.deser;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
public class TestDateDeserialization
extends BaseMapTest
{
// Test for [JACKSON-435]
static class DateAsStringBean
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="/yyyy/MM/dd/")
public Date date;
}
static class DateAsStringBeanGermany
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="/yyyy/MM/dd/", locale="fr_FR")
public Date date;
}
static class CalendarAsStringBean
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern=";yyyy/MM/dd;")
public Calendar cal;
}
static class DateInCETBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH", timezone="CET")
public Date date;
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDateUtil() throws Exception
{
long now = 123456789L;
java.util.Date value = new java.util.Date(now);
// First from long
assertEquals(value, MAPPER.readValue(""+now, java.util.Date.class));
// then from String
String dateStr = dateToString(value);
java.util.Date result = MAPPER.readValue("\""+dateStr+"\"", java.util.Date.class);
assertEquals("Date: expect "+value+" ("+value.getTime()+"), got "+result+" ("+result.getTime()+")",
value.getTime(), result.getTime());
}
public void testDateUtilWithStringTimestamp() throws Exception
{
long now = 1321992375446L;
/* As of 1.5.0, should be ok to pass as JSON String, as long
* as it is plain timestamp (all numbers, 64-bit)
*/
String json = quote(String.valueOf(now));
java.util.Date value = MAPPER.readValue(json, java.util.Date.class);
assertEquals(now, value.getTime());
// #267: should handle negative timestamps too; like 12 hours before 1.1.1970
long before = - (24 * 3600 * 1000L);
json = quote(String.valueOf(before));
value = MAPPER.readValue(json, java.util.Date.class);
assertEquals(before, value.getTime());
}
public void testDateUtilRFC1123() throws Exception
{
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
// let's use an arbitrary value...
String inputStr = "Sat, 17 Jan 2009 06:13:58 +0000";
java.util.Date inputDate = fmt.parse(inputStr);
assertEquals(inputDate, MAPPER.readValue("\""+inputStr+"\"", java.util.Date.class));
}
public void testDateUtilRFC1123OnNonUSLocales() throws Exception
{
Locale old = Locale.getDefault();
Locale.setDefault(Locale.GERMAN);
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
// let's use an arbitrary value...
String inputStr = "Sat, 17 Jan 2009 06:13:58 +0000";
java.util.Date inputDate = fmt.parse(inputStr);
assertEquals(inputDate, MAPPER.readValue("\""+inputStr+"\"", java.util.Date.class));
Locale.setDefault(old);
}
/**
* ISO8601 is supported as well
*/
public void testDateUtilISO8601() throws Exception
{
/* let's use simple baseline value, arbitrary date in GMT,
* using the standard notation
*/
String inputStr = "1972-12-28T00:00:00.000+0000";
Date inputDate = MAPPER.readValue("\""+inputStr+"\"", java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
// And then the same, but using 'Z' as alias for +0000 (very common)
inputStr = "1972-12-28T00:00:00.000Z";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
// Same but using colon in timezone
inputStr = "1972-12-28T00:00:00.000+00:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
// Same but only passing hour difference as timezone
inputStr = "1972-12-28T00:00:00.000+00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
inputStr = "1984-11-30T00:00:00.000Z";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1984, c.get(Calendar.YEAR));
assertEquals(Calendar.NOVEMBER, c.get(Calendar.MONTH));
assertEquals(30, c.get(Calendar.DAY_OF_MONTH));
}
// [Databind#570]
public void testISO8601PartialMilliseconds() throws Exception
{
String inputStr;
Date inputDate;
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
inputStr = "2014-10-03T18:00:00.6-05:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(2014, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(3, c.get(Calendar.DAY_OF_MONTH));
assertEquals(600, c.get(Calendar.MILLISECOND));
inputStr = "2014-10-03T18:00:00.61-05:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(2014, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(3, c.get(Calendar.DAY_OF_MONTH));
assertEquals(18 + 5, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.MINUTE));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(610, c.get(Calendar.MILLISECOND));
inputStr = "1997-07-16T19:20:30.45+01:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1997, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(16, c.get(Calendar.DAY_OF_MONTH));
assertEquals(19 - 1, c.get(Calendar.HOUR_OF_DAY));
assertEquals(20, c.get(Calendar.MINUTE));
assertEquals(30, c.get(Calendar.SECOND));
assertEquals(450, c.get(Calendar.MILLISECOND));
}
public void testISO8601MissingSeconds() throws Exception
{
String inputStr;
Date inputDate;
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
inputStr = "1997-07-16T19:20+01:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1997, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(16, c.get(Calendar.DAY_OF_MONTH));
assertEquals(19 - 1, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
}
public void testDateUtilISO8601NoTimezone() throws Exception
{
// Timezone itself is optional as well...
String inputStr = "1984-11-13T00:00:09";
Date inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(1984, c.get(Calendar.YEAR));
assertEquals(Calendar.NOVEMBER, c.get(Calendar.MONTH));
assertEquals(13, c.get(Calendar.DAY_OF_MONTH));
assertEquals(0, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.MINUTE));
assertEquals(9, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
}
// [Issue#338]
public void testDateUtilISO8601NoMilliseconds() throws Exception
{
final String INPUT_STR = "2013-10-31T17:27:00";
Date inputDate;
Calendar c;
inputDate = MAPPER.readValue(quote(INPUT_STR), java.util.Date.class);
c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(2013, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(31, c.get(Calendar.DAY_OF_MONTH));
assertEquals(17, c.get(Calendar.HOUR_OF_DAY));
assertEquals(27, c.get(Calendar.MINUTE));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
// 03-Nov-2013, tatu: This wouldn't work, and is the nominal reason
// for #338 I think
/*
inputDate = ISO8601Utils.parse(INPUT_STR);
c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(2013, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(31, c.get(Calendar.DAY_OF_MONTH));
assertEquals(17, c.get(Calendar.HOUR_OF_DAY));
assertEquals(27, c.get(Calendar.MINUTE));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
*/
}
public void testDateUtilISO8601JustDate() throws Exception
{
// Plain date (no time)
String inputStr = "1972-12-28";
Date inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
}
@SuppressWarnings("deprecation")
public void testDateSql() throws Exception
{
java.sql.Date value = new java.sql.Date(0L);
value.setYear(99); // 1999
value.setDate(19);
value.setMonth(Calendar.APRIL);
long now = value.getTime();
// First from long
assertEquals(value, MAPPER.readValue(String.valueOf(now), java.sql.Date.class));
// then from default java.sql.Date String serialization:
java.sql.Date result = MAPPER.readValue(quote(value.toString()), java.sql.Date.class);
Calendar c = gmtCalendar(result.getTime());
assertEquals(1999, c.get(Calendar.YEAR));
assertEquals(Calendar.APRIL, c.get(Calendar.MONTH));
assertEquals(19, c.get(Calendar.DAY_OF_MONTH));
/* [JACKSON-200]: looks like we better add support for regular date
* formats as well
*/
String expStr = "1981-07-13";
result = MAPPER.readValue(quote(expStr), java.sql.Date.class);
c.setTimeInMillis(result.getTime());
assertEquals(1981, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(13, c.get(Calendar.DAY_OF_MONTH));
/* 20-Nov-2009, tatus: I'll be damned if I understand why string serialization
* is off-by-one, but day-of-month does seem to be one less. My guess is
* that something is funky with timezones (i.e. somewhere local TZ is
* being used), but just can't resolve it. Hence, need to comment this:
*/
// assertEquals(expStr, result.toString());
}
public void testCalendar() throws Exception
{
// not ideal, to use (ever-changing) current date, but...
java.util.Calendar value = Calendar.getInstance();
long l = 12345678L;
value.setTimeInMillis(l);
// First from long
Calendar result = MAPPER.readValue(""+l, Calendar.class);
assertEquals(l, result.getTimeInMillis());
// Then from serialized String
String dateStr = dateToString(new Date(l));
result = MAPPER.readValue(quote(dateStr), Calendar.class);
// note: representation may differ (wrt timezone etc), but underlying value must remain the same:
assertEquals(l, result.getTimeInMillis());
}
public void testCustom() throws Exception
{
final ObjectMapper mapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
mapper.setDateFormat(df);
String dateStr = "1972-12-28X15:45:00";
java.util.Date exp = df.parse(dateStr);
java.util.Date result = mapper.readValue("\""+dateStr+"\"", java.util.Date.class);
assertEquals(exp, result);
}
/**
* Test for [JACKSON-203]: make empty Strings deserialize as nulls by default,
* without need to turn on feature (which may be added in future)
*/
public void testDatesWithEmptyStrings() throws Exception
{
assertNull(MAPPER.readValue(quote(""), java.util.Date.class));
assertNull(MAPPER.readValue(quote(""), java.util.Calendar.class));
assertNull(MAPPER.readValue(quote(""), java.sql.Date.class));
}
// for [JACKSON-334]
public void test8601DateTimeNoMilliSecs() throws Exception
{
// ok, Zebra, no milliseconds
for (String inputStr : new String[] {
"2010-06-28T23:34:22Z",
"2010-06-28T23:34:22+0000",
"2010-06-28T23:34:22+00",
}) {
Date inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(2010, c.get(Calendar.YEAR));
assertEquals(Calendar.JUNE, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
assertEquals(23, c.get(Calendar.HOUR_OF_DAY));
assertEquals(34, c.get(Calendar.MINUTE));
assertEquals(22, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
}
}
public void testTimeZone() throws Exception
{
TimeZone result = MAPPER.readValue(quote("PST"), TimeZone.class);
assertEquals("PST", result.getID());
}
public void testCustomDateWithAnnotation() throws Exception
{
final String INPUT = "{\"date\":\"/2005/05/25/\"}";
DateAsStringBean result = MAPPER.readValue(INPUT, DateAsStringBean.class);
assertNotNull(result);
assertNotNull(result.date);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long l = result.date.getTime();
if (l == 0L) {
fail("Should not get null date");
}
c.setTimeInMillis(l);
assertEquals(2005, c.get(Calendar.YEAR));
assertEquals(Calendar.MAY, c.get(Calendar.MONTH));
assertEquals(25, c.get(Calendar.DAY_OF_MONTH));
// 27-Mar-2014, tatu: Let's verify that changing Locale won't break it;
// either via context Locale
result = MAPPER.reader(DateAsStringBean.class)
.with(Locale.GERMANY)
.readValue(INPUT);
assertNotNull(result);
assertNotNull(result.date);
l = result.date.getTime();
if (l == 0L) {
fail("Should not get null date");
}
c.setTimeInMillis(l);
assertEquals(2005, c.get(Calendar.YEAR));
assertEquals(Calendar.MAY, c.get(Calendar.MONTH));
assertEquals(25, c.get(Calendar.DAY_OF_MONTH));
// or, via annotations
DateAsStringBeanGermany result2 = MAPPER.reader(DateAsStringBeanGermany.class).readValue(INPUT);
assertNotNull(result2);
assertNotNull(result2.date);
l = result2.date.getTime();
if (l == 0L) {
fail("Should not get null date");
}
c.setTimeInMillis(l);
assertEquals(2005, c.get(Calendar.YEAR));
assertEquals(Calendar.MAY, c.get(Calendar.MONTH));
assertEquals(25, c.get(Calendar.DAY_OF_MONTH));
}
public void testCustomCalendarWithAnnotation() throws Exception
{
CalendarAsStringBean cbean = MAPPER.readValue("{\"cal\":\";2007/07/13;\"}",
CalendarAsStringBean.class);
assertNotNull(cbean);
assertNotNull(cbean.cal);
Calendar c = cbean.cal;
assertEquals(2007, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(13, c.get(Calendar.DAY_OF_MONTH));
}
public void testCustomCalendarWithTimeZone() throws Exception
{
// And then with different TimeZone: CET is +01:00 from GMT -- read as CET
DateInCETBean cet = MAPPER.readValue("{\"date\":\"2001-01-01,10\"}",
DateInCETBean.class);
Calendar c = Calendar.getInstance(getUTCTimeZone());
c.setTimeInMillis(cet.date.getTime());
// so, going to UTC/GMT should reduce hour by one
assertEquals(2001, c.get(Calendar.YEAR));
assertEquals(Calendar.JANUARY, c.get(Calendar.MONTH));
assertEquals(1, c.get(Calendar.DAY_OF_MONTH));
assertEquals(9, c.get(Calendar.HOUR_OF_DAY));
}
/*
/**********************************************************
/* Tests to verify failing cases
/**********************************************************
*/
public void testInvalidFormat() throws Exception
{
try {
MAPPER.readValue(quote("foobar"), Date.class);
fail("Should have failed with an exception");
} catch (InvalidFormatException e) {
verifyException(e, "Can not construct instance");
assertEquals("foobar", e.getValue());
assertEquals(Date.class, e.getTargetType());
} catch (Exception e) {
fail("Wrong type of exception ("+e.getClass().getName()+"), should get "
+InvalidFormatException.class.getName());
}
}
/*
/**********************************************************
/* Helper methods
/**********************************************************
*/
private String dateToString(java.util.Date value)
{
/* Then from String. This is bit tricky, since JDK does not really
* suggest a 'standard' format. So let's try using something...
*/
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return df.format(value);
}
private static Calendar gmtCalendar(long time)
{
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTimeInMillis(time);
return c;
}
} | // You are a professional Java test case writer, please create a test case named `testISO8601MissingSeconds` for the issue `JacksonDatabind-570`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-570
//
// ## Issue-Title:
// Add Support for Parsing All Compliant ISO-8601 Date Formats
//
// ## Issue-Description:
// Some providers create JSON date stamps in ISO-8601 formats that cannot be parsed by the jackson-databind library. Here is a sampling of some valid formats that do not parse correctly:
//
//
// 2014-10-03T18:00:00.6-05:00
//
// 2014-10-03T18:00:00.61-05:00
//
// 1997-07-16T19:20+01:00
//
// 1997-07-16T19:20:30.45+01:00
//
//
// The last two actually come from the ISO-8601 notes on <http://www.w3.org/TR/NOTE-datetime>.
//
//
//
//
public void testISO8601MissingSeconds() throws Exception {
| 200 | 6 | 185 | src/test/java/com/fasterxml/jackson/databind/deser/TestDateDeserialization.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-570
## Issue-Title:
Add Support for Parsing All Compliant ISO-8601 Date Formats
## Issue-Description:
Some providers create JSON date stamps in ISO-8601 formats that cannot be parsed by the jackson-databind library. Here is a sampling of some valid formats that do not parse correctly:
2014-10-03T18:00:00.6-05:00
2014-10-03T18:00:00.61-05:00
1997-07-16T19:20+01:00
1997-07-16T19:20:30.45+01:00
The last two actually come from the ISO-8601 notes on <http://www.w3.org/TR/NOTE-datetime>.
```
You are a professional Java test case writer, please create a test case named `testISO8601MissingSeconds` for the issue `JacksonDatabind-570`, utilizing the provided issue report information and the following function signature.
```java
public void testISO8601MissingSeconds() throws Exception {
```
| 185 | [
"com.fasterxml.jackson.databind.util.StdDateFormat"
] | 65cc4b118b832545c1bb1538870bae82309f1f791a052e8790fda82f82bf92e6 | public void testISO8601MissingSeconds() throws Exception
| // You are a professional Java test case writer, please create a test case named `testISO8601MissingSeconds` for the issue `JacksonDatabind-570`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-570
//
// ## Issue-Title:
// Add Support for Parsing All Compliant ISO-8601 Date Formats
//
// ## Issue-Description:
// Some providers create JSON date stamps in ISO-8601 formats that cannot be parsed by the jackson-databind library. Here is a sampling of some valid formats that do not parse correctly:
//
//
// 2014-10-03T18:00:00.6-05:00
//
// 2014-10-03T18:00:00.61-05:00
//
// 1997-07-16T19:20+01:00
//
// 1997-07-16T19:20:30.45+01:00
//
//
// The last two actually come from the ISO-8601 notes on <http://www.w3.org/TR/NOTE-datetime>.
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.deser;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
public class TestDateDeserialization
extends BaseMapTest
{
// Test for [JACKSON-435]
static class DateAsStringBean
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="/yyyy/MM/dd/")
public Date date;
}
static class DateAsStringBeanGermany
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="/yyyy/MM/dd/", locale="fr_FR")
public Date date;
}
static class CalendarAsStringBean
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern=";yyyy/MM/dd;")
public Calendar cal;
}
static class DateInCETBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH", timezone="CET")
public Date date;
}
/*
/**********************************************************
/* Unit tests
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDateUtil() throws Exception
{
long now = 123456789L;
java.util.Date value = new java.util.Date(now);
// First from long
assertEquals(value, MAPPER.readValue(""+now, java.util.Date.class));
// then from String
String dateStr = dateToString(value);
java.util.Date result = MAPPER.readValue("\""+dateStr+"\"", java.util.Date.class);
assertEquals("Date: expect "+value+" ("+value.getTime()+"), got "+result+" ("+result.getTime()+")",
value.getTime(), result.getTime());
}
public void testDateUtilWithStringTimestamp() throws Exception
{
long now = 1321992375446L;
/* As of 1.5.0, should be ok to pass as JSON String, as long
* as it is plain timestamp (all numbers, 64-bit)
*/
String json = quote(String.valueOf(now));
java.util.Date value = MAPPER.readValue(json, java.util.Date.class);
assertEquals(now, value.getTime());
// #267: should handle negative timestamps too; like 12 hours before 1.1.1970
long before = - (24 * 3600 * 1000L);
json = quote(String.valueOf(before));
value = MAPPER.readValue(json, java.util.Date.class);
assertEquals(before, value.getTime());
}
public void testDateUtilRFC1123() throws Exception
{
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
// let's use an arbitrary value...
String inputStr = "Sat, 17 Jan 2009 06:13:58 +0000";
java.util.Date inputDate = fmt.parse(inputStr);
assertEquals(inputDate, MAPPER.readValue("\""+inputStr+"\"", java.util.Date.class));
}
public void testDateUtilRFC1123OnNonUSLocales() throws Exception
{
Locale old = Locale.getDefault();
Locale.setDefault(Locale.GERMAN);
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
// let's use an arbitrary value...
String inputStr = "Sat, 17 Jan 2009 06:13:58 +0000";
java.util.Date inputDate = fmt.parse(inputStr);
assertEquals(inputDate, MAPPER.readValue("\""+inputStr+"\"", java.util.Date.class));
Locale.setDefault(old);
}
/**
* ISO8601 is supported as well
*/
public void testDateUtilISO8601() throws Exception
{
/* let's use simple baseline value, arbitrary date in GMT,
* using the standard notation
*/
String inputStr = "1972-12-28T00:00:00.000+0000";
Date inputDate = MAPPER.readValue("\""+inputStr+"\"", java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
// And then the same, but using 'Z' as alias for +0000 (very common)
inputStr = "1972-12-28T00:00:00.000Z";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
// Same but using colon in timezone
inputStr = "1972-12-28T00:00:00.000+00:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
// Same but only passing hour difference as timezone
inputStr = "1972-12-28T00:00:00.000+00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
inputStr = "1984-11-30T00:00:00.000Z";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1984, c.get(Calendar.YEAR));
assertEquals(Calendar.NOVEMBER, c.get(Calendar.MONTH));
assertEquals(30, c.get(Calendar.DAY_OF_MONTH));
}
// [Databind#570]
public void testISO8601PartialMilliseconds() throws Exception
{
String inputStr;
Date inputDate;
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
inputStr = "2014-10-03T18:00:00.6-05:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(2014, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(3, c.get(Calendar.DAY_OF_MONTH));
assertEquals(600, c.get(Calendar.MILLISECOND));
inputStr = "2014-10-03T18:00:00.61-05:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(2014, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(3, c.get(Calendar.DAY_OF_MONTH));
assertEquals(18 + 5, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.MINUTE));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(610, c.get(Calendar.MILLISECOND));
inputStr = "1997-07-16T19:20:30.45+01:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1997, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(16, c.get(Calendar.DAY_OF_MONTH));
assertEquals(19 - 1, c.get(Calendar.HOUR_OF_DAY));
assertEquals(20, c.get(Calendar.MINUTE));
assertEquals(30, c.get(Calendar.SECOND));
assertEquals(450, c.get(Calendar.MILLISECOND));
}
public void testISO8601MissingSeconds() throws Exception
{
String inputStr;
Date inputDate;
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
inputStr = "1997-07-16T19:20+01:00";
inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
c.setTime(inputDate);
assertEquals(1997, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(16, c.get(Calendar.DAY_OF_MONTH));
assertEquals(19 - 1, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
}
public void testDateUtilISO8601NoTimezone() throws Exception
{
// Timezone itself is optional as well...
String inputStr = "1984-11-13T00:00:09";
Date inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(1984, c.get(Calendar.YEAR));
assertEquals(Calendar.NOVEMBER, c.get(Calendar.MONTH));
assertEquals(13, c.get(Calendar.DAY_OF_MONTH));
assertEquals(0, c.get(Calendar.HOUR_OF_DAY));
assertEquals(0, c.get(Calendar.MINUTE));
assertEquals(9, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
}
// [Issue#338]
public void testDateUtilISO8601NoMilliseconds() throws Exception
{
final String INPUT_STR = "2013-10-31T17:27:00";
Date inputDate;
Calendar c;
inputDate = MAPPER.readValue(quote(INPUT_STR), java.util.Date.class);
c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(2013, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(31, c.get(Calendar.DAY_OF_MONTH));
assertEquals(17, c.get(Calendar.HOUR_OF_DAY));
assertEquals(27, c.get(Calendar.MINUTE));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
// 03-Nov-2013, tatu: This wouldn't work, and is the nominal reason
// for #338 I think
/*
inputDate = ISO8601Utils.parse(INPUT_STR);
c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(2013, c.get(Calendar.YEAR));
assertEquals(Calendar.OCTOBER, c.get(Calendar.MONTH));
assertEquals(31, c.get(Calendar.DAY_OF_MONTH));
assertEquals(17, c.get(Calendar.HOUR_OF_DAY));
assertEquals(27, c.get(Calendar.MINUTE));
assertEquals(0, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
*/
}
public void testDateUtilISO8601JustDate() throws Exception
{
// Plain date (no time)
String inputStr = "1972-12-28";
Date inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(1972, c.get(Calendar.YEAR));
assertEquals(Calendar.DECEMBER, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
}
@SuppressWarnings("deprecation")
public void testDateSql() throws Exception
{
java.sql.Date value = new java.sql.Date(0L);
value.setYear(99); // 1999
value.setDate(19);
value.setMonth(Calendar.APRIL);
long now = value.getTime();
// First from long
assertEquals(value, MAPPER.readValue(String.valueOf(now), java.sql.Date.class));
// then from default java.sql.Date String serialization:
java.sql.Date result = MAPPER.readValue(quote(value.toString()), java.sql.Date.class);
Calendar c = gmtCalendar(result.getTime());
assertEquals(1999, c.get(Calendar.YEAR));
assertEquals(Calendar.APRIL, c.get(Calendar.MONTH));
assertEquals(19, c.get(Calendar.DAY_OF_MONTH));
/* [JACKSON-200]: looks like we better add support for regular date
* formats as well
*/
String expStr = "1981-07-13";
result = MAPPER.readValue(quote(expStr), java.sql.Date.class);
c.setTimeInMillis(result.getTime());
assertEquals(1981, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(13, c.get(Calendar.DAY_OF_MONTH));
/* 20-Nov-2009, tatus: I'll be damned if I understand why string serialization
* is off-by-one, but day-of-month does seem to be one less. My guess is
* that something is funky with timezones (i.e. somewhere local TZ is
* being used), but just can't resolve it. Hence, need to comment this:
*/
// assertEquals(expStr, result.toString());
}
public void testCalendar() throws Exception
{
// not ideal, to use (ever-changing) current date, but...
java.util.Calendar value = Calendar.getInstance();
long l = 12345678L;
value.setTimeInMillis(l);
// First from long
Calendar result = MAPPER.readValue(""+l, Calendar.class);
assertEquals(l, result.getTimeInMillis());
// Then from serialized String
String dateStr = dateToString(new Date(l));
result = MAPPER.readValue(quote(dateStr), Calendar.class);
// note: representation may differ (wrt timezone etc), but underlying value must remain the same:
assertEquals(l, result.getTimeInMillis());
}
public void testCustom() throws Exception
{
final ObjectMapper mapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("PST"));
mapper.setDateFormat(df);
String dateStr = "1972-12-28X15:45:00";
java.util.Date exp = df.parse(dateStr);
java.util.Date result = mapper.readValue("\""+dateStr+"\"", java.util.Date.class);
assertEquals(exp, result);
}
/**
* Test for [JACKSON-203]: make empty Strings deserialize as nulls by default,
* without need to turn on feature (which may be added in future)
*/
public void testDatesWithEmptyStrings() throws Exception
{
assertNull(MAPPER.readValue(quote(""), java.util.Date.class));
assertNull(MAPPER.readValue(quote(""), java.util.Calendar.class));
assertNull(MAPPER.readValue(quote(""), java.sql.Date.class));
}
// for [JACKSON-334]
public void test8601DateTimeNoMilliSecs() throws Exception
{
// ok, Zebra, no milliseconds
for (String inputStr : new String[] {
"2010-06-28T23:34:22Z",
"2010-06-28T23:34:22+0000",
"2010-06-28T23:34:22+00",
}) {
Date inputDate = MAPPER.readValue(quote(inputStr), java.util.Date.class);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTime(inputDate);
assertEquals(2010, c.get(Calendar.YEAR));
assertEquals(Calendar.JUNE, c.get(Calendar.MONTH));
assertEquals(28, c.get(Calendar.DAY_OF_MONTH));
assertEquals(23, c.get(Calendar.HOUR_OF_DAY));
assertEquals(34, c.get(Calendar.MINUTE));
assertEquals(22, c.get(Calendar.SECOND));
assertEquals(0, c.get(Calendar.MILLISECOND));
}
}
public void testTimeZone() throws Exception
{
TimeZone result = MAPPER.readValue(quote("PST"), TimeZone.class);
assertEquals("PST", result.getID());
}
public void testCustomDateWithAnnotation() throws Exception
{
final String INPUT = "{\"date\":\"/2005/05/25/\"}";
DateAsStringBean result = MAPPER.readValue(INPUT, DateAsStringBean.class);
assertNotNull(result);
assertNotNull(result.date);
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long l = result.date.getTime();
if (l == 0L) {
fail("Should not get null date");
}
c.setTimeInMillis(l);
assertEquals(2005, c.get(Calendar.YEAR));
assertEquals(Calendar.MAY, c.get(Calendar.MONTH));
assertEquals(25, c.get(Calendar.DAY_OF_MONTH));
// 27-Mar-2014, tatu: Let's verify that changing Locale won't break it;
// either via context Locale
result = MAPPER.reader(DateAsStringBean.class)
.with(Locale.GERMANY)
.readValue(INPUT);
assertNotNull(result);
assertNotNull(result.date);
l = result.date.getTime();
if (l == 0L) {
fail("Should not get null date");
}
c.setTimeInMillis(l);
assertEquals(2005, c.get(Calendar.YEAR));
assertEquals(Calendar.MAY, c.get(Calendar.MONTH));
assertEquals(25, c.get(Calendar.DAY_OF_MONTH));
// or, via annotations
DateAsStringBeanGermany result2 = MAPPER.reader(DateAsStringBeanGermany.class).readValue(INPUT);
assertNotNull(result2);
assertNotNull(result2.date);
l = result2.date.getTime();
if (l == 0L) {
fail("Should not get null date");
}
c.setTimeInMillis(l);
assertEquals(2005, c.get(Calendar.YEAR));
assertEquals(Calendar.MAY, c.get(Calendar.MONTH));
assertEquals(25, c.get(Calendar.DAY_OF_MONTH));
}
public void testCustomCalendarWithAnnotation() throws Exception
{
CalendarAsStringBean cbean = MAPPER.readValue("{\"cal\":\";2007/07/13;\"}",
CalendarAsStringBean.class);
assertNotNull(cbean);
assertNotNull(cbean.cal);
Calendar c = cbean.cal;
assertEquals(2007, c.get(Calendar.YEAR));
assertEquals(Calendar.JULY, c.get(Calendar.MONTH));
assertEquals(13, c.get(Calendar.DAY_OF_MONTH));
}
public void testCustomCalendarWithTimeZone() throws Exception
{
// And then with different TimeZone: CET is +01:00 from GMT -- read as CET
DateInCETBean cet = MAPPER.readValue("{\"date\":\"2001-01-01,10\"}",
DateInCETBean.class);
Calendar c = Calendar.getInstance(getUTCTimeZone());
c.setTimeInMillis(cet.date.getTime());
// so, going to UTC/GMT should reduce hour by one
assertEquals(2001, c.get(Calendar.YEAR));
assertEquals(Calendar.JANUARY, c.get(Calendar.MONTH));
assertEquals(1, c.get(Calendar.DAY_OF_MONTH));
assertEquals(9, c.get(Calendar.HOUR_OF_DAY));
}
/*
/**********************************************************
/* Tests to verify failing cases
/**********************************************************
*/
public void testInvalidFormat() throws Exception
{
try {
MAPPER.readValue(quote("foobar"), Date.class);
fail("Should have failed with an exception");
} catch (InvalidFormatException e) {
verifyException(e, "Can not construct instance");
assertEquals("foobar", e.getValue());
assertEquals(Date.class, e.getTargetType());
} catch (Exception e) {
fail("Wrong type of exception ("+e.getClass().getName()+"), should get "
+InvalidFormatException.class.getName());
}
}
/*
/**********************************************************
/* Helper methods
/**********************************************************
*/
private String dateToString(java.util.Date value)
{
/* Then from String. This is bit tricky, since JDK does not really
* suggest a 'standard' format. So let's try using something...
*/
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return df.format(value);
}
private static Calendar gmtCalendar(long time)
{
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.setTimeInMillis(time);
return c;
}
} |
||
@Test
public void testReciprocalZero() {
Assert.assertEquals(Complex.ZERO.reciprocal(), Complex.INF);
} | org.apache.commons.math3.complex.ComplexTest::testReciprocalZero | src/test/java/org/apache/commons/math3/complex/ComplexTest.java | 334 | src/test/java/org/apache/commons/math3/complex/ComplexTest.java | testReciprocalZero | /*
* 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.complex;
import org.apache.commons.math3.TestUtils;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.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.assertSame(Complex.NaN, z);
z = new Complex(1, nan);
Complex w = x.add(z);
Assert.assertSame(Complex.NaN, w);
}
@Test
public void testAddInf() {
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 testScalarAdd() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
}
@Test
public void testScalarAddNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
}
@Test
public void testScalarAddInf() {
Complex x = new Complex(1, 1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
x = new Complex(neginf, 0);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
}
@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 testDivideInf() {
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.INF); // See MATH-657
Assert.assertEquals(z, Complex.NaN);
}
@Test
public void testDivideZeroZero() {
Complex x = new Complex(0.0, 0.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 testScalarDivide() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.divide(yComplex), x.divide(yDouble));
}
@Test
public void testScalarDivideNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.divide(yComplex), x.divide(yDouble));
}
@Test
public void testScalarDivideInf() {
Complex x = new Complex(1,1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0);
yDouble = Double.NEGATIVE_INFINITY;
yComplex = new Complex(yDouble);
TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0);
x = new Complex(1, Double.NEGATIVE_INFINITY);
TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0);
}
@Test
public void testScalarDivideZero() {
Complex x = new Complex(1,1);
TestUtils.assertEquals(x.divide(Complex.ZERO), x.divide(0), 0);
}
@Test
public void testReciprocal() {
Complex z = new Complex(5.0, 6.0);
Complex act = z.reciprocal();
double expRe = 5.0 / 61.0;
double expIm = -6.0 / 61.0;
Assert.assertEquals(expRe, act.getReal(), FastMath.ulp(expRe));
Assert.assertEquals(expIm, act.getImaginary(), FastMath.ulp(expIm));
}
@Test
public void testReciprocalReal() {
Complex z = new Complex(-2.0, 0.0);
Assert.assertEquals(new Complex(-0.5, 0.0), z.reciprocal());
}
@Test
public void testReciprocalImaginary() {
Complex z = new Complex(0.0, -2.0);
Assert.assertEquals(new Complex(0.0, 0.5), z.reciprocal());
}
@Test
public void testReciprocalInf() {
Complex z = new Complex(neginf, inf);
Assert.assertTrue(z.reciprocal().equals(Complex.ZERO));
z = new Complex(1, inf).reciprocal();
Assert.assertEquals(z, Complex.ZERO);
}
@Test
public void testReciprocalZero() {
Assert.assertEquals(Complex.ZERO.reciprocal(), Complex.INF);
}
@Test
public void testReciprocalNaN() {
Assert.assertTrue(Complex.NaN.reciprocal().isNaN());
}
@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.assertSame(Complex.NaN, z);
z = Complex.NaN.multiply(5);
Assert.assertSame(Complex.NaN, z);
}
@Test
public void testMultiplyInfInf() {
// Assert.assertTrue(infInf.multiply(infInf).isNaN()); // MATH-620
Assert.assertTrue(infInf.multiply(infInf).isInfinite());
}
@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()));
z = new Complex(1, neginf);
Assert.assertSame(Complex.INF, z.multiply(z));
}
@Test
public void testScalarMultiply() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
int zInt = -5;
Complex zComplex = new Complex(zInt);
Assert.assertEquals(x.multiply(zComplex), x.multiply(zInt));
}
@Test
public void testScalarMultiplyNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
}
@Test
public void testScalarMultiplyInf() {
Complex x = new Complex(1, 1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
yDouble = Double.NEGATIVE_INFINITY;
yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
}
@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.assertSame(Complex.NaN, z);
z = new Complex(1, nan);
Complex w = x.subtract(z);
Assert.assertSame(Complex.NaN, w);
}
@Test
public void testSubtractInf() {
Complex x = new Complex(1, 1);
Complex z = new Complex(neginf, 0);
Complex w = x.subtract(z);
Assert.assertEquals(w.getImaginary(), 1, 0);
Assert.assertEquals(inf, w.getReal(), 0);
x = new Complex(neginf, 0);
Assert.assertTrue(Double.isNaN(x.subtract(z).getReal()));
}
@Test
public void testScalarSubtract() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
}
@Test
public void testScalarSubtractNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
}
@Test
public void testScalarSubtractInf() {
Complex x = new Complex(1, 1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
x = new Complex(neginf, 0);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
}
@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 testAtanI() {
Assert.assertTrue(Complex.I.atan().isNaN());
}
@Test
public void testAtanNaN() {
Assert.assertTrue(Complex.NaN.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
public void testScalarPow() {
Complex x = new Complex(3, 4);
double yDouble = 5.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.pow(yComplex), x.pow(yDouble));
}
@Test
public void testScalarPowNaNBase() {
Complex x = Complex.NaN;
double yDouble = 5.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.pow(yComplex), x.pow(yDouble));
}
@Test
public void testScalarPowNaNExponent() {
Complex x = new Complex(3, 4);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.pow(yComplex), x.pow(yDouble));
}
@Test
public void testScalarPowInf() {
TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(Double.NEGATIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infOne.pow(1.0));
TestUtils.assertSame(Complex.NaN,negInfOne.pow(1.0));
TestUtils.assertSame(Complex.NaN,infInf.pow(1.0));
TestUtils.assertSame(Complex.NaN,infNegInf.pow(1.0));
TestUtils.assertSame(Complex.NaN,negInfInf.pow(10));
TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(1.0));
TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infInf.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infInf.pow(Double.NEGATIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infNegInf.pow(Double.NEGATIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infNegInf.pow(Double.POSITIVE_INFINITY));
}
@Test
public void testScalarPowZero() {
TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(1.0));
TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(0.0));
TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(0.0), 10e-12);
TestUtils.assertEquals(Complex.ONE, Complex.I.pow(0.0), 10e-12);
TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(0.0), 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);
/* Check that no overflow occurs (MATH-722) */
Complex actual = new Complex(3.0, 1E10).tan();
expected = new Complex(0, 1);
TestUtils.assertEquals(expected, actual, 1.0e-5);
actual = new Complex(3.0, -1E10).tan();
expected = new Complex(0, -1);
TestUtils.assertEquals(expected, actual, 1.0e-5);
}
@Test
public void testTanNaN() {
Assert.assertTrue(Complex.NaN.tan().isNaN());
}
@Test
public void testTanInf() {
TestUtils.assertSame(Complex.valueOf(0.0, 1.0), oneInf.tan());
TestUtils.assertSame(Complex.valueOf(0.0, -1.0), 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);
/* Check that no overflow occurs (MATH-722) */
Complex actual = new Complex(1E10, 3.0).tanh();
expected = new Complex(1, 0);
TestUtils.assertEquals(expected, actual, 1.0e-5);
actual = new Complex(-1E10, 3.0).tanh();
expected = new Complex(-1, 0);
TestUtils.assertEquals(expected, actual, 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(Complex.valueOf(1.0, 0.0), infOne.tanh());
TestUtils.assertSame(Complex.valueOf(-1.0, 0.0), 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 `testReciprocalZero` for the issue `Math-MATH-934`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-934
//
// ## Issue-Title:
// Complex.ZERO.reciprocal() returns NaN but should return INF.
//
// ## Issue-Description:
//
// Complex.ZERO.reciprocal() returns NaN but should return INF.
//
//
// Class: org.apache.commons.math3.complex.Complex;
//
// Method: reciprocal()
//
// @version $Id: Complex.java 1416643 2012-12-03 19:37:14Z tn $
//
//
//
//
//
@Test
public void testReciprocalZero() {
| 334 | 5 | 331 | src/test/java/org/apache/commons/math3/complex/ComplexTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-934
## Issue-Title:
Complex.ZERO.reciprocal() returns NaN but should return INF.
## Issue-Description:
Complex.ZERO.reciprocal() returns NaN but should return INF.
Class: org.apache.commons.math3.complex.Complex;
Method: reciprocal()
@version $Id: Complex.java 1416643 2012-12-03 19:37:14Z tn $
```
You are a professional Java test case writer, please create a test case named `testReciprocalZero` for the issue `Math-MATH-934`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testReciprocalZero() {
```
| 331 | [
"org.apache.commons.math3.complex.Complex"
] | 67ed68038737803c5cdb9706d5f614e75f06fe8eb675ac0f4e5a1fc60d648e8c | @Test
public void testReciprocalZero() | // You are a professional Java test case writer, please create a test case named `testReciprocalZero` for the issue `Math-MATH-934`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-934
//
// ## Issue-Title:
// Complex.ZERO.reciprocal() returns NaN but should return INF.
//
// ## Issue-Description:
//
// Complex.ZERO.reciprocal() returns NaN but should return INF.
//
//
// Class: org.apache.commons.math3.complex.Complex;
//
// Method: reciprocal()
//
// @version $Id: Complex.java 1416643 2012-12-03 19:37:14Z tn $
//
//
//
//
//
| 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.complex;
import org.apache.commons.math3.TestUtils;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.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.assertSame(Complex.NaN, z);
z = new Complex(1, nan);
Complex w = x.add(z);
Assert.assertSame(Complex.NaN, w);
}
@Test
public void testAddInf() {
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 testScalarAdd() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
}
@Test
public void testScalarAddNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
}
@Test
public void testScalarAddInf() {
Complex x = new Complex(1, 1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
x = new Complex(neginf, 0);
Assert.assertEquals(x.add(yComplex), x.add(yDouble));
}
@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 testDivideInf() {
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.INF); // See MATH-657
Assert.assertEquals(z, Complex.NaN);
}
@Test
public void testDivideZeroZero() {
Complex x = new Complex(0.0, 0.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 testScalarDivide() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.divide(yComplex), x.divide(yDouble));
}
@Test
public void testScalarDivideNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.divide(yComplex), x.divide(yDouble));
}
@Test
public void testScalarDivideInf() {
Complex x = new Complex(1,1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0);
yDouble = Double.NEGATIVE_INFINITY;
yComplex = new Complex(yDouble);
TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0);
x = new Complex(1, Double.NEGATIVE_INFINITY);
TestUtils.assertEquals(x.divide(yComplex), x.divide(yDouble), 0);
}
@Test
public void testScalarDivideZero() {
Complex x = new Complex(1,1);
TestUtils.assertEquals(x.divide(Complex.ZERO), x.divide(0), 0);
}
@Test
public void testReciprocal() {
Complex z = new Complex(5.0, 6.0);
Complex act = z.reciprocal();
double expRe = 5.0 / 61.0;
double expIm = -6.0 / 61.0;
Assert.assertEquals(expRe, act.getReal(), FastMath.ulp(expRe));
Assert.assertEquals(expIm, act.getImaginary(), FastMath.ulp(expIm));
}
@Test
public void testReciprocalReal() {
Complex z = new Complex(-2.0, 0.0);
Assert.assertEquals(new Complex(-0.5, 0.0), z.reciprocal());
}
@Test
public void testReciprocalImaginary() {
Complex z = new Complex(0.0, -2.0);
Assert.assertEquals(new Complex(0.0, 0.5), z.reciprocal());
}
@Test
public void testReciprocalInf() {
Complex z = new Complex(neginf, inf);
Assert.assertTrue(z.reciprocal().equals(Complex.ZERO));
z = new Complex(1, inf).reciprocal();
Assert.assertEquals(z, Complex.ZERO);
}
@Test
public void testReciprocalZero() {
Assert.assertEquals(Complex.ZERO.reciprocal(), Complex.INF);
}
@Test
public void testReciprocalNaN() {
Assert.assertTrue(Complex.NaN.reciprocal().isNaN());
}
@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.assertSame(Complex.NaN, z);
z = Complex.NaN.multiply(5);
Assert.assertSame(Complex.NaN, z);
}
@Test
public void testMultiplyInfInf() {
// Assert.assertTrue(infInf.multiply(infInf).isNaN()); // MATH-620
Assert.assertTrue(infInf.multiply(infInf).isInfinite());
}
@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()));
z = new Complex(1, neginf);
Assert.assertSame(Complex.INF, z.multiply(z));
}
@Test
public void testScalarMultiply() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
int zInt = -5;
Complex zComplex = new Complex(zInt);
Assert.assertEquals(x.multiply(zComplex), x.multiply(zInt));
}
@Test
public void testScalarMultiplyNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
}
@Test
public void testScalarMultiplyInf() {
Complex x = new Complex(1, 1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
yDouble = Double.NEGATIVE_INFINITY;
yComplex = new Complex(yDouble);
Assert.assertEquals(x.multiply(yComplex), x.multiply(yDouble));
}
@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.assertSame(Complex.NaN, z);
z = new Complex(1, nan);
Complex w = x.subtract(z);
Assert.assertSame(Complex.NaN, w);
}
@Test
public void testSubtractInf() {
Complex x = new Complex(1, 1);
Complex z = new Complex(neginf, 0);
Complex w = x.subtract(z);
Assert.assertEquals(w.getImaginary(), 1, 0);
Assert.assertEquals(inf, w.getReal(), 0);
x = new Complex(neginf, 0);
Assert.assertTrue(Double.isNaN(x.subtract(z).getReal()));
}
@Test
public void testScalarSubtract() {
Complex x = new Complex(3.0, 4.0);
double yDouble = 2.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
}
@Test
public void testScalarSubtractNaN() {
Complex x = new Complex(3.0, 4.0);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
}
@Test
public void testScalarSubtractInf() {
Complex x = new Complex(1, 1);
double yDouble = Double.POSITIVE_INFINITY;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
x = new Complex(neginf, 0);
Assert.assertEquals(x.subtract(yComplex), x.subtract(yDouble));
}
@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 testAtanI() {
Assert.assertTrue(Complex.I.atan().isNaN());
}
@Test
public void testAtanNaN() {
Assert.assertTrue(Complex.NaN.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
public void testScalarPow() {
Complex x = new Complex(3, 4);
double yDouble = 5.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.pow(yComplex), x.pow(yDouble));
}
@Test
public void testScalarPowNaNBase() {
Complex x = Complex.NaN;
double yDouble = 5.0;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.pow(yComplex), x.pow(yDouble));
}
@Test
public void testScalarPowNaNExponent() {
Complex x = new Complex(3, 4);
double yDouble = Double.NaN;
Complex yComplex = new Complex(yDouble);
Assert.assertEquals(x.pow(yComplex), x.pow(yDouble));
}
@Test
public void testScalarPowInf() {
TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,Complex.ONE.pow(Double.NEGATIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infOne.pow(1.0));
TestUtils.assertSame(Complex.NaN,negInfOne.pow(1.0));
TestUtils.assertSame(Complex.NaN,infInf.pow(1.0));
TestUtils.assertSame(Complex.NaN,infNegInf.pow(1.0));
TestUtils.assertSame(Complex.NaN,negInfInf.pow(10));
TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(1.0));
TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,negInfNegInf.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infInf.pow(Double.POSITIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infInf.pow(Double.NEGATIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infNegInf.pow(Double.NEGATIVE_INFINITY));
TestUtils.assertSame(Complex.NaN,infNegInf.pow(Double.POSITIVE_INFINITY));
}
@Test
public void testScalarPowZero() {
TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(1.0));
TestUtils.assertSame(Complex.NaN, Complex.ZERO.pow(0.0));
TestUtils.assertEquals(Complex.ONE, Complex.ONE.pow(0.0), 10e-12);
TestUtils.assertEquals(Complex.ONE, Complex.I.pow(0.0), 10e-12);
TestUtils.assertEquals(Complex.ONE, new Complex(-1, 3).pow(0.0), 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);
/* Check that no overflow occurs (MATH-722) */
Complex actual = new Complex(3.0, 1E10).tan();
expected = new Complex(0, 1);
TestUtils.assertEquals(expected, actual, 1.0e-5);
actual = new Complex(3.0, -1E10).tan();
expected = new Complex(0, -1);
TestUtils.assertEquals(expected, actual, 1.0e-5);
}
@Test
public void testTanNaN() {
Assert.assertTrue(Complex.NaN.tan().isNaN());
}
@Test
public void testTanInf() {
TestUtils.assertSame(Complex.valueOf(0.0, 1.0), oneInf.tan());
TestUtils.assertSame(Complex.valueOf(0.0, -1.0), 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);
/* Check that no overflow occurs (MATH-722) */
Complex actual = new Complex(1E10, 3.0).tanh();
expected = new Complex(1, 0);
TestUtils.assertEquals(expected, actual, 1.0e-5);
actual = new Complex(-1E10, 3.0).tanh();
expected = new Complex(-1, 0);
TestUtils.assertEquals(expected, actual, 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(Complex.valueOf(1.0, 0.0), infOne.tanh());
TestUtils.assertSame(Complex.valueOf(-1.0, 0.0), 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 testExternalIssue1053() {
testSame(
"var u; function f() { u = Random(); var x = u; f(); alert(x===u)}");
} | com.google.javascript.jscomp.InlineVariablesTest::testExternalIssue1053 | test/com/google/javascript/jscomp/InlineVariablesTest.java | 1,070 | test/com/google/javascript/jscomp/InlineVariablesTest.java | testExternalIssue1053 | /*
* 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;
/**
* Verifies that valid candidates for inlining are inlined, but
* that no dangerous inlining occurs.
*
* @author kushal@google.com (Kushal Dave)
*/
public class InlineVariablesTest extends CompilerTestCase {
private boolean inlineAllStrings = false;
private boolean inlineLocalsOnly = false;
public InlineVariablesTest() {
enableNormalize();
}
@Override
public void setUp() {
super.enableLineNumberCheck(true);
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
return new InlineVariables(
compiler,
(inlineLocalsOnly)
? InlineVariables.Mode.LOCALS_ONLY
: InlineVariables.Mode.ALL,
inlineAllStrings);
}
@Override
public void tearDown() {
inlineAllStrings = false;
inlineLocalsOnly = false;
}
// Test respect for scopes and blocks
public void testInlineGlobal() {
test("var x = 1; var z = x;", "var z = 1;");
}
public void testNoInlineExportedName() {
testSame("var _x = 1; var z = _x;");
}
public void testNoInlineExportedName2() {
testSame("var f = function() {}; var _x = f;" +
"var y = function() { _x(); }; var _y = f;");
}
public void testDoNotInlineIncrement() {
testSame("var x = 1; x++;");
}
public void testDoNotInlineDecrement() {
testSame("var x = 1; x--;");
}
public void testDoNotInlineIntoLhsOfAssign() {
testSame("var x = 1; x += 3;");
}
public void testInlineIntoRhsOfAssign() {
test("var x = 1; var y = x;", "var y = 1;");
}
public void testInlineInFunction() {
test("function baz() { var x = 1; var z = x; }",
"function baz() { var z = 1; }");
}
public void testInlineInFunction2() {
test("function baz() { " +
"var a = new obj();"+
"result = a;" +
"}",
"function baz() { " +
"result = new obj()" +
"}");
}
public void testInlineInFunction3() {
testSame(
"function baz() { " +
"var a = new obj();" +
"(function(){a;})();" +
"result = a;" +
"}");
}
public void testInlineInFunction4() {
testSame(
"function baz() { " +
"var a = new obj();" +
"foo.result = a;" +
"}");
}
public void testInlineInFunction5() {
testSame(
"function baz() { " +
"var a = (foo = new obj());" +
"foo.x();" +
"result = a;" +
"}");
}
public void testInlineAcrossModules() {
// TODO(kushal): Make decision about overlap with CrossModuleCodeMotion
test(createModules("var a = 2;", "var b = a;"),
new String[] { "", "var b = 2;" });
}
public void testDoNotExitConditional1() {
testSame("if (true) { var x = 1; } var z = x;");
}
public void testDoNotExitConditional2() {
testSame("if (true) var x = 1; var z = x;");
}
public void testDoNotExitConditional3() {
testSame("var x; if (true) x=1; var z = x;");
}
public void testDoNotExitLoop() {
testSame("while (z) { var x = 3; } var y = x;");
}
public void testDoNotExitForLoop() {
test("for (var i = 1; false; false) var z = i;",
"for (;false;false) var z = 1;");
testSame("for (; false; false) var i = 1; var z = i;");
testSame("for (var i in {}); var z = i;");
}
public void testDoNotEnterSubscope() {
testSame(
"var x = function() {" +
" var self = this; " +
" return function() { var y = self; };" +
"}");
testSame(
"var x = function() {" +
" var y = [1]; " +
" return function() { var z = y; };" +
"}");
}
public void testDoNotExitTry() {
testSame("try { var x = y; } catch (e) {} var z = y; ");
testSame("try { throw e; var x = 1; } catch (e) {} var z = x; ");
}
public void testDoNotEnterCatch() {
testSame("try { } catch (e) { var z = e; } ");
}
public void testDoNotEnterFinally() {
testSame("try { throw e; var x = 1; } catch (e) {} " +
"finally { var z = x; } ");
}
public void testInsideIfConditional() {
test("var a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }");
test("var a; a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }");
}
public void testOnlyReadAtInitialization() {
test("var a; a = foo();", "foo();");
test("var a; if (a = foo()) { alert(3); }", "if (foo()) { alert(3); }");
test("var a; switch (a = foo()) {}", "switch(foo()) {}");
test("var a; function f(){ return a = foo(); }",
"function f(){ return foo(); }");
test("function f(){ var a; return a = foo(); }",
"function f(){ return foo(); }");
test("var a; with (a = foo()) { alert(3); }", "with (foo()) { alert(3); }");
test("var a; b = (a = foo());", "b = foo();");
test("var a; while(a = foo()) { alert(3); }",
"while(foo()) { alert(3); }");
test("var a; for(;a = foo();) { alert(3); }",
"for(;foo();) { alert(3); }");
test("var a; do {} while(a = foo()) { alert(3); }",
"do {} while(foo()) { alert(3); }");
}
public void testImmutableWithSingleReferenceAfterInitialzation() {
test("var a; a = 1;", "1;");
test("var a; if (a = 1) { alert(3); }", "if (1) { alert(3); }");
test("var a; switch (a = 1) {}", "switch(1) {}");
test("var a; function f(){ return a = 1; }",
"function f(){ return 1; }");
test("function f(){ var a; return a = 1; }",
"function f(){ return 1; }");
test("var a; with (a = 1) { alert(3); }", "with (1) { alert(3); }");
test("var a; b = (a = 1);", "b = 1;");
test("var a; while(a = 1) { alert(3); }",
"while(1) { alert(3); }");
test("var a; for(;a = 1;) { alert(3); }",
"for(;1;) { alert(3); }");
test("var a; do {} while(a = 1) { alert(3); }",
"do {} while(1) { alert(3); }");
}
public void testSingleReferenceAfterInitialzation() {
test("var a; a = foo();a;", "foo();");
testSame("var a; if (a = foo()) { alert(3); } a;");
testSame("var a; switch (a = foo()) {} a;");
testSame("var a; function f(){ return a = foo(); } a;");
testSame("function f(){ var a; return a = foo(); a;}");
testSame("var a; with (a = foo()) { alert(3); } a;");
testSame("var a; b = (a = foo()); a;");
testSame("var a; while(a = foo()) { alert(3); } a;");
testSame("var a; for(;a = foo();) { alert(3); } a;");
testSame("var a; do {} while(a = foo()) { alert(3); } a;");
}
public void testInsideIfBranch() {
testSame("var a = foo(); if (1) { alert(a); }");
}
public void testInsideAndConditional() {
test("var a = foo(); a && alert(3);", "foo() && alert(3);");
}
public void testInsideAndBranch() {
testSame("var a = foo(); 1 && alert(a);");
}
public void testInsideOrBranch() {
testSame("var a = foo(); 1 || alert(a);");
}
public void testInsideHookBranch() {
testSame("var a = foo(); 1 ? alert(a) : alert(3)");
}
public void testInsideHookConditional() {
test("var a = foo(); a ? alert(1) : alert(3)",
"foo() ? alert(1) : alert(3)");
}
public void testInsideOrBranchInsideIfConditional() {
testSame("var a = foo(); if (x || a) {}");
}
public void testInsideOrBranchInsideIfConditionalWithConstant() {
// We don't inline non-immutable constants into branches.
testSame("var a = [false]; if (x || a) {}");
}
public void testCrossFunctionsAsLeftLeaves() {
// Ensures getNext() understands how to walk past a function leaf
test(
new String[] { "var x = function() {};", "",
"function cow() {} var z = x;"},
new String[] { "", "", "function cow() {} var z = function() {};" });
test(
new String[] { "var x = function() {};", "",
"var cow = function() {}; var z = x;"},
new String[] { "", "",
"var cow = function() {}; var z = function() {};" });
testSame(
new String[] { "var x = a;", "",
"(function() { a++; })(); var z = x;"});
test(
new String[] { "var x = a;", "",
"function cow() { a++; }; cow(); var z = x;"},
new String[] { "var x = a;", "",
";(function cow(){ a++; })(); var z = x;"});
testSame(
new String[] { "var x = a;", "",
"cow(); var z = x; function cow() { a++; };"});
}
// Test movement of constant values
public void testDoCrossFunction() {
// We know foo() does not affect x because we require that x is only
// referenced twice.
test("var x = 1; foo(); var z = x;", "foo(); var z = 1;");
}
public void testDoNotCrossReferencingFunction() {
testSame(
"var f = function() { var z = x; };" +
"var x = 1;" +
"f();" +
"var z = x;" +
"f();");
}
// Test tricky declarations and references
public void testChainedAssignment() {
test("var a = 2, b = 2; var c = b;", "var a = 2; var c = 2;");
test("var a = 2, b = 2; var c = a;", "var b = 2; var c = 2;");
test("var a = b = 2; var f = 3; var c = a;", "var f = 3; var c = b = 2;");
testSame("var a = b = 2; var c = b;");
}
public void testForIn() {
testSame("for (var i in j) { var c = i; }");
testSame("var i = 0; for (i in j) ;");
testSame("var i = 0; for (i in j) { var c = i; }");
testSame("i = 0; for (var i in j) { var c = i; }");
testSame("var j = {'key':'value'}; for (var i in j) {print(i)};");
}
// Test movement of values that have (may) side effects
public void testDoCrossNewVariables() {
test("var x = foo(); var z = x;", "var z = foo();");
}
public void testDoNotCrossFunctionCalls() {
testSame("var x = foo(); bar(); var z = x;");
}
// Test movement of values that are complex but lack side effects
public void testDoNotCrossAssignment() {
testSame("var x = {}; var y = x.a; x.a = 1; var z = y;");
testSame("var a = this.id; foo(this.id = 3, a);");
}
public void testDoNotCrossDelete() {
testSame("var x = {}; var y = x.a; delete x.a; var z = y;");
}
public void testDoNotCrossAssignmentPlus() {
testSame("var a = b; b += 2; var c = a;");
}
public void testDoNotCrossIncrement() {
testSame("var a = b.c; b.c++; var d = a;");
}
public void testDoNotCrossConstructor() {
testSame("var a = b; new Foo(); var c = a;");
}
public void testDoCrossVar() {
// Assumes we do not rely on undefined variables (not technically correct!)
test("var a = b; var b = 3; alert(a)", "alert(3);");
}
public void testOverlappingInlines() {
String source =
"a = function(el, x, opt_y) { " +
" var cur = bar(el); " +
" opt_y = x.y; " +
" x = x.x; " +
" var dx = x - cur.x; " +
" var dy = opt_y - cur.y;" +
" foo(el, el.offsetLeft + dx, el.offsetTop + dy); " +
"};";
String expected =
"a = function(el, x, opt_y) { " +
" var cur = bar(el); " +
" opt_y = x.y; " +
" x = x.x; " +
" foo(el, el.offsetLeft + (x - cur.x)," +
" el.offsetTop + (opt_y - cur.y)); " +
"};";
test(source, expected);
}
public void testOverlappingInlineFunctions() {
String source =
"a = function() { " +
" var b = function(args) {var n;}; " +
" var c = function(args) {}; " +
" d(b,c); " +
"};";
String expected =
"a = function() { " +
" d(function(args){var n;}, function(args){}); " +
"};";
test(source, expected);
}
public void testInlineIntoLoops() {
test("var x = true; while (true) alert(x);",
"while (true) alert(true);");
test("var x = true; while (true) for (var i in {}) alert(x);",
"while (true) for (var i in {}) alert(true);");
testSame("var x = [true]; while (true) alert(x);");
}
public void testInlineIntoFunction() {
test("var x = false; var f = function() { alert(x); };",
"var f = function() { alert(false); };");
testSame("var x = [false]; var f = function() { alert(x); };");
}
public void testNoInlineIntoNamedFunction() {
testSame("f(); var x = false; function f() { alert(x); };");
}
public void testInlineIntoNestedNonHoistedNamedFunctions() {
test("f(); var x = false; if (false) function f() { alert(x); };",
"f(); if (false) function f() { alert(false); };");
}
public void testNoInlineIntoNestedNamedFunctions() {
testSame("f(); var x = false; function f() { if (false) { alert(x); } };");
}
public void testNoInlineMutatedVariable() {
testSame("var x = false; if (true) { var y = x; x = true; }");
}
public void testInlineImmutableMultipleTimes() {
test("var x = null; var y = x, z = x;",
"var y = null, z = null;");
test("var x = 3; var y = x, z = x;",
"var y = 3, z = 3;");
}
public void testNoInlineStringMultipleTimesIfNotWorthwhile() {
testSame("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;");
}
public void testInlineStringMultipleTimesWhenAliasingAllStrings() {
inlineAllStrings = true;
test("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;",
"var y = 'abcdefghijklmnopqrstuvwxyz', " +
" z = 'abcdefghijklmnopqrstuvwxyz';");
}
public void testNoInlineBackwards() {
testSame("var y = x; var x = null;");
}
public void testNoInlineOutOfBranch() {
testSame("if (true) var x = null; var y = x;");
}
public void testInterferingInlines() {
test("var a = 3; var f = function() { var x = a; alert(x); };",
"var f = function() { alert(3); };");
}
public void testInlineIntoTryCatch() {
test("var a = true; " +
"try { var b = a; } " +
"catch (e) { var c = a + b; var d = true; } " +
"finally { var f = a + b + c + d; }",
"try { var b = true; } " +
"catch (e) { var c = true + b; var d = true; } " +
"finally { var f = true + b + c + d; }");
}
// Make sure that we still inline constants that are not provably
// written before they're read.
public void testInlineConstants() {
test("function foo() { return XXX; } var XXX = true;",
"function foo() { return true; }");
}
public void testInlineStringWhenWorthwhile() {
test("var x = 'a'; foo(x, x, x);", "foo('a', 'a', 'a');");
}
public void testInlineConstantAlias() {
test("var XXX = new Foo(); q(XXX); var YYY = XXX; bar(YYY)",
"var XXX = new Foo(); q(XXX); bar(XXX)");
}
public void testInlineConstantAliasWithAnnotation() {
test("/** @const */ var xxx = new Foo(); q(xxx); var YYY = xxx; bar(YYY)",
"/** @const */ var xxx = new Foo(); q(xxx); bar(xxx)");
}
public void testInlineConstantAliasWithNonConstant() {
test("var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)",
"var XXX = new Foo(); q(XXX); bar(XXX); baz(XXX)");
}
public void testCascadingInlines() {
test("var XXX = 4; " +
"function f() { var YYY = XXX; bar(YYY); baz(YYY); }",
"function f() { bar(4); baz(4); }");
}
public void testNoInlineGetpropIntoCall() {
test("var a = b; a();", "b();");
test("var a = b.c; f(a);", "f(b.c);");
testSame("var a = b.c; a();");
}
public void testInlineFunctionDeclaration() {
test("var f = function () {}; var a = f;",
"var a = function () {};");
test("var f = function () {}; foo(); var a = f;",
"foo(); var a = function () {};");
test("var f = function () {}; foo(f);",
"foo(function () {});");
testSame("var f = function () {}; function g() {var a = f;}");
testSame("var f = function () {}; function g() {h(f);}");
}
public void test2388531() {
testSame("var f = function () {};" +
"var g = function () {};" +
"goog.inherits(f, g);");
testSame("var f = function () {};" +
"var g = function () {};" +
"goog$inherits(f, g);");
}
public void testRecursiveFunction1() {
testSame("var x = 0; (function x() { return x ? x() : 3; })();");
}
public void testRecursiveFunction2() {
testSame("function y() { return y(); }");
}
public void testUnreferencedBleedingFunction() {
testSame("var x = function y() {}");
}
public void testReferencedBleedingFunction() {
testSame("var x = function y() { return y(); }");
}
public void testInlineAliases1() {
test("var x = this.foo(); this.bar(); var y = x; this.baz(y);",
"var x = this.foo(); this.bar(); this.baz(x);");
}
public void testInlineAliases1b() {
test("var x = this.foo(); this.bar(); var y; y = x; this.baz(y);",
"var x = this.foo(); this.bar(); x; this.baz(x);");
}
public void testInlineAliases1c() {
test("var x; x = this.foo(); this.bar(); var y = x; this.baz(y);",
"var x; x = this.foo(); this.bar(); this.baz(x);");
}
public void testInlineAliases1d() {
test("var x; x = this.foo(); this.bar(); var y; y = x; this.baz(y);",
"var x; x = this.foo(); this.bar(); x; this.baz(x);");
}
public void testInlineAliases2() {
test("var x = this.foo(); this.bar(); " +
"function f() { var y = x; this.baz(y); }",
"var x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliases2b() {
test("var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.baz(y); }",
"var x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliases2c() {
test("var x; x = this.foo(); this.bar(); " +
"function f() { var y = x; this.baz(y); }",
"var x; x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliases2d() {
test("var x; x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.baz(y); }",
"var x; x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliasesInLoop() {
test(
"function f() { " +
" var x = extern();" +
" for (var i = 0; i < 5; i++) {" +
" (function() {" +
" var y = x; window.setTimeout(function() { extern(y); }, 0);" +
" })();" +
" }" +
"}",
"function f() { " +
" var x = extern();" +
" for (var i = 0; i < 5; i++) {" +
" (function() {" +
" window.setTimeout(function() { extern(x); }, 0);" +
" })();" +
" }" +
"}");
}
public void testNoInlineAliasesInLoop() {
testSame(
"function f() { " +
" for (var i = 0; i < 5; i++) {" +
" var x = extern();" +
" (function() {" +
" var y = x; window.setTimeout(function() { extern(y); }, 0);" +
" })();" +
" }" +
"}");
}
public void testNoInlineAliases1() {
testSame(
"var x = this.foo(); this.bar(); var y = x; x = 3; this.baz(y);");
}
public void testNoInlineAliases1b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; x = 3; this.baz(y);");
}
public void testNoInlineAliases2() {
testSame(
"var x = this.foo(); this.bar(); var y = x; y = 3; this.baz(y); ");
}
public void testNoInlineAliases2b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; y = 3; this.baz(y); ");
}
public void testNoInlineAliases3() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; g(); this.baz(y); } " +
"function g() { x = 3; }");
}
public void testNoInlineAliases3b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; g(); this.baz(y); } " +
"function g() { x = 3; }");
}
public void testNoInlineAliases4() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; y = 3; this.baz(y); }");
}
public void testNoInlineAliases4b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; y = 3; this.baz(y); }");
}
public void testNoInlineAliases5() {
testSame(
"var x = this.foo(); this.bar(); var y = x; this.bing();" +
"this.baz(y); x = 3;");
}
public void testNoInlineAliases5b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; this.bing();" +
"this.baz(y); x = 3;");
}
public void testNoInlineAliases6() {
testSame(
"var x = this.foo(); this.bar(); var y = x; this.bing();" +
"this.baz(y); y = 3;");
}
public void testNoInlineAliases6b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; this.bing();" +
"this.baz(y); y = 3;");
}
public void testNoInlineAliases7() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; this.bing(); this.baz(y); x = 3; }");
}
public void testNoInlineAliases7b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.bing(); this.baz(y); x = 3; }");
}
public void testNoInlineAliases8() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; this.baz(y); y = 3; }");
}
public void testNoInlineAliases8b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.baz(y); y = 3; }");
}
public void testSideEffectOrder() {
// z can not be changed by the call to y, so x can be inlined.
String EXTERNS = "var z; function f(){}";
test(EXTERNS,
"var x = f(y.a, y); z = x;",
"z = f(y.a, y);", null, null);
// z.b can be changed by the call to y, so x can not be inlined.
testSame(EXTERNS, "var x = f(y.a, y); z.b = x;", null, null);
}
public void testInlineParameterAlias1() {
test(
"function f(x) {" +
" var y = x;" +
" g();" +
" y;y;" +
"}",
"function f(x) {" +
" g();" +
" x;x;" +
"}"
);
}
public void testInlineParameterAlias2() {
test(
"function f(x) {" +
" var y; y = x;" +
" g();" +
" y;y;" +
"}",
"function f(x) {" +
" x;" +
" g();" +
" x;x;" +
"}"
);
}
public void testInlineFunctionAlias1a() {
test(
"function f(x) {}" +
"var y = f;" +
"g();" +
"y();y();",
"var y = function f(x) {};" +
"g();" +
"y();y();"
);
}
public void testInlineFunctionAlias1b() {
test(
"function f(x) {};" +
"f;var y = f;" +
"g();" +
"y();y();",
"function f(x) {};" +
"f;g();" +
"f();f();"
);
}
public void testInlineFunctionAlias2a() {
test(
"function f(x) {}" +
"var y; y = f;" +
"g();" +
"y();y();",
"var y; y = function f(x) {};" +
"g();" +
"y();y();"
);
}
public void testInlineFunctionAlias2b() {
test(
"function f(x) {};" +
"f; var y; y = f;" +
"g();" +
"y();y();",
"function f(x) {};" +
"f; f;" +
"g();" +
"f();f();"
);
}
public void testInlineCatchAlias1() {
test(
"try {" +
"} catch (e) {" +
" var y = e;" +
" g();" +
" y;y;" +
"}",
"try {" +
"} catch (e) {" +
" g();" +
" e;e;" +
"}"
);
}
public void testInlineCatchAlias2() {
test(
"try {" +
"} catch (e) {" +
" var y; y = e;" +
" g();" +
" y;y;" +
"}",
"try {" +
"} catch (e) {" +
" e;" +
" g();" +
" e;e;" +
"}"
);
}
public void testLocalsOnly1() {
inlineLocalsOnly = true;
test(
"var x=1; x; function f() {var x = 1; x;}",
"var x=1; x; function f() {1;}");
}
public void testLocalsOnly2() {
inlineLocalsOnly = true;
test(
"/** @const */\n" +
"var X=1; X;\n" +
"function f() {\n" +
" /** @const */\n" +
" var X = 1; X;\n" +
"}",
"var X=1; X; function f() {1;}");
}
public void testInlineUndefined1() {
test("var x; x;",
"void 0;");
}
public void testInlineUndefined2() {
testSame("var x; x++;");
}
public void testInlineUndefined3() {
testSame("var x; var x;");
}
public void testInlineUndefined4() {
test("var x; x; x;",
"void 0; void 0;");
}
public void testInlineUndefined5() {
test("var x; for(x in a) {}",
"var x; for(x in a) {}");
}
public void testIssue90() {
test("var x; x && alert(1)",
"void 0 && alert(1)");
}
public void testRenamePropertyFunction() {
testSame("var JSCompiler_renameProperty; " +
"JSCompiler_renameProperty('foo')");
}
public void testThisAlias() {
test("function f() { var a = this; a.y(); a.z(); }",
"function f() { this.y(); this.z(); }");
}
public void testThisEscapedAlias() {
testSame(
"function f() { var a = this; var g = function() { a.y(); }; a.z(); }");
}
public void testInlineNamedFunction() {
test("function f() {} f();", "(function f(){})()");
}
public void testIssue378ModifiedArguments1() {
testSame(
"function g(callback) {\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
"}");
}
public void testIssue378ModifiedArguments2() {
testSame(
"function g(callback) {\n" +
" /** @const */\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
"}");
}
public void testIssue378EscapedArguments1() {
testSame(
"function g(callback) {\n" +
" var f = callback;\n" +
" h(arguments,this);\n" +
" f.apply(this, arguments);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testIssue378EscapedArguments2() {
testSame(
"function g(callback) {\n" +
" /** @const */\n" +
" var f = callback;\n" +
" h(arguments,this);\n" +
" f.apply(this);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testIssue378EscapedArguments3() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" f.apply(this, arguments);\n" +
"}\n",
"function g(callback) {\n" +
" callback.apply(this, arguments);\n" +
"}\n");
}
public void testIssue378EscapedArguments4() {
testSame(
"function g(callback) {\n" +
" var f = callback;\n" +
" h(arguments[0],this);\n" +
" f.apply(this, arguments);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testIssue378ArgumentsRead1() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" var g = arguments[0];\n" +
" f.apply(this, arguments);\n" +
"}",
"function g(callback) {\n" +
" var g = arguments[0];\n" +
" callback.apply(this, arguments);\n" +
"}");
}
public void testIssue378ArgumentsRead2() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" h(arguments[0],this);\n" +
" f.apply(this, arguments[0]);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}",
"function g(callback) {\n" +
" h(arguments[0],this);\n" +
" callback.apply(this, arguments[0]);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testArgumentsModifiedInOuterFunction() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
" function inner(callback) {" +
" var x = callback;\n" +
" x.apply(this);\n" +
" }" +
"}",
"function g(callback) {\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
" function inner(callback) {" +
" callback.apply(this);\n" +
" }" +
"}");
}
public void testArgumentsModifiedInInnerFunction() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" f.apply(this, arguments);\n" +
" function inner(callback) {" +
" var x = callback;\n" +
" arguments[0] = this;\n" +
" x.apply(this);\n" +
" }" +
"}",
"function g(callback) {\n" +
" callback.apply(this, arguments);\n" +
" function inner(callback) {" +
" var x = callback;\n" +
" arguments[0] = this;\n" +
" x.apply(this);\n" +
" }" +
"}");
}
public void testNoInlineRedeclaredExterns() {
String externs = "var test = 1;";
String code = "/** @suppress {duplicate} */ var test = 2;alert(test);";
test(externs, code, code, null, null);
}
public void testBug6598844() {
testSame(
"function F() { this.a = 0; }" +
"F.prototype.inc = function() { this.a++; return 10; };" +
"F.prototype.bar = function() { var x = this.inc(); this.a += x; };");
}
public void testExternalIssue1053() {
testSame(
"var u; function f() { u = Random(); var x = u; f(); alert(x===u)}");
}
} | // You are a professional Java test case writer, please create a test case named `testExternalIssue1053` for the issue `Closure-1053`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-1053
//
// ## Issue-Title:
// Overzealous optimization confuses variables
//
// ## Issue-Description:
// The following code:
//
// // ==ClosureCompiler==
// // @compilation\_level ADVANCED\_OPTIMIZATIONS
// // ==/ClosureCompiler==
// var uid;
// function reset() {
// uid = Math.random();
// }
// function doStuff() {
// reset();
// var \_uid = uid;
//
// if (uid < 0.5) {
// doStuff();
// }
//
// if (\_uid !== uid) {
// throw 'reset() was called';
// }
// }
// doStuff();
//
// ...gets optimized to:
//
// var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b();
//
// Notice how \_uid gets optimized away and (uid!==\_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from \_uid.
//
// As an aside, replacing the declaration with "var \_uid = +uid;" fixes it, as does adding an extra "uid = \_uid" after "var \_uid = uid".
//
//
public void testExternalIssue1053() {
| 1,070 | 121 | 1,067 | test/com/google/javascript/jscomp/InlineVariablesTest.java | test | ```markdown
## Issue-ID: Closure-1053
## Issue-Title:
Overzealous optimization confuses variables
## Issue-Description:
The following code:
// ==ClosureCompiler==
// @compilation\_level ADVANCED\_OPTIMIZATIONS
// ==/ClosureCompiler==
var uid;
function reset() {
uid = Math.random();
}
function doStuff() {
reset();
var \_uid = uid;
if (uid < 0.5) {
doStuff();
}
if (\_uid !== uid) {
throw 'reset() was called';
}
}
doStuff();
...gets optimized to:
var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b();
Notice how \_uid gets optimized away and (uid!==\_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from \_uid.
As an aside, replacing the declaration with "var \_uid = +uid;" fixes it, as does adding an extra "uid = \_uid" after "var \_uid = uid".
```
You are a professional Java test case writer, please create a test case named `testExternalIssue1053` for the issue `Closure-1053`, utilizing the provided issue report information and the following function signature.
```java
public void testExternalIssue1053() {
```
| 1,067 | [
"com.google.javascript.jscomp.InlineVariables"
] | 6800127fc4e69929b8a51694a75d7bc9d712a75b01886b8f554c11b166efce27 | public void testExternalIssue1053() | // You are a professional Java test case writer, please create a test case named `testExternalIssue1053` for the issue `Closure-1053`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-1053
//
// ## Issue-Title:
// Overzealous optimization confuses variables
//
// ## Issue-Description:
// The following code:
//
// // ==ClosureCompiler==
// // @compilation\_level ADVANCED\_OPTIMIZATIONS
// // ==/ClosureCompiler==
// var uid;
// function reset() {
// uid = Math.random();
// }
// function doStuff() {
// reset();
// var \_uid = uid;
//
// if (uid < 0.5) {
// doStuff();
// }
//
// if (\_uid !== uid) {
// throw 'reset() was called';
// }
// }
// doStuff();
//
// ...gets optimized to:
//
// var a;function b(){a=Math.random();0.5>a&&b();if(a!==a)throw"reset() was called";}b();
//
// Notice how \_uid gets optimized away and (uid!==\_uid) becomes (a!==a) even though doStuff() might have been called and uid's value may have changed and become different from \_uid.
//
// As an aside, replacing the declaration with "var \_uid = +uid;" fixes it, as does adding an extra "uid = \_uid" after "var \_uid = uid".
//
//
| 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;
/**
* Verifies that valid candidates for inlining are inlined, but
* that no dangerous inlining occurs.
*
* @author kushal@google.com (Kushal Dave)
*/
public class InlineVariablesTest extends CompilerTestCase {
private boolean inlineAllStrings = false;
private boolean inlineLocalsOnly = false;
public InlineVariablesTest() {
enableNormalize();
}
@Override
public void setUp() {
super.enableLineNumberCheck(true);
}
@Override
protected CompilerPass getProcessor(final Compiler compiler) {
return new InlineVariables(
compiler,
(inlineLocalsOnly)
? InlineVariables.Mode.LOCALS_ONLY
: InlineVariables.Mode.ALL,
inlineAllStrings);
}
@Override
public void tearDown() {
inlineAllStrings = false;
inlineLocalsOnly = false;
}
// Test respect for scopes and blocks
public void testInlineGlobal() {
test("var x = 1; var z = x;", "var z = 1;");
}
public void testNoInlineExportedName() {
testSame("var _x = 1; var z = _x;");
}
public void testNoInlineExportedName2() {
testSame("var f = function() {}; var _x = f;" +
"var y = function() { _x(); }; var _y = f;");
}
public void testDoNotInlineIncrement() {
testSame("var x = 1; x++;");
}
public void testDoNotInlineDecrement() {
testSame("var x = 1; x--;");
}
public void testDoNotInlineIntoLhsOfAssign() {
testSame("var x = 1; x += 3;");
}
public void testInlineIntoRhsOfAssign() {
test("var x = 1; var y = x;", "var y = 1;");
}
public void testInlineInFunction() {
test("function baz() { var x = 1; var z = x; }",
"function baz() { var z = 1; }");
}
public void testInlineInFunction2() {
test("function baz() { " +
"var a = new obj();"+
"result = a;" +
"}",
"function baz() { " +
"result = new obj()" +
"}");
}
public void testInlineInFunction3() {
testSame(
"function baz() { " +
"var a = new obj();" +
"(function(){a;})();" +
"result = a;" +
"}");
}
public void testInlineInFunction4() {
testSame(
"function baz() { " +
"var a = new obj();" +
"foo.result = a;" +
"}");
}
public void testInlineInFunction5() {
testSame(
"function baz() { " +
"var a = (foo = new obj());" +
"foo.x();" +
"result = a;" +
"}");
}
public void testInlineAcrossModules() {
// TODO(kushal): Make decision about overlap with CrossModuleCodeMotion
test(createModules("var a = 2;", "var b = a;"),
new String[] { "", "var b = 2;" });
}
public void testDoNotExitConditional1() {
testSame("if (true) { var x = 1; } var z = x;");
}
public void testDoNotExitConditional2() {
testSame("if (true) var x = 1; var z = x;");
}
public void testDoNotExitConditional3() {
testSame("var x; if (true) x=1; var z = x;");
}
public void testDoNotExitLoop() {
testSame("while (z) { var x = 3; } var y = x;");
}
public void testDoNotExitForLoop() {
test("for (var i = 1; false; false) var z = i;",
"for (;false;false) var z = 1;");
testSame("for (; false; false) var i = 1; var z = i;");
testSame("for (var i in {}); var z = i;");
}
public void testDoNotEnterSubscope() {
testSame(
"var x = function() {" +
" var self = this; " +
" return function() { var y = self; };" +
"}");
testSame(
"var x = function() {" +
" var y = [1]; " +
" return function() { var z = y; };" +
"}");
}
public void testDoNotExitTry() {
testSame("try { var x = y; } catch (e) {} var z = y; ");
testSame("try { throw e; var x = 1; } catch (e) {} var z = x; ");
}
public void testDoNotEnterCatch() {
testSame("try { } catch (e) { var z = e; } ");
}
public void testDoNotEnterFinally() {
testSame("try { throw e; var x = 1; } catch (e) {} " +
"finally { var z = x; } ");
}
public void testInsideIfConditional() {
test("var a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }");
test("var a; a = foo(); if (a) { alert(3); }", "if (foo()) { alert(3); }");
}
public void testOnlyReadAtInitialization() {
test("var a; a = foo();", "foo();");
test("var a; if (a = foo()) { alert(3); }", "if (foo()) { alert(3); }");
test("var a; switch (a = foo()) {}", "switch(foo()) {}");
test("var a; function f(){ return a = foo(); }",
"function f(){ return foo(); }");
test("function f(){ var a; return a = foo(); }",
"function f(){ return foo(); }");
test("var a; with (a = foo()) { alert(3); }", "with (foo()) { alert(3); }");
test("var a; b = (a = foo());", "b = foo();");
test("var a; while(a = foo()) { alert(3); }",
"while(foo()) { alert(3); }");
test("var a; for(;a = foo();) { alert(3); }",
"for(;foo();) { alert(3); }");
test("var a; do {} while(a = foo()) { alert(3); }",
"do {} while(foo()) { alert(3); }");
}
public void testImmutableWithSingleReferenceAfterInitialzation() {
test("var a; a = 1;", "1;");
test("var a; if (a = 1) { alert(3); }", "if (1) { alert(3); }");
test("var a; switch (a = 1) {}", "switch(1) {}");
test("var a; function f(){ return a = 1; }",
"function f(){ return 1; }");
test("function f(){ var a; return a = 1; }",
"function f(){ return 1; }");
test("var a; with (a = 1) { alert(3); }", "with (1) { alert(3); }");
test("var a; b = (a = 1);", "b = 1;");
test("var a; while(a = 1) { alert(3); }",
"while(1) { alert(3); }");
test("var a; for(;a = 1;) { alert(3); }",
"for(;1;) { alert(3); }");
test("var a; do {} while(a = 1) { alert(3); }",
"do {} while(1) { alert(3); }");
}
public void testSingleReferenceAfterInitialzation() {
test("var a; a = foo();a;", "foo();");
testSame("var a; if (a = foo()) { alert(3); } a;");
testSame("var a; switch (a = foo()) {} a;");
testSame("var a; function f(){ return a = foo(); } a;");
testSame("function f(){ var a; return a = foo(); a;}");
testSame("var a; with (a = foo()) { alert(3); } a;");
testSame("var a; b = (a = foo()); a;");
testSame("var a; while(a = foo()) { alert(3); } a;");
testSame("var a; for(;a = foo();) { alert(3); } a;");
testSame("var a; do {} while(a = foo()) { alert(3); } a;");
}
public void testInsideIfBranch() {
testSame("var a = foo(); if (1) { alert(a); }");
}
public void testInsideAndConditional() {
test("var a = foo(); a && alert(3);", "foo() && alert(3);");
}
public void testInsideAndBranch() {
testSame("var a = foo(); 1 && alert(a);");
}
public void testInsideOrBranch() {
testSame("var a = foo(); 1 || alert(a);");
}
public void testInsideHookBranch() {
testSame("var a = foo(); 1 ? alert(a) : alert(3)");
}
public void testInsideHookConditional() {
test("var a = foo(); a ? alert(1) : alert(3)",
"foo() ? alert(1) : alert(3)");
}
public void testInsideOrBranchInsideIfConditional() {
testSame("var a = foo(); if (x || a) {}");
}
public void testInsideOrBranchInsideIfConditionalWithConstant() {
// We don't inline non-immutable constants into branches.
testSame("var a = [false]; if (x || a) {}");
}
public void testCrossFunctionsAsLeftLeaves() {
// Ensures getNext() understands how to walk past a function leaf
test(
new String[] { "var x = function() {};", "",
"function cow() {} var z = x;"},
new String[] { "", "", "function cow() {} var z = function() {};" });
test(
new String[] { "var x = function() {};", "",
"var cow = function() {}; var z = x;"},
new String[] { "", "",
"var cow = function() {}; var z = function() {};" });
testSame(
new String[] { "var x = a;", "",
"(function() { a++; })(); var z = x;"});
test(
new String[] { "var x = a;", "",
"function cow() { a++; }; cow(); var z = x;"},
new String[] { "var x = a;", "",
";(function cow(){ a++; })(); var z = x;"});
testSame(
new String[] { "var x = a;", "",
"cow(); var z = x; function cow() { a++; };"});
}
// Test movement of constant values
public void testDoCrossFunction() {
// We know foo() does not affect x because we require that x is only
// referenced twice.
test("var x = 1; foo(); var z = x;", "foo(); var z = 1;");
}
public void testDoNotCrossReferencingFunction() {
testSame(
"var f = function() { var z = x; };" +
"var x = 1;" +
"f();" +
"var z = x;" +
"f();");
}
// Test tricky declarations and references
public void testChainedAssignment() {
test("var a = 2, b = 2; var c = b;", "var a = 2; var c = 2;");
test("var a = 2, b = 2; var c = a;", "var b = 2; var c = 2;");
test("var a = b = 2; var f = 3; var c = a;", "var f = 3; var c = b = 2;");
testSame("var a = b = 2; var c = b;");
}
public void testForIn() {
testSame("for (var i in j) { var c = i; }");
testSame("var i = 0; for (i in j) ;");
testSame("var i = 0; for (i in j) { var c = i; }");
testSame("i = 0; for (var i in j) { var c = i; }");
testSame("var j = {'key':'value'}; for (var i in j) {print(i)};");
}
// Test movement of values that have (may) side effects
public void testDoCrossNewVariables() {
test("var x = foo(); var z = x;", "var z = foo();");
}
public void testDoNotCrossFunctionCalls() {
testSame("var x = foo(); bar(); var z = x;");
}
// Test movement of values that are complex but lack side effects
public void testDoNotCrossAssignment() {
testSame("var x = {}; var y = x.a; x.a = 1; var z = y;");
testSame("var a = this.id; foo(this.id = 3, a);");
}
public void testDoNotCrossDelete() {
testSame("var x = {}; var y = x.a; delete x.a; var z = y;");
}
public void testDoNotCrossAssignmentPlus() {
testSame("var a = b; b += 2; var c = a;");
}
public void testDoNotCrossIncrement() {
testSame("var a = b.c; b.c++; var d = a;");
}
public void testDoNotCrossConstructor() {
testSame("var a = b; new Foo(); var c = a;");
}
public void testDoCrossVar() {
// Assumes we do not rely on undefined variables (not technically correct!)
test("var a = b; var b = 3; alert(a)", "alert(3);");
}
public void testOverlappingInlines() {
String source =
"a = function(el, x, opt_y) { " +
" var cur = bar(el); " +
" opt_y = x.y; " +
" x = x.x; " +
" var dx = x - cur.x; " +
" var dy = opt_y - cur.y;" +
" foo(el, el.offsetLeft + dx, el.offsetTop + dy); " +
"};";
String expected =
"a = function(el, x, opt_y) { " +
" var cur = bar(el); " +
" opt_y = x.y; " +
" x = x.x; " +
" foo(el, el.offsetLeft + (x - cur.x)," +
" el.offsetTop + (opt_y - cur.y)); " +
"};";
test(source, expected);
}
public void testOverlappingInlineFunctions() {
String source =
"a = function() { " +
" var b = function(args) {var n;}; " +
" var c = function(args) {}; " +
" d(b,c); " +
"};";
String expected =
"a = function() { " +
" d(function(args){var n;}, function(args){}); " +
"};";
test(source, expected);
}
public void testInlineIntoLoops() {
test("var x = true; while (true) alert(x);",
"while (true) alert(true);");
test("var x = true; while (true) for (var i in {}) alert(x);",
"while (true) for (var i in {}) alert(true);");
testSame("var x = [true]; while (true) alert(x);");
}
public void testInlineIntoFunction() {
test("var x = false; var f = function() { alert(x); };",
"var f = function() { alert(false); };");
testSame("var x = [false]; var f = function() { alert(x); };");
}
public void testNoInlineIntoNamedFunction() {
testSame("f(); var x = false; function f() { alert(x); };");
}
public void testInlineIntoNestedNonHoistedNamedFunctions() {
test("f(); var x = false; if (false) function f() { alert(x); };",
"f(); if (false) function f() { alert(false); };");
}
public void testNoInlineIntoNestedNamedFunctions() {
testSame("f(); var x = false; function f() { if (false) { alert(x); } };");
}
public void testNoInlineMutatedVariable() {
testSame("var x = false; if (true) { var y = x; x = true; }");
}
public void testInlineImmutableMultipleTimes() {
test("var x = null; var y = x, z = x;",
"var y = null, z = null;");
test("var x = 3; var y = x, z = x;",
"var y = 3, z = 3;");
}
public void testNoInlineStringMultipleTimesIfNotWorthwhile() {
testSame("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;");
}
public void testInlineStringMultipleTimesWhenAliasingAllStrings() {
inlineAllStrings = true;
test("var x = 'abcdefghijklmnopqrstuvwxyz'; var y = x, z = x;",
"var y = 'abcdefghijklmnopqrstuvwxyz', " +
" z = 'abcdefghijklmnopqrstuvwxyz';");
}
public void testNoInlineBackwards() {
testSame("var y = x; var x = null;");
}
public void testNoInlineOutOfBranch() {
testSame("if (true) var x = null; var y = x;");
}
public void testInterferingInlines() {
test("var a = 3; var f = function() { var x = a; alert(x); };",
"var f = function() { alert(3); };");
}
public void testInlineIntoTryCatch() {
test("var a = true; " +
"try { var b = a; } " +
"catch (e) { var c = a + b; var d = true; } " +
"finally { var f = a + b + c + d; }",
"try { var b = true; } " +
"catch (e) { var c = true + b; var d = true; } " +
"finally { var f = true + b + c + d; }");
}
// Make sure that we still inline constants that are not provably
// written before they're read.
public void testInlineConstants() {
test("function foo() { return XXX; } var XXX = true;",
"function foo() { return true; }");
}
public void testInlineStringWhenWorthwhile() {
test("var x = 'a'; foo(x, x, x);", "foo('a', 'a', 'a');");
}
public void testInlineConstantAlias() {
test("var XXX = new Foo(); q(XXX); var YYY = XXX; bar(YYY)",
"var XXX = new Foo(); q(XXX); bar(XXX)");
}
public void testInlineConstantAliasWithAnnotation() {
test("/** @const */ var xxx = new Foo(); q(xxx); var YYY = xxx; bar(YYY)",
"/** @const */ var xxx = new Foo(); q(xxx); bar(xxx)");
}
public void testInlineConstantAliasWithNonConstant() {
test("var XXX = new Foo(); q(XXX); var y = XXX; bar(y); baz(y)",
"var XXX = new Foo(); q(XXX); bar(XXX); baz(XXX)");
}
public void testCascadingInlines() {
test("var XXX = 4; " +
"function f() { var YYY = XXX; bar(YYY); baz(YYY); }",
"function f() { bar(4); baz(4); }");
}
public void testNoInlineGetpropIntoCall() {
test("var a = b; a();", "b();");
test("var a = b.c; f(a);", "f(b.c);");
testSame("var a = b.c; a();");
}
public void testInlineFunctionDeclaration() {
test("var f = function () {}; var a = f;",
"var a = function () {};");
test("var f = function () {}; foo(); var a = f;",
"foo(); var a = function () {};");
test("var f = function () {}; foo(f);",
"foo(function () {});");
testSame("var f = function () {}; function g() {var a = f;}");
testSame("var f = function () {}; function g() {h(f);}");
}
public void test2388531() {
testSame("var f = function () {};" +
"var g = function () {};" +
"goog.inherits(f, g);");
testSame("var f = function () {};" +
"var g = function () {};" +
"goog$inherits(f, g);");
}
public void testRecursiveFunction1() {
testSame("var x = 0; (function x() { return x ? x() : 3; })();");
}
public void testRecursiveFunction2() {
testSame("function y() { return y(); }");
}
public void testUnreferencedBleedingFunction() {
testSame("var x = function y() {}");
}
public void testReferencedBleedingFunction() {
testSame("var x = function y() { return y(); }");
}
public void testInlineAliases1() {
test("var x = this.foo(); this.bar(); var y = x; this.baz(y);",
"var x = this.foo(); this.bar(); this.baz(x);");
}
public void testInlineAliases1b() {
test("var x = this.foo(); this.bar(); var y; y = x; this.baz(y);",
"var x = this.foo(); this.bar(); x; this.baz(x);");
}
public void testInlineAliases1c() {
test("var x; x = this.foo(); this.bar(); var y = x; this.baz(y);",
"var x; x = this.foo(); this.bar(); this.baz(x);");
}
public void testInlineAliases1d() {
test("var x; x = this.foo(); this.bar(); var y; y = x; this.baz(y);",
"var x; x = this.foo(); this.bar(); x; this.baz(x);");
}
public void testInlineAliases2() {
test("var x = this.foo(); this.bar(); " +
"function f() { var y = x; this.baz(y); }",
"var x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliases2b() {
test("var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.baz(y); }",
"var x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliases2c() {
test("var x; x = this.foo(); this.bar(); " +
"function f() { var y = x; this.baz(y); }",
"var x; x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliases2d() {
test("var x; x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.baz(y); }",
"var x; x = this.foo(); this.bar(); function f() { this.baz(x); }");
}
public void testInlineAliasesInLoop() {
test(
"function f() { " +
" var x = extern();" +
" for (var i = 0; i < 5; i++) {" +
" (function() {" +
" var y = x; window.setTimeout(function() { extern(y); }, 0);" +
" })();" +
" }" +
"}",
"function f() { " +
" var x = extern();" +
" for (var i = 0; i < 5; i++) {" +
" (function() {" +
" window.setTimeout(function() { extern(x); }, 0);" +
" })();" +
" }" +
"}");
}
public void testNoInlineAliasesInLoop() {
testSame(
"function f() { " +
" for (var i = 0; i < 5; i++) {" +
" var x = extern();" +
" (function() {" +
" var y = x; window.setTimeout(function() { extern(y); }, 0);" +
" })();" +
" }" +
"}");
}
public void testNoInlineAliases1() {
testSame(
"var x = this.foo(); this.bar(); var y = x; x = 3; this.baz(y);");
}
public void testNoInlineAliases1b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; x = 3; this.baz(y);");
}
public void testNoInlineAliases2() {
testSame(
"var x = this.foo(); this.bar(); var y = x; y = 3; this.baz(y); ");
}
public void testNoInlineAliases2b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; y = 3; this.baz(y); ");
}
public void testNoInlineAliases3() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; g(); this.baz(y); } " +
"function g() { x = 3; }");
}
public void testNoInlineAliases3b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; g(); this.baz(y); } " +
"function g() { x = 3; }");
}
public void testNoInlineAliases4() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; y = 3; this.baz(y); }");
}
public void testNoInlineAliases4b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; y = 3; this.baz(y); }");
}
public void testNoInlineAliases5() {
testSame(
"var x = this.foo(); this.bar(); var y = x; this.bing();" +
"this.baz(y); x = 3;");
}
public void testNoInlineAliases5b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; this.bing();" +
"this.baz(y); x = 3;");
}
public void testNoInlineAliases6() {
testSame(
"var x = this.foo(); this.bar(); var y = x; this.bing();" +
"this.baz(y); y = 3;");
}
public void testNoInlineAliases6b() {
testSame(
"var x = this.foo(); this.bar(); var y; y = x; this.bing();" +
"this.baz(y); y = 3;");
}
public void testNoInlineAliases7() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; this.bing(); this.baz(y); x = 3; }");
}
public void testNoInlineAliases7b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.bing(); this.baz(y); x = 3; }");
}
public void testNoInlineAliases8() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y = x; this.baz(y); y = 3; }");
}
public void testNoInlineAliases8b() {
testSame(
"var x = this.foo(); this.bar(); " +
"function f() { var y; y = x; this.baz(y); y = 3; }");
}
public void testSideEffectOrder() {
// z can not be changed by the call to y, so x can be inlined.
String EXTERNS = "var z; function f(){}";
test(EXTERNS,
"var x = f(y.a, y); z = x;",
"z = f(y.a, y);", null, null);
// z.b can be changed by the call to y, so x can not be inlined.
testSame(EXTERNS, "var x = f(y.a, y); z.b = x;", null, null);
}
public void testInlineParameterAlias1() {
test(
"function f(x) {" +
" var y = x;" +
" g();" +
" y;y;" +
"}",
"function f(x) {" +
" g();" +
" x;x;" +
"}"
);
}
public void testInlineParameterAlias2() {
test(
"function f(x) {" +
" var y; y = x;" +
" g();" +
" y;y;" +
"}",
"function f(x) {" +
" x;" +
" g();" +
" x;x;" +
"}"
);
}
public void testInlineFunctionAlias1a() {
test(
"function f(x) {}" +
"var y = f;" +
"g();" +
"y();y();",
"var y = function f(x) {};" +
"g();" +
"y();y();"
);
}
public void testInlineFunctionAlias1b() {
test(
"function f(x) {};" +
"f;var y = f;" +
"g();" +
"y();y();",
"function f(x) {};" +
"f;g();" +
"f();f();"
);
}
public void testInlineFunctionAlias2a() {
test(
"function f(x) {}" +
"var y; y = f;" +
"g();" +
"y();y();",
"var y; y = function f(x) {};" +
"g();" +
"y();y();"
);
}
public void testInlineFunctionAlias2b() {
test(
"function f(x) {};" +
"f; var y; y = f;" +
"g();" +
"y();y();",
"function f(x) {};" +
"f; f;" +
"g();" +
"f();f();"
);
}
public void testInlineCatchAlias1() {
test(
"try {" +
"} catch (e) {" +
" var y = e;" +
" g();" +
" y;y;" +
"}",
"try {" +
"} catch (e) {" +
" g();" +
" e;e;" +
"}"
);
}
public void testInlineCatchAlias2() {
test(
"try {" +
"} catch (e) {" +
" var y; y = e;" +
" g();" +
" y;y;" +
"}",
"try {" +
"} catch (e) {" +
" e;" +
" g();" +
" e;e;" +
"}"
);
}
public void testLocalsOnly1() {
inlineLocalsOnly = true;
test(
"var x=1; x; function f() {var x = 1; x;}",
"var x=1; x; function f() {1;}");
}
public void testLocalsOnly2() {
inlineLocalsOnly = true;
test(
"/** @const */\n" +
"var X=1; X;\n" +
"function f() {\n" +
" /** @const */\n" +
" var X = 1; X;\n" +
"}",
"var X=1; X; function f() {1;}");
}
public void testInlineUndefined1() {
test("var x; x;",
"void 0;");
}
public void testInlineUndefined2() {
testSame("var x; x++;");
}
public void testInlineUndefined3() {
testSame("var x; var x;");
}
public void testInlineUndefined4() {
test("var x; x; x;",
"void 0; void 0;");
}
public void testInlineUndefined5() {
test("var x; for(x in a) {}",
"var x; for(x in a) {}");
}
public void testIssue90() {
test("var x; x && alert(1)",
"void 0 && alert(1)");
}
public void testRenamePropertyFunction() {
testSame("var JSCompiler_renameProperty; " +
"JSCompiler_renameProperty('foo')");
}
public void testThisAlias() {
test("function f() { var a = this; a.y(); a.z(); }",
"function f() { this.y(); this.z(); }");
}
public void testThisEscapedAlias() {
testSame(
"function f() { var a = this; var g = function() { a.y(); }; a.z(); }");
}
public void testInlineNamedFunction() {
test("function f() {} f();", "(function f(){})()");
}
public void testIssue378ModifiedArguments1() {
testSame(
"function g(callback) {\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
"}");
}
public void testIssue378ModifiedArguments2() {
testSame(
"function g(callback) {\n" +
" /** @const */\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
"}");
}
public void testIssue378EscapedArguments1() {
testSame(
"function g(callback) {\n" +
" var f = callback;\n" +
" h(arguments,this);\n" +
" f.apply(this, arguments);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testIssue378EscapedArguments2() {
testSame(
"function g(callback) {\n" +
" /** @const */\n" +
" var f = callback;\n" +
" h(arguments,this);\n" +
" f.apply(this);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testIssue378EscapedArguments3() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" f.apply(this, arguments);\n" +
"}\n",
"function g(callback) {\n" +
" callback.apply(this, arguments);\n" +
"}\n");
}
public void testIssue378EscapedArguments4() {
testSame(
"function g(callback) {\n" +
" var f = callback;\n" +
" h(arguments[0],this);\n" +
" f.apply(this, arguments);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testIssue378ArgumentsRead1() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" var g = arguments[0];\n" +
" f.apply(this, arguments);\n" +
"}",
"function g(callback) {\n" +
" var g = arguments[0];\n" +
" callback.apply(this, arguments);\n" +
"}");
}
public void testIssue378ArgumentsRead2() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" h(arguments[0],this);\n" +
" f.apply(this, arguments[0]);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}",
"function g(callback) {\n" +
" h(arguments[0],this);\n" +
" callback.apply(this, arguments[0]);\n" +
"}\n" +
"function h(a,b) {\n" +
" a[0] = b;" +
"}");
}
public void testArgumentsModifiedInOuterFunction() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
" function inner(callback) {" +
" var x = callback;\n" +
" x.apply(this);\n" +
" }" +
"}",
"function g(callback) {\n" +
" var f = callback;\n" +
" arguments[0] = this;\n" +
" f.apply(this, arguments);\n" +
" function inner(callback) {" +
" callback.apply(this);\n" +
" }" +
"}");
}
public void testArgumentsModifiedInInnerFunction() {
test(
"function g(callback) {\n" +
" var f = callback;\n" +
" f.apply(this, arguments);\n" +
" function inner(callback) {" +
" var x = callback;\n" +
" arguments[0] = this;\n" +
" x.apply(this);\n" +
" }" +
"}",
"function g(callback) {\n" +
" callback.apply(this, arguments);\n" +
" function inner(callback) {" +
" var x = callback;\n" +
" arguments[0] = this;\n" +
" x.apply(this);\n" +
" }" +
"}");
}
public void testNoInlineRedeclaredExterns() {
String externs = "var test = 1;";
String code = "/** @suppress {duplicate} */ var test = 2;alert(test);";
test(externs, code, code, null, null);
}
public void testBug6598844() {
testSame(
"function F() { this.a = 0; }" +
"F.prototype.inc = function() { this.a++; return 10; };" +
"F.prototype.bar = function() { var x = this.inc(); this.a += x; };");
}
public void testExternalIssue1053() {
testSame(
"var u; function f() { u = Random(); var x = u; f(); alert(x===u)}");
}
} |
||
public void testLeapYearRulesConstruction() {
// 1500 not leap in Gregorian, but is leap in Julian
DateMidnight dt = new DateMidnight(1500, 2, 29, GJChronology.getInstanceUTC());
assertEquals(dt.getYear(), 1500);
assertEquals(dt.getMonthOfYear(), 2);
assertEquals(dt.getDayOfMonth(), 29);
} | org.joda.time.chrono.TestGJChronology::testLeapYearRulesConstruction | src/test/java/org/joda/time/chrono/TestGJChronology.java | 499 | src/test/java/org/joda/time/chrono/TestGJChronology.java | testLeapYearRulesConstruction | /*
* Copyright 2001-2005 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.chrono;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.DurationField;
import org.joda.time.DurationFieldType;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.Instant;
import org.joda.time.Period;
import org.joda.time.TimeOfDay;
import org.joda.time.YearMonthDay;
/**
* This class is a Junit unit test for GJChronology.
*
* @author Stephen Colebourne
*/
public class TestGJChronology extends TestCase {
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");
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;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestGJChronology.class);
}
public TestGJChronology(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);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testFactoryUTC() {
assertEquals(DateTimeZone.UTC, GJChronology.getInstanceUTC().getZone());
assertSame(GJChronology.class, GJChronology.getInstanceUTC().getClass());
}
public void testFactory() {
assertEquals(LONDON, GJChronology.getInstance().getZone());
assertSame(GJChronology.class, GJChronology.getInstance().getClass());
}
public void testFactory_Zone() {
assertEquals(TOKYO, GJChronology.getInstance(TOKYO).getZone());
assertEquals(PARIS, GJChronology.getInstance(PARIS).getZone());
assertEquals(LONDON, GJChronology.getInstance(null).getZone());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO).getClass());
}
public void testFactory_Zone_long_int() {
GJChronology chrono = GJChronology.getInstance(TOKYO, 0L, 2);
assertEquals(TOKYO, chrono.getZone());
assertEquals(new Instant(0L), chrono.getGregorianCutover());
assertEquals(2, chrono.getMinimumDaysInFirstWeek());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, 0L, 2).getClass());
try {
GJChronology.getInstance(TOKYO, 0L, 0);
fail();
} catch (IllegalArgumentException ex) {}
try {
GJChronology.getInstance(TOKYO, 0L, 8);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFactory_Zone_RI() {
GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L));
assertEquals(TOKYO, chrono.getZone());
assertEquals(new Instant(0L), chrono.getGregorianCutover());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L)).getClass());
DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC);
chrono = GJChronology.getInstance(TOKYO, null);
assertEquals(TOKYO, chrono.getZone());
assertEquals(cutover.toInstant(), chrono.getGregorianCutover());
}
public void testFactory_Zone_RI_int() {
GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L), 2);
assertEquals(TOKYO, chrono.getZone());
assertEquals(new Instant(0L), chrono.getGregorianCutover());
assertEquals(2, chrono.getMinimumDaysInFirstWeek());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L), 2).getClass());
DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC);
chrono = GJChronology.getInstance(TOKYO, null, 2);
assertEquals(TOKYO, chrono.getZone());
assertEquals(cutover.toInstant(), chrono.getGregorianCutover());
assertEquals(2, chrono.getMinimumDaysInFirstWeek());
try {
GJChronology.getInstance(TOKYO, new Instant(0L), 0);
fail();
} catch (IllegalArgumentException ex) {}
try {
GJChronology.getInstance(TOKYO, new Instant(0L), 8);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testEquality() {
assertSame(GJChronology.getInstance(TOKYO), GJChronology.getInstance(TOKYO));
assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(LONDON));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance(PARIS));
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstanceUTC());
assertSame(GJChronology.getInstance(), GJChronology.getInstance(LONDON));
}
public void testWithUTC() {
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance(LONDON).withUTC());
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance(TOKYO).withUTC());
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstanceUTC().withUTC());
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance().withUTC());
}
public void testWithZone() {
assertSame(GJChronology.getInstance(TOKYO), GJChronology.getInstance(TOKYO).withZone(TOKYO));
assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(TOKYO).withZone(LONDON));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance(TOKYO).withZone(PARIS));
assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(TOKYO).withZone(null));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance().withZone(PARIS));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstanceUTC().withZone(PARIS));
}
public void testToString() {
assertEquals("GJChronology[Europe/London]", GJChronology.getInstance(LONDON).toString());
assertEquals("GJChronology[Asia/Tokyo]", GJChronology.getInstance(TOKYO).toString());
assertEquals("GJChronology[Europe/London]", GJChronology.getInstance().toString());
assertEquals("GJChronology[UTC]", GJChronology.getInstanceUTC().toString());
assertEquals("GJChronology[UTC,cutover=1970-01-01]", GJChronology.getInstance(DateTimeZone.UTC, 0L, 4).toString());
assertEquals("GJChronology[UTC,cutover=1970-01-01T00:00:00.001Z,mdfw=2]", GJChronology.getInstance(DateTimeZone.UTC, 1L, 2).toString());
}
//-----------------------------------------------------------------------
public void testDurationFields() {
assertEquals("eras", GJChronology.getInstance().eras().getName());
assertEquals("centuries", GJChronology.getInstance().centuries().getName());
assertEquals("years", GJChronology.getInstance().years().getName());
assertEquals("weekyears", GJChronology.getInstance().weekyears().getName());
assertEquals("months", GJChronology.getInstance().months().getName());
assertEquals("weeks", GJChronology.getInstance().weeks().getName());
assertEquals("halfdays", GJChronology.getInstance().halfdays().getName());
assertEquals("days", GJChronology.getInstance().days().getName());
assertEquals("hours", GJChronology.getInstance().hours().getName());
assertEquals("minutes", GJChronology.getInstance().minutes().getName());
assertEquals("seconds", GJChronology.getInstance().seconds().getName());
assertEquals("millis", GJChronology.getInstance().millis().getName());
assertEquals(false, GJChronology.getInstance().eras().isSupported());
assertEquals(true, GJChronology.getInstance().centuries().isSupported());
assertEquals(true, GJChronology.getInstance().years().isSupported());
assertEquals(true, GJChronology.getInstance().weekyears().isSupported());
assertEquals(true, GJChronology.getInstance().months().isSupported());
assertEquals(true, GJChronology.getInstance().weeks().isSupported());
assertEquals(true, GJChronology.getInstance().days().isSupported());
assertEquals(true, GJChronology.getInstance().halfdays().isSupported());
assertEquals(true, GJChronology.getInstance().hours().isSupported());
assertEquals(true, GJChronology.getInstance().minutes().isSupported());
assertEquals(true, GJChronology.getInstance().seconds().isSupported());
assertEquals(true, GJChronology.getInstance().millis().isSupported());
assertEquals(false, GJChronology.getInstance().centuries().isPrecise());
assertEquals(false, GJChronology.getInstance().years().isPrecise());
assertEquals(false, GJChronology.getInstance().weekyears().isPrecise());
assertEquals(false, GJChronology.getInstance().months().isPrecise());
assertEquals(false, GJChronology.getInstance().weeks().isPrecise());
assertEquals(false, GJChronology.getInstance().days().isPrecise());
assertEquals(false, GJChronology.getInstance().halfdays().isPrecise());
assertEquals(true, GJChronology.getInstance().hours().isPrecise());
assertEquals(true, GJChronology.getInstance().minutes().isPrecise());
assertEquals(true, GJChronology.getInstance().seconds().isPrecise());
assertEquals(true, GJChronology.getInstance().millis().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().centuries().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().years().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().weekyears().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().months().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().weeks().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().days().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().halfdays().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().hours().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().minutes().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().seconds().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().millis().isPrecise());
DateTimeZone gmt = DateTimeZone.forID("Etc/GMT");
assertEquals(false, GJChronology.getInstance(gmt).centuries().isPrecise());
assertEquals(false, GJChronology.getInstance(gmt).years().isPrecise());
assertEquals(false, GJChronology.getInstance(gmt).weekyears().isPrecise());
assertEquals(false, GJChronology.getInstance(gmt).months().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).weeks().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).days().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).halfdays().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).hours().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).minutes().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).seconds().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).millis().isPrecise());
}
public void testDateFields() {
assertEquals("era", GJChronology.getInstance().era().getName());
assertEquals("centuryOfEra", GJChronology.getInstance().centuryOfEra().getName());
assertEquals("yearOfCentury", GJChronology.getInstance().yearOfCentury().getName());
assertEquals("yearOfEra", GJChronology.getInstance().yearOfEra().getName());
assertEquals("year", GJChronology.getInstance().year().getName());
assertEquals("monthOfYear", GJChronology.getInstance().monthOfYear().getName());
assertEquals("weekyearOfCentury", GJChronology.getInstance().weekyearOfCentury().getName());
assertEquals("weekyear", GJChronology.getInstance().weekyear().getName());
assertEquals("weekOfWeekyear", GJChronology.getInstance().weekOfWeekyear().getName());
assertEquals("dayOfYear", GJChronology.getInstance().dayOfYear().getName());
assertEquals("dayOfMonth", GJChronology.getInstance().dayOfMonth().getName());
assertEquals("dayOfWeek", GJChronology.getInstance().dayOfWeek().getName());
assertEquals(true, GJChronology.getInstance().era().isSupported());
assertEquals(true, GJChronology.getInstance().centuryOfEra().isSupported());
assertEquals(true, GJChronology.getInstance().yearOfCentury().isSupported());
assertEquals(true, GJChronology.getInstance().yearOfEra().isSupported());
assertEquals(true, GJChronology.getInstance().year().isSupported());
assertEquals(true, GJChronology.getInstance().monthOfYear().isSupported());
assertEquals(true, GJChronology.getInstance().weekyearOfCentury().isSupported());
assertEquals(true, GJChronology.getInstance().weekyear().isSupported());
assertEquals(true, GJChronology.getInstance().weekOfWeekyear().isSupported());
assertEquals(true, GJChronology.getInstance().dayOfYear().isSupported());
assertEquals(true, GJChronology.getInstance().dayOfMonth().isSupported());
assertEquals(true, GJChronology.getInstance().dayOfWeek().isSupported());
}
public void testTimeFields() {
assertEquals("halfdayOfDay", GJChronology.getInstance().halfdayOfDay().getName());
assertEquals("clockhourOfHalfday", GJChronology.getInstance().clockhourOfHalfday().getName());
assertEquals("hourOfHalfday", GJChronology.getInstance().hourOfHalfday().getName());
assertEquals("clockhourOfDay", GJChronology.getInstance().clockhourOfDay().getName());
assertEquals("hourOfDay", GJChronology.getInstance().hourOfDay().getName());
assertEquals("minuteOfDay", GJChronology.getInstance().minuteOfDay().getName());
assertEquals("minuteOfHour", GJChronology.getInstance().minuteOfHour().getName());
assertEquals("secondOfDay", GJChronology.getInstance().secondOfDay().getName());
assertEquals("secondOfMinute", GJChronology.getInstance().secondOfMinute().getName());
assertEquals("millisOfDay", GJChronology.getInstance().millisOfDay().getName());
assertEquals("millisOfSecond", GJChronology.getInstance().millisOfSecond().getName());
assertEquals(true, GJChronology.getInstance().halfdayOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().clockhourOfHalfday().isSupported());
assertEquals(true, GJChronology.getInstance().hourOfHalfday().isSupported());
assertEquals(true, GJChronology.getInstance().clockhourOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().hourOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().minuteOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().minuteOfHour().isSupported());
assertEquals(true, GJChronology.getInstance().secondOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().secondOfMinute().isSupported());
assertEquals(true, GJChronology.getInstance().millisOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().millisOfSecond().isSupported());
}
public void testIllegalDates() {
try {
new DateTime(1582, 10, 5, 0, 0, 0, 0, GJChronology.getInstance(DateTimeZone.UTC));
fail("Constructed illegal date");
} catch (IllegalArgumentException e) { /* good */ }
try {
new DateTime(1582, 10, 14, 0, 0, 0, 0, GJChronology.getInstance(DateTimeZone.UTC));
fail("Constructed illegal date");
} catch (IllegalArgumentException e) { /* good */ }
}
public void testParseEquivalence() {
testParse("1581-01-01T01:23:45.678", 1581, 1, 1, 1, 23, 45, 678);
testParse("1581-06-30", 1581, 6, 30, 0, 0, 0, 0);
testParse("1582-01-01T01:23:45.678", 1582, 1, 1, 1, 23, 45, 678);
testParse("1582-06-30T01:23:45.678", 1582, 6, 30, 1, 23, 45, 678);
testParse("1582-10-04", 1582, 10, 4, 0, 0, 0, 0);
testParse("1582-10-15", 1582, 10, 15, 0, 0, 0, 0);
testParse("1582-12-31", 1582, 12, 31, 0, 0, 0, 0);
testParse("1583-12-31", 1583, 12, 31, 0, 0, 0, 0);
}
private void testParse(String str,
int year, int month, int day,
int hour, int minute, int second, int millis) {
assertEquals(new DateTime(str, GJChronology.getInstance(DateTimeZone.UTC)),
new DateTime(year, month, day, hour, minute, second, millis,
GJChronology.getInstance(DateTimeZone.UTC)));
}
public void testCutoverAddYears() {
testAdd("1582-01-01", DurationFieldType.years(), 1, "1583-01-01");
testAdd("1582-02-15", DurationFieldType.years(), 1, "1583-02-15");
testAdd("1582-02-28", DurationFieldType.years(), 1, "1583-02-28");
testAdd("1582-03-01", DurationFieldType.years(), 1, "1583-03-01");
testAdd("1582-09-30", DurationFieldType.years(), 1, "1583-09-30");
testAdd("1582-10-01", DurationFieldType.years(), 1, "1583-10-01");
testAdd("1582-10-04", DurationFieldType.years(), 1, "1583-10-04");
testAdd("1582-10-15", DurationFieldType.years(), 1, "1583-10-15");
testAdd("1582-10-16", DurationFieldType.years(), 1, "1583-10-16");
// Leap years...
testAdd("1580-01-01", DurationFieldType.years(), 4, "1584-01-01");
testAdd("1580-02-29", DurationFieldType.years(), 4, "1584-02-29");
testAdd("1580-10-01", DurationFieldType.years(), 4, "1584-10-01");
testAdd("1580-10-10", DurationFieldType.years(), 4, "1584-10-10");
testAdd("1580-10-15", DurationFieldType.years(), 4, "1584-10-15");
testAdd("1580-12-31", DurationFieldType.years(), 4, "1584-12-31");
}
public void testCutoverAddWeekyears() {
testAdd("1582-W01-1", DurationFieldType.weekyears(), 1, "1583-W01-1");
testAdd("1582-W39-1", DurationFieldType.weekyears(), 1, "1583-W39-1");
testAdd("1583-W45-1", DurationFieldType.weekyears(), 1, "1584-W45-1");
// This test fails, but I'm not sure if its worth fixing. The date
// falls after the cutover, but in the cutover year. The add operation
// is performed completely within the gregorian calendar, with no
// crossing of the cutover. As a result, no special correction is
// applied. Since the full gregorian year of 1582 has a different week
// numbers than the full julian year of 1582, the week number is off by
// one after the addition.
//
//testAdd("1582-W42-1", DurationFieldType.weekyears(), 1, "1583-W42-1");
// Leap years...
testAdd("1580-W01-1", DurationFieldType.weekyears(), 4, "1584-W01-1");
testAdd("1580-W30-7", DurationFieldType.weekyears(), 4, "1584-W30-7");
testAdd("1580-W50-7", DurationFieldType.weekyears(), 4, "1584-W50-7");
}
public void testCutoverAddMonths() {
testAdd("1582-01-01", DurationFieldType.months(), 1, "1582-02-01");
testAdd("1582-01-01", DurationFieldType.months(), 6, "1582-07-01");
testAdd("1582-01-01", DurationFieldType.months(), 12, "1583-01-01");
testAdd("1582-11-15", DurationFieldType.months(), 1, "1582-12-15");
testAdd("1582-09-04", DurationFieldType.months(), 2, "1582-11-04");
testAdd("1582-09-05", DurationFieldType.months(), 2, "1582-11-05");
testAdd("1582-09-10", DurationFieldType.months(), 2, "1582-11-10");
testAdd("1582-09-15", DurationFieldType.months(), 2, "1582-11-15");
// Leap years...
testAdd("1580-01-01", DurationFieldType.months(), 48, "1584-01-01");
testAdd("1580-02-29", DurationFieldType.months(), 48, "1584-02-29");
testAdd("1580-10-01", DurationFieldType.months(), 48, "1584-10-01");
testAdd("1580-10-10", DurationFieldType.months(), 48, "1584-10-10");
testAdd("1580-10-15", DurationFieldType.months(), 48, "1584-10-15");
testAdd("1580-12-31", DurationFieldType.months(), 48, "1584-12-31");
}
public void testCutoverAddWeeks() {
testAdd("1582-01-01", DurationFieldType.weeks(), 1, "1582-01-08");
testAdd("1583-01-01", DurationFieldType.weeks(), 1, "1583-01-08");
// Weeks are precise, and so cutover is not ignored.
testAdd("1582-10-01", DurationFieldType.weeks(), 2, "1582-10-25");
testAdd("1582-W01-1", DurationFieldType.weeks(), 51, "1583-W01-1");
}
public void testCutoverAddDays() {
testAdd("1582-10-03", DurationFieldType.days(), 1, "1582-10-04");
testAdd("1582-10-04", DurationFieldType.days(), 1, "1582-10-15");
testAdd("1582-10-15", DurationFieldType.days(), 1, "1582-10-16");
testAdd("1582-09-30", DurationFieldType.days(), 10, "1582-10-20");
testAdd("1582-10-04", DurationFieldType.days(), 10, "1582-10-24");
testAdd("1582-10-15", DurationFieldType.days(), 10, "1582-10-25");
}
public void testYearEndAddDays() {
testAdd("1582-11-05", DurationFieldType.days(), 28, "1582-12-03");
testAdd("1582-12-05", DurationFieldType.days(), 28, "1583-01-02");
testAdd("2005-11-05", DurationFieldType.days(), 28, "2005-12-03");
testAdd("2005-12-05", DurationFieldType.days(), 28, "2006-01-02");
}
public void testSubtractDays() {
// This is a test for a bug in version 1.0. The dayOfMonth range
// duration field did not match the monthOfYear duration field. This
// caused an exception to be thrown when subtracting days.
DateTime dt = new DateTime
(1112306400000L, GJChronology.getInstance(DateTimeZone.forID("Europe/Berlin")));
YearMonthDay ymd = dt.toYearMonthDay();
while (ymd.toDateTimeAtMidnight().getDayOfWeek() != DateTimeConstants.MONDAY) {
ymd = ymd.minus(Period.days(1));
}
}
private void testAdd(String start, DurationFieldType type, int amt, String end) {
DateTime dtStart = new DateTime(start, GJChronology.getInstance(DateTimeZone.UTC));
DateTime dtEnd = new DateTime(end, GJChronology.getInstance(DateTimeZone.UTC));
assertEquals(dtEnd, dtStart.withFieldAdded(type, amt));
assertEquals(dtStart, dtEnd.withFieldAdded(type, -amt));
DurationField field = type.getField(GJChronology.getInstance(DateTimeZone.UTC));
int diff = field.getDifference(dtEnd.getMillis(), dtStart.getMillis());
assertEquals(amt, diff);
if (type == DurationFieldType.years() ||
type == DurationFieldType.months() ||
type == DurationFieldType.days()) {
YearMonthDay ymdStart = new YearMonthDay(start, GJChronology.getInstance(DateTimeZone.UTC));
YearMonthDay ymdEnd = new YearMonthDay(end, GJChronology.getInstance(DateTimeZone.UTC));
assertEquals(ymdEnd, ymdStart.withFieldAdded(type, amt));
assertEquals(ymdStart, ymdEnd.withFieldAdded(type, -amt));
}
}
public void testTimeOfDayAdd() {
TimeOfDay start = new TimeOfDay(12, 30, GJChronology.getInstance());
TimeOfDay end = new TimeOfDay(10, 30, GJChronology.getInstance());
assertEquals(end, start.plusHours(22));
assertEquals(start, end.minusHours(22));
assertEquals(end, start.plusMinutes(22 * 60));
assertEquals(start, end.minusMinutes(22 * 60));
}
public void testMaximumValue() {
DateMidnight dt = new DateMidnight(1570, 1, 1, GJChronology.getInstance());
while (dt.getYear() < 1590) {
dt = dt.plusDays(1);
YearMonthDay ymd = dt.toYearMonthDay();
assertEquals(dt.year().getMaximumValue(), ymd.year().getMaximumValue());
assertEquals(dt.monthOfYear().getMaximumValue(), ymd.monthOfYear().getMaximumValue());
assertEquals(dt.dayOfMonth().getMaximumValue(), ymd.dayOfMonth().getMaximumValue());
}
}
public void testPartialGetAsText() {
GJChronology chrono = GJChronology.getInstance(TOKYO);
assertEquals("January", new YearMonthDay("2005-01-01", chrono).monthOfYear().getAsText());
assertEquals("Jan", new YearMonthDay("2005-01-01", chrono).monthOfYear().getAsShortText());
}
public void testLeapYearRulesConstruction() {
// 1500 not leap in Gregorian, but is leap in Julian
DateMidnight dt = new DateMidnight(1500, 2, 29, GJChronology.getInstanceUTC());
assertEquals(dt.getYear(), 1500);
assertEquals(dt.getMonthOfYear(), 2);
assertEquals(dt.getDayOfMonth(), 29);
}
public void testLeapYearRulesConstructionInvalid() {
// 1500 not leap in Gregorian, but is leap in Julian
try {
new DateMidnight(1500, 2, 30, GJChronology.getInstanceUTC());
fail();
} catch (IllegalFieldValueException ex) {
// good
}
}
} | // You are a professional Java test case writer, please create a test case named `testLeapYearRulesConstruction` for the issue `Time-130`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-130
//
// ## Issue-Title:
// #130 GJChronology rejects valid Julian dates
//
//
//
//
//
// ## Issue-Description:
// Example:
//
//
// DateTime jdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, JulianChronology.getInstanceUTC()); // Valid.
//
// DateTime gjdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, GJChronology.getInstanceUTC()); // Invalid.
//
//
// The 2nd statement fails with "org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]".
//
//
// Given that I left the cutover date at the default (October 15, 1582), isn't 1500/02/29 a valid date in the GJChronology?
//
//
//
//
public void testLeapYearRulesConstruction() {
| 499 | 18 | 493 | src/test/java/org/joda/time/chrono/TestGJChronology.java | src/test/java | ```markdown
## Issue-ID: Time-130
## Issue-Title:
#130 GJChronology rejects valid Julian dates
## Issue-Description:
Example:
DateTime jdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, JulianChronology.getInstanceUTC()); // Valid.
DateTime gjdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, GJChronology.getInstanceUTC()); // Invalid.
The 2nd statement fails with "org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]".
Given that I left the cutover date at the default (October 15, 1582), isn't 1500/02/29 a valid date in the GJChronology?
```
You are a professional Java test case writer, please create a test case named `testLeapYearRulesConstruction` for the issue `Time-130`, utilizing the provided issue report information and the following function signature.
```java
public void testLeapYearRulesConstruction() {
```
| 493 | [
"org.joda.time.chrono.GJChronology"
] | 6848cf447fa392de16db9dbe5089ed657df74d3ec2bf27c72bc27ecae81dbcf1 | public void testLeapYearRulesConstruction() | // You are a professional Java test case writer, please create a test case named `testLeapYearRulesConstruction` for the issue `Time-130`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Time-130
//
// ## Issue-Title:
// #130 GJChronology rejects valid Julian dates
//
//
//
//
//
// ## Issue-Description:
// Example:
//
//
// DateTime jdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, JulianChronology.getInstanceUTC()); // Valid.
//
// DateTime gjdt = new DateTime(1500, 2, 29, 0, 0, 0, 0, GJChronology.getInstanceUTC()); // Invalid.
//
//
// The 2nd statement fails with "org.joda.time.IllegalFieldValueException: Value 29 for dayOfMonth must be in the range [1,28]".
//
//
// Given that I left the cutover date at the default (October 15, 1582), isn't 1500/02/29 a valid date in the GJChronology?
//
//
//
//
| Time | /*
* Copyright 2001-2005 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.chrono;
import java.util.Locale;
import java.util.TimeZone;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.DurationField;
import org.joda.time.DurationFieldType;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.Instant;
import org.joda.time.Period;
import org.joda.time.TimeOfDay;
import org.joda.time.YearMonthDay;
/**
* This class is a Junit unit test for GJChronology.
*
* @author Stephen Colebourne
*/
public class TestGJChronology extends TestCase {
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");
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;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestGJChronology.class);
}
public TestGJChronology(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);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(originalDateTimeZone);
TimeZone.setDefault(originalTimeZone);
Locale.setDefault(originalLocale);
originalDateTimeZone = null;
originalTimeZone = null;
originalLocale = null;
}
//-----------------------------------------------------------------------
public void testFactoryUTC() {
assertEquals(DateTimeZone.UTC, GJChronology.getInstanceUTC().getZone());
assertSame(GJChronology.class, GJChronology.getInstanceUTC().getClass());
}
public void testFactory() {
assertEquals(LONDON, GJChronology.getInstance().getZone());
assertSame(GJChronology.class, GJChronology.getInstance().getClass());
}
public void testFactory_Zone() {
assertEquals(TOKYO, GJChronology.getInstance(TOKYO).getZone());
assertEquals(PARIS, GJChronology.getInstance(PARIS).getZone());
assertEquals(LONDON, GJChronology.getInstance(null).getZone());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO).getClass());
}
public void testFactory_Zone_long_int() {
GJChronology chrono = GJChronology.getInstance(TOKYO, 0L, 2);
assertEquals(TOKYO, chrono.getZone());
assertEquals(new Instant(0L), chrono.getGregorianCutover());
assertEquals(2, chrono.getMinimumDaysInFirstWeek());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, 0L, 2).getClass());
try {
GJChronology.getInstance(TOKYO, 0L, 0);
fail();
} catch (IllegalArgumentException ex) {}
try {
GJChronology.getInstance(TOKYO, 0L, 8);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testFactory_Zone_RI() {
GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L));
assertEquals(TOKYO, chrono.getZone());
assertEquals(new Instant(0L), chrono.getGregorianCutover());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L)).getClass());
DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC);
chrono = GJChronology.getInstance(TOKYO, null);
assertEquals(TOKYO, chrono.getZone());
assertEquals(cutover.toInstant(), chrono.getGregorianCutover());
}
public void testFactory_Zone_RI_int() {
GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L), 2);
assertEquals(TOKYO, chrono.getZone());
assertEquals(new Instant(0L), chrono.getGregorianCutover());
assertEquals(2, chrono.getMinimumDaysInFirstWeek());
assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L), 2).getClass());
DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC);
chrono = GJChronology.getInstance(TOKYO, null, 2);
assertEquals(TOKYO, chrono.getZone());
assertEquals(cutover.toInstant(), chrono.getGregorianCutover());
assertEquals(2, chrono.getMinimumDaysInFirstWeek());
try {
GJChronology.getInstance(TOKYO, new Instant(0L), 0);
fail();
} catch (IllegalArgumentException ex) {}
try {
GJChronology.getInstance(TOKYO, new Instant(0L), 8);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testEquality() {
assertSame(GJChronology.getInstance(TOKYO), GJChronology.getInstance(TOKYO));
assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(LONDON));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance(PARIS));
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstanceUTC());
assertSame(GJChronology.getInstance(), GJChronology.getInstance(LONDON));
}
public void testWithUTC() {
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance(LONDON).withUTC());
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance(TOKYO).withUTC());
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstanceUTC().withUTC());
assertSame(GJChronology.getInstanceUTC(), GJChronology.getInstance().withUTC());
}
public void testWithZone() {
assertSame(GJChronology.getInstance(TOKYO), GJChronology.getInstance(TOKYO).withZone(TOKYO));
assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(TOKYO).withZone(LONDON));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance(TOKYO).withZone(PARIS));
assertSame(GJChronology.getInstance(LONDON), GJChronology.getInstance(TOKYO).withZone(null));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstance().withZone(PARIS));
assertSame(GJChronology.getInstance(PARIS), GJChronology.getInstanceUTC().withZone(PARIS));
}
public void testToString() {
assertEquals("GJChronology[Europe/London]", GJChronology.getInstance(LONDON).toString());
assertEquals("GJChronology[Asia/Tokyo]", GJChronology.getInstance(TOKYO).toString());
assertEquals("GJChronology[Europe/London]", GJChronology.getInstance().toString());
assertEquals("GJChronology[UTC]", GJChronology.getInstanceUTC().toString());
assertEquals("GJChronology[UTC,cutover=1970-01-01]", GJChronology.getInstance(DateTimeZone.UTC, 0L, 4).toString());
assertEquals("GJChronology[UTC,cutover=1970-01-01T00:00:00.001Z,mdfw=2]", GJChronology.getInstance(DateTimeZone.UTC, 1L, 2).toString());
}
//-----------------------------------------------------------------------
public void testDurationFields() {
assertEquals("eras", GJChronology.getInstance().eras().getName());
assertEquals("centuries", GJChronology.getInstance().centuries().getName());
assertEquals("years", GJChronology.getInstance().years().getName());
assertEquals("weekyears", GJChronology.getInstance().weekyears().getName());
assertEquals("months", GJChronology.getInstance().months().getName());
assertEquals("weeks", GJChronology.getInstance().weeks().getName());
assertEquals("halfdays", GJChronology.getInstance().halfdays().getName());
assertEquals("days", GJChronology.getInstance().days().getName());
assertEquals("hours", GJChronology.getInstance().hours().getName());
assertEquals("minutes", GJChronology.getInstance().minutes().getName());
assertEquals("seconds", GJChronology.getInstance().seconds().getName());
assertEquals("millis", GJChronology.getInstance().millis().getName());
assertEquals(false, GJChronology.getInstance().eras().isSupported());
assertEquals(true, GJChronology.getInstance().centuries().isSupported());
assertEquals(true, GJChronology.getInstance().years().isSupported());
assertEquals(true, GJChronology.getInstance().weekyears().isSupported());
assertEquals(true, GJChronology.getInstance().months().isSupported());
assertEquals(true, GJChronology.getInstance().weeks().isSupported());
assertEquals(true, GJChronology.getInstance().days().isSupported());
assertEquals(true, GJChronology.getInstance().halfdays().isSupported());
assertEquals(true, GJChronology.getInstance().hours().isSupported());
assertEquals(true, GJChronology.getInstance().minutes().isSupported());
assertEquals(true, GJChronology.getInstance().seconds().isSupported());
assertEquals(true, GJChronology.getInstance().millis().isSupported());
assertEquals(false, GJChronology.getInstance().centuries().isPrecise());
assertEquals(false, GJChronology.getInstance().years().isPrecise());
assertEquals(false, GJChronology.getInstance().weekyears().isPrecise());
assertEquals(false, GJChronology.getInstance().months().isPrecise());
assertEquals(false, GJChronology.getInstance().weeks().isPrecise());
assertEquals(false, GJChronology.getInstance().days().isPrecise());
assertEquals(false, GJChronology.getInstance().halfdays().isPrecise());
assertEquals(true, GJChronology.getInstance().hours().isPrecise());
assertEquals(true, GJChronology.getInstance().minutes().isPrecise());
assertEquals(true, GJChronology.getInstance().seconds().isPrecise());
assertEquals(true, GJChronology.getInstance().millis().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().centuries().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().years().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().weekyears().isPrecise());
assertEquals(false, GJChronology.getInstanceUTC().months().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().weeks().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().days().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().halfdays().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().hours().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().minutes().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().seconds().isPrecise());
assertEquals(true, GJChronology.getInstanceUTC().millis().isPrecise());
DateTimeZone gmt = DateTimeZone.forID("Etc/GMT");
assertEquals(false, GJChronology.getInstance(gmt).centuries().isPrecise());
assertEquals(false, GJChronology.getInstance(gmt).years().isPrecise());
assertEquals(false, GJChronology.getInstance(gmt).weekyears().isPrecise());
assertEquals(false, GJChronology.getInstance(gmt).months().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).weeks().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).days().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).halfdays().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).hours().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).minutes().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).seconds().isPrecise());
assertEquals(true, GJChronology.getInstance(gmt).millis().isPrecise());
}
public void testDateFields() {
assertEquals("era", GJChronology.getInstance().era().getName());
assertEquals("centuryOfEra", GJChronology.getInstance().centuryOfEra().getName());
assertEquals("yearOfCentury", GJChronology.getInstance().yearOfCentury().getName());
assertEquals("yearOfEra", GJChronology.getInstance().yearOfEra().getName());
assertEquals("year", GJChronology.getInstance().year().getName());
assertEquals("monthOfYear", GJChronology.getInstance().monthOfYear().getName());
assertEquals("weekyearOfCentury", GJChronology.getInstance().weekyearOfCentury().getName());
assertEquals("weekyear", GJChronology.getInstance().weekyear().getName());
assertEquals("weekOfWeekyear", GJChronology.getInstance().weekOfWeekyear().getName());
assertEquals("dayOfYear", GJChronology.getInstance().dayOfYear().getName());
assertEquals("dayOfMonth", GJChronology.getInstance().dayOfMonth().getName());
assertEquals("dayOfWeek", GJChronology.getInstance().dayOfWeek().getName());
assertEquals(true, GJChronology.getInstance().era().isSupported());
assertEquals(true, GJChronology.getInstance().centuryOfEra().isSupported());
assertEquals(true, GJChronology.getInstance().yearOfCentury().isSupported());
assertEquals(true, GJChronology.getInstance().yearOfEra().isSupported());
assertEquals(true, GJChronology.getInstance().year().isSupported());
assertEquals(true, GJChronology.getInstance().monthOfYear().isSupported());
assertEquals(true, GJChronology.getInstance().weekyearOfCentury().isSupported());
assertEquals(true, GJChronology.getInstance().weekyear().isSupported());
assertEquals(true, GJChronology.getInstance().weekOfWeekyear().isSupported());
assertEquals(true, GJChronology.getInstance().dayOfYear().isSupported());
assertEquals(true, GJChronology.getInstance().dayOfMonth().isSupported());
assertEquals(true, GJChronology.getInstance().dayOfWeek().isSupported());
}
public void testTimeFields() {
assertEquals("halfdayOfDay", GJChronology.getInstance().halfdayOfDay().getName());
assertEquals("clockhourOfHalfday", GJChronology.getInstance().clockhourOfHalfday().getName());
assertEquals("hourOfHalfday", GJChronology.getInstance().hourOfHalfday().getName());
assertEquals("clockhourOfDay", GJChronology.getInstance().clockhourOfDay().getName());
assertEquals("hourOfDay", GJChronology.getInstance().hourOfDay().getName());
assertEquals("minuteOfDay", GJChronology.getInstance().minuteOfDay().getName());
assertEquals("minuteOfHour", GJChronology.getInstance().minuteOfHour().getName());
assertEquals("secondOfDay", GJChronology.getInstance().secondOfDay().getName());
assertEquals("secondOfMinute", GJChronology.getInstance().secondOfMinute().getName());
assertEquals("millisOfDay", GJChronology.getInstance().millisOfDay().getName());
assertEquals("millisOfSecond", GJChronology.getInstance().millisOfSecond().getName());
assertEquals(true, GJChronology.getInstance().halfdayOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().clockhourOfHalfday().isSupported());
assertEquals(true, GJChronology.getInstance().hourOfHalfday().isSupported());
assertEquals(true, GJChronology.getInstance().clockhourOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().hourOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().minuteOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().minuteOfHour().isSupported());
assertEquals(true, GJChronology.getInstance().secondOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().secondOfMinute().isSupported());
assertEquals(true, GJChronology.getInstance().millisOfDay().isSupported());
assertEquals(true, GJChronology.getInstance().millisOfSecond().isSupported());
}
public void testIllegalDates() {
try {
new DateTime(1582, 10, 5, 0, 0, 0, 0, GJChronology.getInstance(DateTimeZone.UTC));
fail("Constructed illegal date");
} catch (IllegalArgumentException e) { /* good */ }
try {
new DateTime(1582, 10, 14, 0, 0, 0, 0, GJChronology.getInstance(DateTimeZone.UTC));
fail("Constructed illegal date");
} catch (IllegalArgumentException e) { /* good */ }
}
public void testParseEquivalence() {
testParse("1581-01-01T01:23:45.678", 1581, 1, 1, 1, 23, 45, 678);
testParse("1581-06-30", 1581, 6, 30, 0, 0, 0, 0);
testParse("1582-01-01T01:23:45.678", 1582, 1, 1, 1, 23, 45, 678);
testParse("1582-06-30T01:23:45.678", 1582, 6, 30, 1, 23, 45, 678);
testParse("1582-10-04", 1582, 10, 4, 0, 0, 0, 0);
testParse("1582-10-15", 1582, 10, 15, 0, 0, 0, 0);
testParse("1582-12-31", 1582, 12, 31, 0, 0, 0, 0);
testParse("1583-12-31", 1583, 12, 31, 0, 0, 0, 0);
}
private void testParse(String str,
int year, int month, int day,
int hour, int minute, int second, int millis) {
assertEquals(new DateTime(str, GJChronology.getInstance(DateTimeZone.UTC)),
new DateTime(year, month, day, hour, minute, second, millis,
GJChronology.getInstance(DateTimeZone.UTC)));
}
public void testCutoverAddYears() {
testAdd("1582-01-01", DurationFieldType.years(), 1, "1583-01-01");
testAdd("1582-02-15", DurationFieldType.years(), 1, "1583-02-15");
testAdd("1582-02-28", DurationFieldType.years(), 1, "1583-02-28");
testAdd("1582-03-01", DurationFieldType.years(), 1, "1583-03-01");
testAdd("1582-09-30", DurationFieldType.years(), 1, "1583-09-30");
testAdd("1582-10-01", DurationFieldType.years(), 1, "1583-10-01");
testAdd("1582-10-04", DurationFieldType.years(), 1, "1583-10-04");
testAdd("1582-10-15", DurationFieldType.years(), 1, "1583-10-15");
testAdd("1582-10-16", DurationFieldType.years(), 1, "1583-10-16");
// Leap years...
testAdd("1580-01-01", DurationFieldType.years(), 4, "1584-01-01");
testAdd("1580-02-29", DurationFieldType.years(), 4, "1584-02-29");
testAdd("1580-10-01", DurationFieldType.years(), 4, "1584-10-01");
testAdd("1580-10-10", DurationFieldType.years(), 4, "1584-10-10");
testAdd("1580-10-15", DurationFieldType.years(), 4, "1584-10-15");
testAdd("1580-12-31", DurationFieldType.years(), 4, "1584-12-31");
}
public void testCutoverAddWeekyears() {
testAdd("1582-W01-1", DurationFieldType.weekyears(), 1, "1583-W01-1");
testAdd("1582-W39-1", DurationFieldType.weekyears(), 1, "1583-W39-1");
testAdd("1583-W45-1", DurationFieldType.weekyears(), 1, "1584-W45-1");
// This test fails, but I'm not sure if its worth fixing. The date
// falls after the cutover, but in the cutover year. The add operation
// is performed completely within the gregorian calendar, with no
// crossing of the cutover. As a result, no special correction is
// applied. Since the full gregorian year of 1582 has a different week
// numbers than the full julian year of 1582, the week number is off by
// one after the addition.
//
//testAdd("1582-W42-1", DurationFieldType.weekyears(), 1, "1583-W42-1");
// Leap years...
testAdd("1580-W01-1", DurationFieldType.weekyears(), 4, "1584-W01-1");
testAdd("1580-W30-7", DurationFieldType.weekyears(), 4, "1584-W30-7");
testAdd("1580-W50-7", DurationFieldType.weekyears(), 4, "1584-W50-7");
}
public void testCutoverAddMonths() {
testAdd("1582-01-01", DurationFieldType.months(), 1, "1582-02-01");
testAdd("1582-01-01", DurationFieldType.months(), 6, "1582-07-01");
testAdd("1582-01-01", DurationFieldType.months(), 12, "1583-01-01");
testAdd("1582-11-15", DurationFieldType.months(), 1, "1582-12-15");
testAdd("1582-09-04", DurationFieldType.months(), 2, "1582-11-04");
testAdd("1582-09-05", DurationFieldType.months(), 2, "1582-11-05");
testAdd("1582-09-10", DurationFieldType.months(), 2, "1582-11-10");
testAdd("1582-09-15", DurationFieldType.months(), 2, "1582-11-15");
// Leap years...
testAdd("1580-01-01", DurationFieldType.months(), 48, "1584-01-01");
testAdd("1580-02-29", DurationFieldType.months(), 48, "1584-02-29");
testAdd("1580-10-01", DurationFieldType.months(), 48, "1584-10-01");
testAdd("1580-10-10", DurationFieldType.months(), 48, "1584-10-10");
testAdd("1580-10-15", DurationFieldType.months(), 48, "1584-10-15");
testAdd("1580-12-31", DurationFieldType.months(), 48, "1584-12-31");
}
public void testCutoverAddWeeks() {
testAdd("1582-01-01", DurationFieldType.weeks(), 1, "1582-01-08");
testAdd("1583-01-01", DurationFieldType.weeks(), 1, "1583-01-08");
// Weeks are precise, and so cutover is not ignored.
testAdd("1582-10-01", DurationFieldType.weeks(), 2, "1582-10-25");
testAdd("1582-W01-1", DurationFieldType.weeks(), 51, "1583-W01-1");
}
public void testCutoverAddDays() {
testAdd("1582-10-03", DurationFieldType.days(), 1, "1582-10-04");
testAdd("1582-10-04", DurationFieldType.days(), 1, "1582-10-15");
testAdd("1582-10-15", DurationFieldType.days(), 1, "1582-10-16");
testAdd("1582-09-30", DurationFieldType.days(), 10, "1582-10-20");
testAdd("1582-10-04", DurationFieldType.days(), 10, "1582-10-24");
testAdd("1582-10-15", DurationFieldType.days(), 10, "1582-10-25");
}
public void testYearEndAddDays() {
testAdd("1582-11-05", DurationFieldType.days(), 28, "1582-12-03");
testAdd("1582-12-05", DurationFieldType.days(), 28, "1583-01-02");
testAdd("2005-11-05", DurationFieldType.days(), 28, "2005-12-03");
testAdd("2005-12-05", DurationFieldType.days(), 28, "2006-01-02");
}
public void testSubtractDays() {
// This is a test for a bug in version 1.0. The dayOfMonth range
// duration field did not match the monthOfYear duration field. This
// caused an exception to be thrown when subtracting days.
DateTime dt = new DateTime
(1112306400000L, GJChronology.getInstance(DateTimeZone.forID("Europe/Berlin")));
YearMonthDay ymd = dt.toYearMonthDay();
while (ymd.toDateTimeAtMidnight().getDayOfWeek() != DateTimeConstants.MONDAY) {
ymd = ymd.minus(Period.days(1));
}
}
private void testAdd(String start, DurationFieldType type, int amt, String end) {
DateTime dtStart = new DateTime(start, GJChronology.getInstance(DateTimeZone.UTC));
DateTime dtEnd = new DateTime(end, GJChronology.getInstance(DateTimeZone.UTC));
assertEquals(dtEnd, dtStart.withFieldAdded(type, amt));
assertEquals(dtStart, dtEnd.withFieldAdded(type, -amt));
DurationField field = type.getField(GJChronology.getInstance(DateTimeZone.UTC));
int diff = field.getDifference(dtEnd.getMillis(), dtStart.getMillis());
assertEquals(amt, diff);
if (type == DurationFieldType.years() ||
type == DurationFieldType.months() ||
type == DurationFieldType.days()) {
YearMonthDay ymdStart = new YearMonthDay(start, GJChronology.getInstance(DateTimeZone.UTC));
YearMonthDay ymdEnd = new YearMonthDay(end, GJChronology.getInstance(DateTimeZone.UTC));
assertEquals(ymdEnd, ymdStart.withFieldAdded(type, amt));
assertEquals(ymdStart, ymdEnd.withFieldAdded(type, -amt));
}
}
public void testTimeOfDayAdd() {
TimeOfDay start = new TimeOfDay(12, 30, GJChronology.getInstance());
TimeOfDay end = new TimeOfDay(10, 30, GJChronology.getInstance());
assertEquals(end, start.plusHours(22));
assertEquals(start, end.minusHours(22));
assertEquals(end, start.plusMinutes(22 * 60));
assertEquals(start, end.minusMinutes(22 * 60));
}
public void testMaximumValue() {
DateMidnight dt = new DateMidnight(1570, 1, 1, GJChronology.getInstance());
while (dt.getYear() < 1590) {
dt = dt.plusDays(1);
YearMonthDay ymd = dt.toYearMonthDay();
assertEquals(dt.year().getMaximumValue(), ymd.year().getMaximumValue());
assertEquals(dt.monthOfYear().getMaximumValue(), ymd.monthOfYear().getMaximumValue());
assertEquals(dt.dayOfMonth().getMaximumValue(), ymd.dayOfMonth().getMaximumValue());
}
}
public void testPartialGetAsText() {
GJChronology chrono = GJChronology.getInstance(TOKYO);
assertEquals("January", new YearMonthDay("2005-01-01", chrono).monthOfYear().getAsText());
assertEquals("Jan", new YearMonthDay("2005-01-01", chrono).monthOfYear().getAsShortText());
}
public void testLeapYearRulesConstruction() {
// 1500 not leap in Gregorian, but is leap in Julian
DateMidnight dt = new DateMidnight(1500, 2, 29, GJChronology.getInstanceUTC());
assertEquals(dt.getYear(), 1500);
assertEquals(dt.getMonthOfYear(), 2);
assertEquals(dt.getDayOfMonth(), 29);
}
public void testLeapYearRulesConstructionInvalid() {
// 1500 not leap in Gregorian, but is leap in Julian
try {
new DateMidnight(1500, 2, 30, GJChronology.getInstanceUTC());
fail();
} catch (IllegalFieldValueException ex) {
// good
}
}
} |
||
@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));
} | org.apache.commons.math3.fraction.FractionTest::testMath835 | src/test/java/org/apache/commons/math3/fraction/FractionTest.java | 253 | src/test/java/org/apache/commons/math3/fraction/FractionTest.java | testMath835 | /*
* 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);
}
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 `testMath835` for the issue `Math-MATH-835`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-835
//
// ## Issue-Title:
// Fraction percentageValue rare overflow
//
// ## Issue-Description:
//
// The percentageValue() method of the Fraction class works by first multiplying the Fraction by 100, then converting the Fraction to a double. This causes overflows when the numerator is greater than Integer.MAX\_VALUE/100, even when the value of the fraction is far below this value.
//
//
// The patch changes the method to first convert to a double value, and then multiply this value by 100 - the result should be the same, but with less overflows. An addition to the test for the method that covers this bug is also included.
//
//
//
//
//
@Test
public void testMath835() {
| 253 | 27 | 244 | src/test/java/org/apache/commons/math3/fraction/FractionTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-835
## Issue-Title:
Fraction percentageValue rare overflow
## Issue-Description:
The percentageValue() method of the Fraction class works by first multiplying the Fraction by 100, then converting the Fraction to a double. This causes overflows when the numerator is greater than Integer.MAX\_VALUE/100, even when the value of the fraction is far below this value.
The patch changes the method to first convert to a double value, and then multiply this value by 100 - the result should be the same, but with less overflows. An addition to the test for the method that covers this bug is also included.
```
You are a professional Java test case writer, please create a test case named `testMath835` for the issue `Math-MATH-835`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testMath835() {
```
| 244 | [
"org.apache.commons.math3.fraction.Fraction"
] | 6876a313dfb88c3640a4aa6d3933d53308768bfd8117cd65ae85021ec9ad507d | @Test
public void testMath835() | // You are a professional Java test case writer, please create a test case named `testMath835` for the issue `Math-MATH-835`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-835
//
// ## Issue-Title:
// Fraction percentageValue rare overflow
//
// ## Issue-Description:
//
// The percentageValue() method of the Fraction class works by first multiplying the Fraction by 100, then converting the Fraction to a double. This causes overflows when the numerator is greater than Integer.MAX\_VALUE/100, even when the value of the fraction is far below this value.
//
//
// The patch changes the method to first convert to a double value, and then multiply this value by 100 - the result should be the same, but with less overflows. An addition to the test for the method that covers this bug is also included.
//
//
//
//
//
| 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);
}
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 testSimpleFunctionCall() {
test("var a = String(23)", "var a = '' + 23");
test("var a = String('hello')", "var a = '' + 'hello'");
testSame("var a = String('hello', bar());");
testSame("var a = String({valueOf: function() { return 1; }});");
} | com.google.javascript.jscomp.PeepholeSubstituteAlternateSyntaxTest::testSimpleFunctionCall | test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java | 1,032 | test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java | testSimpleFunctionCall | /*
* 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;
/**
* Tests for {@link PeepholeSubstituteAlternateSyntax} in isolation.
* Tests for the interaction of multiple peephole passes are in
* PeepholeIntegrationTest.
*/
public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase {
// Externs for built-in constructors
// Needed for testFoldLiteralObjectConstructors(),
// testFoldLiteralArrayConstructors() and testFoldRegExp...()
private static final String FOLD_CONSTANTS_TEST_EXTERNS =
"var Object = function f(){};\n" +
"var RegExp = function f(a){};\n" +
"var Array = function f(a){};\n";
private boolean late = true;
// TODO(user): Remove this when we no longer need to do string comparison.
private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) {
super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree);
}
public PeepholeSubstituteAlternateSyntaxTest() {
super(FOLD_CONSTANTS_TEST_EXTERNS);
}
@Override
public void setUp() throws Exception {
late = true;
super.setUp();
enableLineNumberCheck(true);
disableNormalize();
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
CompilerPass peepholePass =
new PeepholeOptimizationsPass(compiler,
new PeepholeSubstituteAlternateSyntax(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);
}
void assertResultString(String js, String expected) {
assertResultString(js, expected, false);
}
// 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.
void assertResultString(String js, String expected, boolean normalize) {
PeepholeSubstituteAlternateSyntaxTest scTest
= new PeepholeSubstituteAlternateSyntaxTest(false);
if (normalize) {
scTest.enableNormalize();
} else {
scTest.disableNormalize();
}
scTest.test(js, expected);
}
/** Check that removing blocks with 1 child works */
public void testFoldOneChildBlocks() {
late = false;
fold("function f(){if(x)a();x=3}",
"function f(){x&&a();x=3}");
fold("function f(){if(x){a()}x=3}",
"function f(){x&&a();x=3}");
fold("function f(){if(x){return 3}}",
"function f(){if(x)return 3}");
fold("function f(){if(x){a()}}",
"function f(){x&&a()}");
fold("function f(){if(x){throw 1}}", "function f(){if(x)throw 1;}");
// Try it out with functions
fold("function f(){if(x){foo()}}", "function f(){x&&foo()}");
fold("function f(){if(x){foo()}else{bar()}}",
"function f(){x?foo():bar()}");
// Try it out with properties and methods
fold("function f(){if(x){a.b=1}}", "function f(){if(x)a.b=1}");
fold("function f(){if(x){a.b*=1}}", "function f(){x&&(a.b*=1)}");
fold("function f(){if(x){a.b+=1}}", "function f(){x&&(a.b+=1)}");
fold("function f(){if(x){++a.b}}", "function f(){x&&++a.b}");
fold("function f(){if(x){a.foo()}}", "function f(){x&&a.foo()}");
// Try it out with throw/catch/finally [which should not change]
fold("function f(){try{foo()}catch(e){bar(e)}finally{baz()}}",
"function f(){try{foo()}catch(e){bar(e)}finally{baz()}}");
// Try it out with switch statements
fold("function f(){switch(x){case 1:break}}",
"function f(){switch(x){case 1:break}}");
// Do while loops stay in a block if that's where they started
fold("function f(){if(e1){do foo();while(e2)}else foo2()}",
"function f(){if(e1){do foo();while(e2)}else foo2()}");
// Test an obscure case with do and while
fold("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
// Play with nested IFs
fold("function f(){if(x){if(y)foo()}}",
"function f(){x&&y&&foo()}");
fold("function f(){if(x){if(y)foo();else bar()}}",
"function f(){x&&(y?foo():bar())}");
fold("function f(){if(x){if(y)foo()}else bar()}",
"function f(){x?y&&foo():bar()}");
fold("function f(){if(x){if(y)foo();else bar()}else{baz()}}",
"function f(){x?y?foo():bar():baz()}");
fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
"if(e1)while(e2)e3&&foo();else bar()");
fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
"if(e1)with(e2)e3&&foo();else bar()");
fold("if(a||b){if(c||d){var x;}}", "if(a||b)if(c||d)var x");
fold("if(x){ if(y){var x;}else{var z;} }",
"if(x)if(y)var x;else var z");
// NOTE - technically we can remove the blocks since both the parent
// and child have elses. But we don't since it causes ambiguities in
// some cases where not all descendent ifs having elses
fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
"if(x)if(y)var x;else var z;else var w");
fold("if (x) {var x;}else { if (y) { var y;} }",
"if(x)var x;else if(y)var y");
// Here's some of the ambiguous cases
fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
"if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
fold("function f(){foo()}", "function f(){foo()}");
fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
fold("try{foo()}catch(ex){bar()}finally{baz()}",
"try{foo()}catch(ex){bar()}finally{baz()}");
}
/** Try to minimize returns */
public void testFoldReturns() {
fold("function f(){if(x)return 1;else return 2}",
"function f(){return x?1:2}");
fold("function f(){if(x)return 1;return 2}",
"function f(){return x?1:2}");
fold("function f(){if(x)return;return 2}",
"function f(){return x?void 0:2}");
fold("function f(){if(x)return 1+x;else return 2-x}",
"function f(){return x?1+x:2-x}");
fold("function f(){if(x)return 1+x;return 2-x}",
"function f(){return x?1+x:2-x}");
fold("function f(){if(x)return y += 1;else return y += 2}",
"function f(){return x?(y+=1):(y+=2)}");
fold("function f(){if(x)return;else return 2-x}",
"function f(){if(x);else return 2-x}");
fold("function f(){if(x)return;return 2-x}",
"function f(){return x?void 0:2-x}");
fold("function f(){if(x)return x;else return}",
"function f(){if(x)return x;{}}");
fold("function f(){if(x)return x;return}",
"function f(){if(x)return x}");
foldSame("function f(){for(var x in y) { return x.y; } return k}");
}
public void testCombineIfs1() {
fold("function f() {if (x) return 1; if (y) return 1}",
"function f() {if (x||y) return 1;}");
fold("function f() {if (x) return 1; if (y) foo(); else return 1}",
"function f() {if ((!x)&&y) foo(); else return 1;}");
}
public void testCombineIfs2() {
// combinable but not yet done
foldSame("function f() {if (x) throw 1; if (y) throw 1}");
// Can't combine, side-effect
fold("function f(){ if (x) g(); if (y) g() }",
"function f(){ x&&g(); y&&g() }");
// Can't combine, side-effect
fold("function f(){ if (x) y = 0; if (y) y = 0; }",
"function f(){ x&&(y = 0); y&&(y = 0); }");
}
public void testCombineIfs3() {
foldSame("function f() {if (x) return 1; if (y) {g();f()}}");
}
/** Try to minimize assignments */
public void testFoldAssignments() {
fold("function f(){if(x)y=3;else y=4;}", "function f(){y=x?3:4}");
fold("function f(){if(x)y=1+a;else y=2+a;}", "function f(){y=x?1+a:2+a}");
// and operation assignments
fold("function f(){if(x)y+=1;else y+=2;}", "function f(){y+=x?1:2}");
fold("function f(){if(x)y-=1;else y-=2;}", "function f(){y-=x?1:2}");
fold("function f(){if(x)y%=1;else y%=2;}", "function f(){y%=x?1:2}");
fold("function f(){if(x)y|=1;else y|=2;}", "function f(){y|=x?1:2}");
// sanity check, don't fold if the 2 ops don't match
foldSame("function f(){x ? y-=1 : y+=2}");
// sanity check, don't fold if the 2 LHS don't match
foldSame("function f(){x ? y-=1 : z-=1}");
// sanity check, don't fold if there are potential effects
foldSame("function f(){x ? y().a=3 : y().a=4}");
}
public void testRemoveDuplicateStatements() {
fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
"x=(a) ? 1 : 2; x++");
fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
" else { x = 2; x++; y += 1; z = pi; }",
"x=(a) ? 1 : 2; x++; y += 1; z = pi;");
fold("function z() {" +
"if (a) { foo(); return !0 } else { goo(); return !0 }" +
"}",
"function z() {(a) ? foo() : goo(); return !0}");
fold("function z() {if (a) { foo(); x = true; return true " +
"} else { goo(); x = true; return true }}",
"function z() {(a) ? foo() : goo(); x = !0; return !0}");
fold("function z() {" +
" if (a) { bar(); foo(); return true }" +
" else { bar(); goo(); return true }" +
"}",
"function z() {" +
" if (a) { bar(); foo(); }" +
" else { bar(); goo(); }" +
" return !0;" +
"}");
}
public void testNotCond() {
fold("function f(){if(!x)foo()}", "function f(){x||foo()}");
fold("function f(){if(!x)b=1}", "function f(){x||(b=1)}");
fold("if(!x)z=1;else if(y)z=2", "x ? y&&(z=2) : z=1");
foldSame("function f(){if(!(x=1))a.b=1}");
}
public void testAndParenthesesCount() {
fold("function f(){if(x||y)a.foo()}", "function f(){(x||y)&&a.foo()}");
fold("function f(){if(x.a)x.a=0}",
"function f(){x.a&&(x.a=0)}");
foldSame("function f(){if(x()||y()){x()||y()}}");
}
public void testFoldLogicalOpStringCompare() {
// side-effects
// There is two way to parse two &&'s and both are correct.
assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
}
public void testFoldNot() {
fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
// Because !(x<NaN) != x>=NaN don't fold < and > cases.
foldSame("while(!(x>y)){a=b;}");
foldSame("while(!(x>=y)){a=b;}");
foldSame("while(!(x<y)){a=b;}");
foldSame("while(!(x<=y)){a=b;}");
foldSame("while(!(x<=NaN)){a=b;}");
// NOT forces a boolean context
fold("x = !(y() && true)", "x = !y()");
// This will be further optimized by PeepholeFoldConstants.
fold("x = !true", "x = !1");
}
public void testFoldRegExpConstructor() {
enableNormalize();
// Cannot fold all the way to a literal because there are too few arguments.
fold("x = new RegExp", "x = RegExp()");
// Empty regexp should not fold to // since that is a line comment in JS
fold("x = new RegExp(\"\")", "x = RegExp(\"\")");
fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")");
// Bogus flags should not fold
fold("x = new RegExp(\"foobar\", \"bogus\")",
"x = RegExp(\"foobar\",\"bogus\")",
PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS);
// Can Fold
fold("x = new RegExp(\"foobar\")", "x = /foobar/");
fold("x = RegExp(\"foobar\")", "x = /foobar/");
fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
// Make sure that escaping works
fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"[/]\", \"\")", "x = /[/]/");
fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"\\n\")", "x = /\\n/");
fold("x = new RegExp('\\\\\\r')", "x = /\\r/");
// Don't fold really long regexp literals, because Opera 9.2's
// regexp parser will explode.
String longRegexp = "";
for (int i = 0; i < 200; i++) longRegexp += "x";
foldSame("x = RegExp(\"" + longRegexp + "\")");
// Shouldn't fold RegExp unnormalized because
// we can't be sure that RegExp hasn't been redefined
disableNormalize();
foldSame("x = new RegExp(\"foobar\")");
}
public void testVersionSpecificRegExpQuirks() {
enableNormalize();
// Don't fold if the flags contain 'g'
enableEcmaScript5(false);
fold("x = new RegExp(\"foobar\", \"g\")",
"x = RegExp(\"foobar\",\"g\")");
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = RegExp(\"foobar\",\"ig\")");
// ... unless in ECMAScript 5 mode per section 7.8.5 of ECMAScript 5.
enableEcmaScript5(true);
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = /foobar/ig");
// Don't fold things that crash older versions of Safari and that don't work
// as regex literals on other old versions of Safari
enableEcmaScript5(false);
fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
// Sunset Safari exclusions for ECMAScript 5 and later.
enableEcmaScript5(true);
fold("x = new RegExp(\"\\u2028\\u2029\")", "x = /\\u2028\\u2029/");
fold("x = new RegExp(\"\\\\u2028\")", "x = /\\u2028/");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
}
public void testFoldRegExpConstructorStringCompare() {
// Might have something to do with the internal representation of \n and how
// it is used in node comparison.
assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true);
}
public void testContainsUnicodeEscape() throws Exception {
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(""));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\\u2028"));
assertTrue(
PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028"));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028bar\\u2028"));
}
public void testFoldLiteralObjectConstructors() {
enableNormalize();
// Can fold when normalized
fold("x = new Object", "x = ({})");
fold("x = new Object()", "x = ({})");
fold("x = Object()", "x = ({})");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Object");
foldSame("x = new Object()");
foldSame("x = Object()");
enableNormalize();
// Cannot fold, the constructor being used is actually a local function
foldSame("x = " +
"(function f(){function Object(){this.x=4};return new Object();})();");
}
public void testFoldLiteralArrayConstructors() {
enableNormalize();
// No arguments - can fold when normalized
fold("x = new Array", "x = []");
fold("x = new Array()", "x = []");
fold("x = Array()", "x = []");
// One argument - can be fold when normalized
fold("x = new Array(0)", "x = []");
fold("x = Array(0)", "x = []");
fold("x = new Array(\"a\")", "x = [\"a\"]");
fold("x = Array(\"a\")", "x = [\"a\"]");
// One argument - cannot be fold when normalized
fold("x = new Array(7)", "x = Array(7)");
fold("x = Array(7)", "x = Array(7)");
fold("x = new Array(y)", "x = Array(y)");
fold("x = Array(y)", "x = Array(y)");
fold("x = new Array(foo())", "x = Array(foo())");
fold("x = Array(foo())", "x = Array(foo())");
// More than one argument - can be fold when normalized
fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]]");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Array");
foldSame("x = new Array()");
foldSame("x = Array()");
foldSame("x = new Array(0)");
foldSame("x = Array(0)");
foldSame("x = new Array(\"a\")");
foldSame("x = Array(\"a\")");
foldSame("x = new Array(7)");
foldSame("x = Array(7)");
foldSame("x = new Array(foo())");
foldSame("x = Array(foo())");
foldSame("x = new Array(1, 2, 3, 4)");
foldSame("x = Array(1, 2, 3, 4)");
foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = new Array(Array(1, '2', 3, '4'))");
foldSame("x = Array(Array(1, '2', 3, '4'))");
foldSame("x = new Array(" +
"Object(), Array(\"abc\", Object(), Array(Array())))");
foldSame("x = new Array(" +
"Object(), Array(\"abc\", Object(), Array(Array())))");
}
public void testMinimizeExprCondition() {
fold("(x ? true : false) && y()", "x&&y()");
fold("(x ? false : true) && y()", "(!x)&&y()");
fold("(x ? true : y) && y()", "(x || y)&&y()");
fold("(x ? y : false) && y()", "(x && y)&&y()");
fold("(x && true) && y()", "x && y()");
fold("(x && false) && y()", "0&&y()");
fold("(x || true) && y()", "1&&y()");
fold("(x || false) && y()", "x&&y()");
}
public void testMinimizeWhileCondition() {
// This test uses constant folding logic, so is only here for completeness.
fold("while(!!true) foo()", "while(1) foo()");
// These test tryMinimizeCondition
fold("while(!!x) foo()", "while(x) foo()");
fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
fold("while(x||!!y) foo()", "while(x||y) foo()");
fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()");
fold("while(!(!x&&y)) foo()", "while(x||!y) foo()");
fold("while(!(x||!y)) foo()", "while(!x&&y) foo()");
fold("while(!(x||y)) foo()", "while(!x&&!y) foo()");
fold("while(!(!x||y-z)) foo()", "while(x&&!(y-z)) foo()");
fold("while(!(!(x/y)||z+w)) foo()", "while(x/y&&!(z+w)) foo()");
foldSame("while(!(x+y||z)) foo()");
foldSame("while(!(x&&y*z)) foo()");
fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()");
fold("while(x&&!0) foo()", "while(x) foo()");
fold("while(x||!1) foo()", "while(x) foo()");
fold("while(!((x,y)&&z)) foo()", "while(!(x,y)||!z) foo()");
}
public void testMinimizeForCondition() {
// This test uses constant folding logic, so is only here for completeness.
// These could be simplified to "for(;;) ..."
fold("for(;!!true;) foo()", "for(;1;) foo()");
// Don't bother with FOR inits as there are normalized out.
fold("for(!!true;;) foo()", "for(!0;;) foo()");
// These test tryMinimizeCondition
fold("for(;!!x;) foo()", "for(;x;) foo()");
// sanity check
foldSame("for(a in b) foo()");
foldSame("for(a in {}) foo()");
foldSame("for(a in []) foo()");
fold("for(a in !!true) foo()", "for(a in !0) foo()");
}
public void testMinimizeCondition_example1() {
// Based on a real failing code sample.
fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
}
public void testFoldLoopBreakLate() {
late = true;
fold("for(;;) if (a) break", "for(;!a;);");
foldSame("for(;;) if (a) { f(); break }");
fold("for(;;) if (a) break; else f()", "for(;!a;) { { f(); } }");
fold("for(;a;) if (b) break", "for(;a && !b;);");
fold("for(;a;) { if (b) break; if (c) break; }", "for(;(a && !b) && !c;);");
// 'while' is normalized to 'for'
enableNormalize(true);
fold("while(true) if (a) break", "for(;1&&!a;);");
}
public void testFoldLoopBreakEarly() {
late = false;
foldSame("for(;;) if (a) break");
foldSame("for(;;) if (a) { f(); break }");
foldSame("for(;;) if (a) break; else f()");
foldSame("for(;a;) if (b) break");
foldSame("for(;a;) { if (b) break; if (c) break; }");
foldSame("while(1) if (a) break");
enableNormalize(true);
foldSame("while(1) if (a) break");
}
public void testFoldConditionalVarDeclaration() {
fold("if(x) var y=1;else y=2", "var y=x?1:2");
fold("if(x) y=1;else var y=2", "var y=x?1:2");
foldSame("if(x) var y = 1; z = 2");
foldSame("if(x||y) y = 1; var z = 2");
foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
foldSame("if(x) var y = 1; else {y = 2; print(y)}");
}
public void testFoldReturnResult() {
fold("function f(){return false;}", "function f(){return !1}");
foldSame("function f(){return null;}");
fold("function f(){return void 0;}",
"function f(){}");
foldSame("function f(){return void foo();}");
fold("function f(){return undefined;}",
"function f(){}");
fold("function f(){if(a()){return undefined;}}",
"function f(){if(a()){}}");
}
public void testFoldStandardConstructors() {
foldSame("new Foo('a')");
foldSame("var x = new goog.Foo(1)");
foldSame("var x = new String(1)");
foldSame("var x = new Number(1)");
foldSame("var x = new Boolean(1)");
enableNormalize();
fold("var x = new Object('a')", "var x = Object('a')");
fold("var x = new RegExp('')", "var x = RegExp('')");
fold("var x = new Error('20')", "var x = Error(\"20\")");
fold("var x = new Array(20)", "var x = Array(20)");
}
public void testSubsituteReturn() {
fold("function f() { while(x) { return }}",
"function f() { while(x) { break }}");
foldSame("function f() { while(x) { return 5 } }");
foldSame("function f() { a: { return 5 } }");
fold("function f() { while(x) { return 5} return 5}",
"function f() { while(x) { break } return 5}");
fold("function f() { while(x) { return x} return x}",
"function f() { while(x) { break } return x}");
fold("function f() { while(x) { if (y) { return }}}",
"function f() { while(x) { if (y) { break }}}");
fold("function f() { while(x) { if (y) { return }} return}",
"function f() { while(x) { if (y) { break }}}");
fold("function f() { while(x) { if (y) { return 5 }} return 5}",
"function f() { while(x) { if (y) { break }} return 5}");
// It doesn't matter if x is changed between them. We are still returning
// x at whatever x value current holds. The whole x = 1 is skipped.
fold("function f() { while(x) { if (y) { return x } x = 1} return x}",
"function f() { while(x) { if (y) { break } x = 1} return x}");
// RemoveUnreachableCode would take care of the useless breaks.
fold("function f() { while(x) { if (y) { return x } return x} return x}",
"function f() { while(x) { if (y) {} break }return x}");
// A break here only breaks out of the inner loop.
foldSame("function f() { while(x) { while (y) { return } } }");
foldSame("function f() { while(1) { return 7} return 5}");
foldSame("function f() {" +
" try { while(x) {return f()}} catch (e) { } return f()}");
foldSame("function f() {" +
" try { while(x) {return f()}} finally {alert(1)} return f()}");
// Both returns has the same handler
fold("function f() {" +
" try { while(x) { return f() } return f() } catch (e) { } }",
"function f() {" +
" try { while(x) { break } return f() } catch (e) { } }");
// We can't fold this because it'll change the order of when foo is called.
foldSame("function f() {" +
" try { while(x) { return foo() } } finally { alert(1) } " +
" return foo()}");
// This is fine, we have no side effect in the return value.
fold("function f() {" +
" try { while(x) { return 1 } } finally { alert(1) } return 1}",
"function f() {" +
" try { while(x) { break } } finally { alert(1) } return 1}"
);
foldSame("function f() { try{ return a } finally { a = 2 } return a; }");
fold(
"function f() { switch(a){ case 1: return a; default: g();} return a;}",
"function f() { switch(a){ case 1: break; default: g();} return a; }");
}
public void testSubsituteBreakForThrow() {
foldSame("function f() { while(x) { throw Error }}");
fold("function f() { while(x) { throw Error } throw Error }",
"function f() { while(x) { break } throw Error}");
foldSame("function f() { while(x) { throw Error(1) } throw Error(2)}");
foldSame("function f() { while(x) { throw Error(1) } return Error(2)}");
foldSame("function f() { while(x) { throw 5 } }");
foldSame("function f() { a: { throw 5 } }");
fold("function f() { while(x) { throw 5} throw 5}",
"function f() { while(x) { break } throw 5}");
fold("function f() { while(x) { throw x} throw x}",
"function f() { while(x) { break } throw x}");
foldSame("function f() { while(x) { if (y) { throw Error }}}");
fold("function f() { while(x) { if (y) { throw Error }} throw Error}",
"function f() { while(x) { if (y) { break }} throw Error}");
fold("function f() { while(x) { if (y) { throw 5 }} throw 5}",
"function f() { while(x) { if (y) { break }} throw 5}");
// It doesn't matter if x is changed between them. We are still throwing
// x at whatever x value current holds. The whole x = 1 is skipped.
fold("function f() { while(x) { if (y) { throw x } x = 1} throw x}",
"function f() { while(x) { if (y) { break } x = 1} throw x}");
// RemoveUnreachableCode would take care of the useless breaks.
fold("function f() { while(x) { if (y) { throw x } throw x} throw x}",
"function f() { while(x) { if (y) {} break }throw x}");
// A break here only breaks out of the inner loop.
foldSame("function f() { while(x) { while (y) { throw Error } } }");
foldSame("function f() { while(1) { throw 7} throw 5}");
foldSame("function f() {" +
" try { while(x) {throw f()}} catch (e) { } throw f()}");
foldSame("function f() {" +
" try { while(x) {throw f()}} finally {alert(1)} throw f()}");
// Both throws has the same handler
fold("function f() {" +
" try { while(x) { throw f() } throw f() } catch (e) { } }",
"function f() {" +
" try { while(x) { break } throw f() } catch (e) { } }");
// We can't fold this because it'll change the order of when foo is called.
foldSame("function f() {" +
" try { while(x) { throw foo() } } finally { alert(1) } " +
" throw foo()}");
// This is fine, we have no side effect in the throw value.
fold("function f() {" +
" try { while(x) { throw 1 } } finally { alert(1) } throw 1}",
"function f() {" +
" try { while(x) { break } } finally { alert(1) } throw 1}"
);
foldSame("function f() { try{ throw a } finally { a = 2 } throw a; }");
fold(
"function f() { switch(a){ case 1: throw a; default: g();} throw a;}",
"function f() { switch(a){ case 1: break; default: g();} throw a; }");
}
public void testRemoveDuplicateReturn() {
fold("function f() { return; }",
"function f(){}");
foldSame("function f() { return a; }");
fold("function f() { if (x) { return a } return a; }",
"function f() { if (x) {} return a; }");
foldSame(
"function f() { try { if (x) { return a } } catch(e) {} return a; }");
foldSame(
"function f() { try { if (x) {} } catch(e) {} return 1; }");
// finally clauses may have side effects
foldSame(
"function f() { try { if (x) { return a } } finally { a++ } return a; }");
// but they don't matter if the result doesn't have side effects and can't
// be affect by side-effects.
fold("function f() { try { if (x) { return 1 } } finally {} return 1; }",
"function f() { try { if (x) {} } finally {} return 1; }");
fold("function f() { switch(a){ case 1: return a; } return a; }",
"function f() { switch(a){ case 1: } return a; }");
fold("function f() { switch(a){ " +
" case 1: return a; case 2: return a; } return a; }",
"function f() { switch(a){ " +
" case 1: break; case 2: } return a; }");
}
public void testRemoveDuplicateThrow() {
foldSame("function f() { throw a; }");
fold("function f() { if (x) { throw a } throw a; }",
"function f() { if (x) {} throw a; }");
foldSame(
"function f() { try { if (x) {throw a} } catch(e) {} throw a; }");
foldSame(
"function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }");
foldSame(
"function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }");
foldSame(
"function f() { try { if (x) {throw 1} } catch(e) {throw 1}}");
fold(
"function f() { try { if (x) {throw 1} } catch(e) {throw 1} throw 1; }",
"function f() { try { if (x) {throw 1} } catch(e) {} throw 1; }");
// finally clauses may have side effects
foldSame(
"function f() { try { if (x) { throw a } } finally { a++ } throw a; }");
// but they don't matter if the result doesn't have side effects and can't
// be affect by side-effects.
fold("function f() { try { if (x) { throw 1 } } finally {} throw 1; }",
"function f() { try { if (x) {} } finally {} throw 1; }");
fold("function f() { switch(a){ case 1: throw a; } throw a; }",
"function f() { switch(a){ case 1: } throw a; }");
fold("function f() { switch(a){ " +
"case 1: throw a; case 2: throw a; } throw a; }",
"function f() { switch(a){ case 1: break; case 2: } throw a; }");
}
public void testNestedIfCombine() {
fold("if(x)if(y){while(1){}}", "if(x&&y){while(1){}}");
fold("if(x||z)if(y){while(1){}}", "if((x||z)&&y){while(1){}}");
fold("if(x)if(y||z){while(1){}}", "if((x)&&(y||z)){while(1){}}");
foldSame("if(x||z)if(y||z){while(1){}}");
fold("if(x)if(y){if(z){while(1){}}}", "if(x&&y&&z){while(1){}}");
}
public void testFoldTrueFalse() {
fold("x = true", "x = !0");
fold("x = false", "x = !1");
}
public void testIssue291() {
fold("if (true) { f.onchange(); }", "if (1) f.onchange();");
foldSame("if (f) { f.onchange(); }");
foldSame("if (f) { f.bar(); } else { f.onchange(); }");
fold("if (f) { f.bonchange(); }", "f && f.bonchange();");
foldSame("if (f) { f['x'](); }");
}
public void testUndefined() {
foldSame("var x = undefined");
foldSame("function f(f) {var undefined=2;var x = undefined;}");
this.enableNormalize();
fold("var x = undefined", "var x=void 0");
foldSame(
"var undefined = 1;" +
"function f() {var undefined=2;var x = undefined;}");
foldSame("function f(undefined) {}");
foldSame("try {} catch(undefined) {}");
foldSame("for (undefined in {}) {}");
foldSame("undefined++;");
fold("undefined += undefined;", "undefined += void 0;");
}
public void testSplitCommaExpressions() {
late = false;
// Don't try to split in expressions.
foldSame("while (foo(), !0) boo()");
foldSame("var a = (foo(), !0);");
foldSame("a = (foo(), !0);");
// Don't try to split COMMA under LABELs.
foldSame("a:a(),b()");
fold("(x=2), foo()", "x=2; foo()");
fold("foo(), boo();", "foo(); boo()");
fold("(a(), b()), (c(), d());", "a(); b(); c(); d();");
fold("foo(), true", "foo();1");
fold("function x(){foo(), !0}", "function x(){foo(); 1}");
}
public void testComma1() {
late = false;
fold("1, 2", "1; 1");
late = true;
foldSame("1, 2");
}
public void testComma2() {
late = false;
test("1, a()", "1; a()");
late = true;
foldSame("1, a()");
}
public void testComma3() {
late = false;
test("1, a(), b()", "1; a(); b()");
late = true;
foldSame("1, a(), b()");
}
public void testComma4() {
late = false;
test("a(), b()", "a();b()");
late = true;
foldSame("a(), b()");
}
public void testComma5() {
late = false;
test("a(), b(), 1", "a();b();1");
late = true;
foldSame("a(), b(), 1");
}
public void testObjectLiteral() {
test("({})", "1");
test("({a:1})", "1");
testSame("({a:foo()})");
testSame("({'a':foo()})");
}
public void testArrayLiteral() {
test("([])", "1");
test("([1])", "1");
test("([a])", "1");
testSame("([foo()])");
}
public void testStringArraySplitting() {
testSame("var x=['1','2','3','4']");
testSame("var x=['1','2','3','4','5']");
test("var x=['1','2','3','4','5','6']",
"var x='123456'.split('')");
test("var x=['1','2','3','4','5','00']",
"var x='1 2 3 4 5 00'.split(' ')");
test("var x=['1','2','3','4','5','6','7']",
"var x='1234567'.split('')");
test("var x=['1','2','3','4','5','6','00']",
"var x='1 2 3 4 5 6 00'.split(' ')");
test("var x=[' ,',',',',',',',',',',']",
"var x=' ,;,;,;,;,;,'.split(';')");
test("var x=[',,',' ',',',',',',',',']",
"var x=',,; ;,;,;,;,'.split(';')");
test("var x=['a,',' ',',',',',',',',']",
"var x='a,; ;,;,;,;,'.split(';')");
// all possible delimiters used, leave it alone
testSame("var x=[',', ' ', ';', '{', '}']");
}
public void testRemoveElseCause() {
test("function f() {" +
" if(x) return 1;" +
" else if(x) return 2;" +
" else if(x) return 3 }",
"function f() {" +
" if(x) return 1;" +
"{ if(x) return 2;" +
"{ if(x) return 3 } } }");
}
public void testRemoveElseCause1() {
test("function f() { if (x) throw 1; else f() }",
"function f() { if (x) throw 1; { f() } }");
}
public void testRemoveElseCause2() {
test("function f() { if (x) return 1; else f() }",
"function f() { if (x) return 1; { f() } }");
test("function f() { if (x) return; else f() }",
"function f() { if (x) {} else { f() } }");
// This case is handled by minimize exit points.
testSame("function f() { if (x) return; f() }");
}
public void testRemoveElseCause3() {
testSame("function f() { a:{if (x) break a; else f() } }");
testSame("function f() { if (x) { a:{ break a } } else f() }");
testSame("function f() { if (x) a:{ break a } else f() }");
}
public void testRemoveElseCause4() {
testSame("function f() { if (x) { if (y) { return 1; } } else f() }");
}
public void testBindToCall1() {
test("(goog.bind(f))()", "f()");
test("(goog.bind(f,a))()", "f.call(a)");
test("(goog.bind(f,a,b))()", "f.call(a,b)");
test("(goog.bind(f))(a)", "f(a)");
test("(goog.bind(f,a))(b)", "f.call(a,b)");
test("(goog.bind(f,a,b))(c)", "f.call(a,b,c)");
test("(goog.partial(f))()", "f()");
test("(goog.partial(f,a))()", "f(a)");
test("(goog.partial(f,a,b))()", "f(a,b)");
test("(goog.partial(f))(a)", "f(a)");
test("(goog.partial(f,a))(b)", "f(a,b)");
test("(goog.partial(f,a,b))(c)", "f(a,b,c)");
test("((function(){}).bind())()", "((function(){}))()");
test("((function(){}).bind(a))()", "((function(){})).call(a)");
test("((function(){}).bind(a,b))()", "((function(){})).call(a,b)");
test("((function(){}).bind())(a)", "((function(){}))(a)");
test("((function(){}).bind(a))(b)", "((function(){})).call(a,b)");
test("((function(){}).bind(a,b))(c)", "((function(){})).call(a,b,c)");
// Without using type information we don't know "f" is a function.
testSame("(f.bind())()");
testSame("(f.bind(a))()");
testSame("(f.bind())(a)");
testSame("(f.bind(a))(b)");
// Don't rewrite if the bind isn't the immediate call target
testSame("(goog.bind(f)).call(g)");
}
public void testBindToCall2() {
test("(goog$bind(f))()", "f()");
test("(goog$bind(f,a))()", "f.call(a)");
test("(goog$bind(f,a,b))()", "f.call(a,b)");
test("(goog$bind(f))(a)", "f(a)");
test("(goog$bind(f,a))(b)", "f.call(a,b)");
test("(goog$bind(f,a,b))(c)", "f.call(a,b,c)");
test("(goog$partial(f))()", "f()");
test("(goog$partial(f,a))()", "f(a)");
test("(goog$partial(f,a,b))()", "f(a,b)");
test("(goog$partial(f))(a)", "f(a)");
test("(goog$partial(f,a))(b)", "f(a,b)");
test("(goog$partial(f,a,b))(c)", "f(a,b,c)");
// Don't rewrite if the bind isn't the immediate call target
testSame("(goog$bind(f)).call(g)");
}
public void testBindToCall3() {
// TODO(johnlenz): The code generator wraps free calls with (0,...) to
// prevent leaking "this", but the parser doesn't unfold it, making a
// AST comparison fail. For now do a string comparison to validate the
// correct code is in fact generated.
// The FREE call wrapping should be moved out of the code generator
// and into a denormalizing pass.
new StringCompareTestCase().testBindToCall3();
}
public void testSimpleFunctionCall() {
test("var a = String(23)", "var a = '' + 23");
test("var a = String('hello')", "var a = '' + 'hello'");
testSame("var a = String('hello', bar());");
testSame("var a = String({valueOf: function() { return 1; }});");
}
private static class StringCompareTestCase extends CompilerTestCase {
StringCompareTestCase() {
super("", false);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
CompilerPass peepholePass =
new PeepholeOptimizationsPass(compiler,
new PeepholeSubstituteAlternateSyntax(false));
return peepholePass;
}
public void testBindToCall3() {
test("(goog.bind(f.m))()", "(0,f.m)()");
test("(goog.bind(f.m,a))()", "f.m.call(a)");
test("(goog.bind(f.m))(a)", "(0,f.m)(a)");
test("(goog.bind(f.m,a))(b)", "f.m.call(a,b)");
test("(goog.partial(f.m))()", "(0,f.m)()");
test("(goog.partial(f.m,a))()", "(0,f.m)(a)");
test("(goog.partial(f.m))(a)", "(0,f.m)(a)");
test("(goog.partial(f.m,a))(b)", "(0,f.m)(a,b)");
// Without using type information we don't know "f" is a function.
testSame("f.m.bind()()");
testSame("f.m.bind(a)()");
testSame("f.m.bind()(a)");
testSame("f.m.bind(a)(b)");
// Don't rewrite if the bind isn't the immediate call target
testSame("goog.bind(f.m).call(g)");
}
}
} | // You are a professional Java test case writer, please create a test case named `testSimpleFunctionCall` for the issue `Closure-759`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-759
//
// ## Issue-Title:
// String conversion optimization is incorrect
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
//
// var f = {
// valueOf: function() { return undefined; }
// }
// String(f)
//
// **What is the expected output? What do you see instead?**
//
// Expected output: "[object Object]"
// Actual output: "undefined"
//
// **What version of the product are you using? On what operating system?**
//
// All versions (http://closure-compiler.appspot.com/ as well).
//
// **Please provide any additional information below.**
//
// The compiler optimizes String(x) calls by replacing them with x + ''. This is correct in most cases, but incorrect in corner cases like the one mentioned above.
//
//
public void testSimpleFunctionCall() {
| 1,032 | 20 | 1,027 | test/com/google/javascript/jscomp/PeepholeSubstituteAlternateSyntaxTest.java | test | ```markdown
## Issue-ID: Closure-759
## Issue-Title:
String conversion optimization is incorrect
## Issue-Description:
**What steps will reproduce the problem?**
var f = {
valueOf: function() { return undefined; }
}
String(f)
**What is the expected output? What do you see instead?**
Expected output: "[object Object]"
Actual output: "undefined"
**What version of the product are you using? On what operating system?**
All versions (http://closure-compiler.appspot.com/ as well).
**Please provide any additional information below.**
The compiler optimizes String(x) calls by replacing them with x + ''. This is correct in most cases, but incorrect in corner cases like the one mentioned above.
```
You are a professional Java test case writer, please create a test case named `testSimpleFunctionCall` for the issue `Closure-759`, utilizing the provided issue report information and the following function signature.
```java
public void testSimpleFunctionCall() {
```
| 1,027 | [
"com.google.javascript.jscomp.PeepholeSubstituteAlternateSyntax"
] | 697b2d1985d3a2a554c9dffda676578cb48c35e486d26e27a4122a7ec364f188 | public void testSimpleFunctionCall() | // You are a professional Java test case writer, please create a test case named `testSimpleFunctionCall` for the issue `Closure-759`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Closure-759
//
// ## Issue-Title:
// String conversion optimization is incorrect
//
// ## Issue-Description:
// **What steps will reproduce the problem?**
//
// var f = {
// valueOf: function() { return undefined; }
// }
// String(f)
//
// **What is the expected output? What do you see instead?**
//
// Expected output: "[object Object]"
// Actual output: "undefined"
//
// **What version of the product are you using? On what operating system?**
//
// All versions (http://closure-compiler.appspot.com/ as well).
//
// **Please provide any additional information below.**
//
// The compiler optimizes String(x) calls by replacing them with x + ''. This is correct in most cases, but incorrect in corner cases like the one mentioned above.
//
//
| 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;
/**
* Tests for {@link PeepholeSubstituteAlternateSyntax} in isolation.
* Tests for the interaction of multiple peephole passes are in
* PeepholeIntegrationTest.
*/
public class PeepholeSubstituteAlternateSyntaxTest extends CompilerTestCase {
// Externs for built-in constructors
// Needed for testFoldLiteralObjectConstructors(),
// testFoldLiteralArrayConstructors() and testFoldRegExp...()
private static final String FOLD_CONSTANTS_TEST_EXTERNS =
"var Object = function f(){};\n" +
"var RegExp = function f(a){};\n" +
"var Array = function f(a){};\n";
private boolean late = true;
// TODO(user): Remove this when we no longer need to do string comparison.
private PeepholeSubstituteAlternateSyntaxTest(boolean compareAsTree) {
super(FOLD_CONSTANTS_TEST_EXTERNS, compareAsTree);
}
public PeepholeSubstituteAlternateSyntaxTest() {
super(FOLD_CONSTANTS_TEST_EXTERNS);
}
@Override
public void setUp() throws Exception {
late = true;
super.setUp();
enableLineNumberCheck(true);
disableNormalize();
}
@Override
public CompilerPass getProcessor(final Compiler compiler) {
CompilerPass peepholePass =
new PeepholeOptimizationsPass(compiler,
new PeepholeSubstituteAlternateSyntax(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);
}
void assertResultString(String js, String expected) {
assertResultString(js, expected, false);
}
// 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.
void assertResultString(String js, String expected, boolean normalize) {
PeepholeSubstituteAlternateSyntaxTest scTest
= new PeepholeSubstituteAlternateSyntaxTest(false);
if (normalize) {
scTest.enableNormalize();
} else {
scTest.disableNormalize();
}
scTest.test(js, expected);
}
/** Check that removing blocks with 1 child works */
public void testFoldOneChildBlocks() {
late = false;
fold("function f(){if(x)a();x=3}",
"function f(){x&&a();x=3}");
fold("function f(){if(x){a()}x=3}",
"function f(){x&&a();x=3}");
fold("function f(){if(x){return 3}}",
"function f(){if(x)return 3}");
fold("function f(){if(x){a()}}",
"function f(){x&&a()}");
fold("function f(){if(x){throw 1}}", "function f(){if(x)throw 1;}");
// Try it out with functions
fold("function f(){if(x){foo()}}", "function f(){x&&foo()}");
fold("function f(){if(x){foo()}else{bar()}}",
"function f(){x?foo():bar()}");
// Try it out with properties and methods
fold("function f(){if(x){a.b=1}}", "function f(){if(x)a.b=1}");
fold("function f(){if(x){a.b*=1}}", "function f(){x&&(a.b*=1)}");
fold("function f(){if(x){a.b+=1}}", "function f(){x&&(a.b+=1)}");
fold("function f(){if(x){++a.b}}", "function f(){x&&++a.b}");
fold("function f(){if(x){a.foo()}}", "function f(){x&&a.foo()}");
// Try it out with throw/catch/finally [which should not change]
fold("function f(){try{foo()}catch(e){bar(e)}finally{baz()}}",
"function f(){try{foo()}catch(e){bar(e)}finally{baz()}}");
// Try it out with switch statements
fold("function f(){switch(x){case 1:break}}",
"function f(){switch(x){case 1:break}}");
// Do while loops stay in a block if that's where they started
fold("function f(){if(e1){do foo();while(e2)}else foo2()}",
"function f(){if(e1){do foo();while(e2)}else foo2()}");
// Test an obscure case with do and while
fold("if(x){do{foo()}while(y)}else bar()",
"if(x){do foo();while(y)}else bar()");
// Play with nested IFs
fold("function f(){if(x){if(y)foo()}}",
"function f(){x&&y&&foo()}");
fold("function f(){if(x){if(y)foo();else bar()}}",
"function f(){x&&(y?foo():bar())}");
fold("function f(){if(x){if(y)foo()}else bar()}",
"function f(){x?y&&foo():bar()}");
fold("function f(){if(x){if(y)foo();else bar()}else{baz()}}",
"function f(){x?y?foo():bar():baz()}");
fold("if(e1){while(e2){if(e3){foo()}}}else{bar()}",
"if(e1)while(e2)e3&&foo();else bar()");
fold("if(e1){with(e2){if(e3){foo()}}}else{bar()}",
"if(e1)with(e2)e3&&foo();else bar()");
fold("if(a||b){if(c||d){var x;}}", "if(a||b)if(c||d)var x");
fold("if(x){ if(y){var x;}else{var z;} }",
"if(x)if(y)var x;else var z");
// NOTE - technically we can remove the blocks since both the parent
// and child have elses. But we don't since it causes ambiguities in
// some cases where not all descendent ifs having elses
fold("if(x){ if(y){var x;}else{var z;} }else{var w}",
"if(x)if(y)var x;else var z;else var w");
fold("if (x) {var x;}else { if (y) { var y;} }",
"if(x)var x;else if(y)var y");
// Here's some of the ambiguous cases
fold("if(a){if(b){f1();f2();}else if(c){f3();}}else {if(d){f4();}}",
"if(a)if(b){f1();f2()}else c&&f3();else d&&f4()");
fold("function f(){foo()}", "function f(){foo()}");
fold("switch(x){case y: foo()}", "switch(x){case y:foo()}");
fold("try{foo()}catch(ex){bar()}finally{baz()}",
"try{foo()}catch(ex){bar()}finally{baz()}");
}
/** Try to minimize returns */
public void testFoldReturns() {
fold("function f(){if(x)return 1;else return 2}",
"function f(){return x?1:2}");
fold("function f(){if(x)return 1;return 2}",
"function f(){return x?1:2}");
fold("function f(){if(x)return;return 2}",
"function f(){return x?void 0:2}");
fold("function f(){if(x)return 1+x;else return 2-x}",
"function f(){return x?1+x:2-x}");
fold("function f(){if(x)return 1+x;return 2-x}",
"function f(){return x?1+x:2-x}");
fold("function f(){if(x)return y += 1;else return y += 2}",
"function f(){return x?(y+=1):(y+=2)}");
fold("function f(){if(x)return;else return 2-x}",
"function f(){if(x);else return 2-x}");
fold("function f(){if(x)return;return 2-x}",
"function f(){return x?void 0:2-x}");
fold("function f(){if(x)return x;else return}",
"function f(){if(x)return x;{}}");
fold("function f(){if(x)return x;return}",
"function f(){if(x)return x}");
foldSame("function f(){for(var x in y) { return x.y; } return k}");
}
public void testCombineIfs1() {
fold("function f() {if (x) return 1; if (y) return 1}",
"function f() {if (x||y) return 1;}");
fold("function f() {if (x) return 1; if (y) foo(); else return 1}",
"function f() {if ((!x)&&y) foo(); else return 1;}");
}
public void testCombineIfs2() {
// combinable but not yet done
foldSame("function f() {if (x) throw 1; if (y) throw 1}");
// Can't combine, side-effect
fold("function f(){ if (x) g(); if (y) g() }",
"function f(){ x&&g(); y&&g() }");
// Can't combine, side-effect
fold("function f(){ if (x) y = 0; if (y) y = 0; }",
"function f(){ x&&(y = 0); y&&(y = 0); }");
}
public void testCombineIfs3() {
foldSame("function f() {if (x) return 1; if (y) {g();f()}}");
}
/** Try to minimize assignments */
public void testFoldAssignments() {
fold("function f(){if(x)y=3;else y=4;}", "function f(){y=x?3:4}");
fold("function f(){if(x)y=1+a;else y=2+a;}", "function f(){y=x?1+a:2+a}");
// and operation assignments
fold("function f(){if(x)y+=1;else y+=2;}", "function f(){y+=x?1:2}");
fold("function f(){if(x)y-=1;else y-=2;}", "function f(){y-=x?1:2}");
fold("function f(){if(x)y%=1;else y%=2;}", "function f(){y%=x?1:2}");
fold("function f(){if(x)y|=1;else y|=2;}", "function f(){y|=x?1:2}");
// sanity check, don't fold if the 2 ops don't match
foldSame("function f(){x ? y-=1 : y+=2}");
// sanity check, don't fold if the 2 LHS don't match
foldSame("function f(){x ? y-=1 : z-=1}");
// sanity check, don't fold if there are potential effects
foldSame("function f(){x ? y().a=3 : y().a=4}");
}
public void testRemoveDuplicateStatements() {
fold("if (a) { x = 1; x++ } else { x = 2; x++ }",
"x=(a) ? 1 : 2; x++");
fold("if (a) { x = 1; x++; y += 1; z = pi; }" +
" else { x = 2; x++; y += 1; z = pi; }",
"x=(a) ? 1 : 2; x++; y += 1; z = pi;");
fold("function z() {" +
"if (a) { foo(); return !0 } else { goo(); return !0 }" +
"}",
"function z() {(a) ? foo() : goo(); return !0}");
fold("function z() {if (a) { foo(); x = true; return true " +
"} else { goo(); x = true; return true }}",
"function z() {(a) ? foo() : goo(); x = !0; return !0}");
fold("function z() {" +
" if (a) { bar(); foo(); return true }" +
" else { bar(); goo(); return true }" +
"}",
"function z() {" +
" if (a) { bar(); foo(); }" +
" else { bar(); goo(); }" +
" return !0;" +
"}");
}
public void testNotCond() {
fold("function f(){if(!x)foo()}", "function f(){x||foo()}");
fold("function f(){if(!x)b=1}", "function f(){x||(b=1)}");
fold("if(!x)z=1;else if(y)z=2", "x ? y&&(z=2) : z=1");
foldSame("function f(){if(!(x=1))a.b=1}");
}
public void testAndParenthesesCount() {
fold("function f(){if(x||y)a.foo()}", "function f(){(x||y)&&a.foo()}");
fold("function f(){if(x.a)x.a=0}",
"function f(){x.a&&(x.a=0)}");
foldSame("function f(){if(x()||y()){x()||y()}}");
}
public void testFoldLogicalOpStringCompare() {
// side-effects
// There is two way to parse two &&'s and both are correct.
assertResultString("if(foo() && false) z()", "foo()&&0&&z()");
}
public void testFoldNot() {
fold("while(!(x==y)){a=b;}" , "while(x!=y){a=b;}");
fold("while(!(x!=y)){a=b;}" , "while(x==y){a=b;}");
fold("while(!(x===y)){a=b;}", "while(x!==y){a=b;}");
fold("while(!(x!==y)){a=b;}", "while(x===y){a=b;}");
// Because !(x<NaN) != x>=NaN don't fold < and > cases.
foldSame("while(!(x>y)){a=b;}");
foldSame("while(!(x>=y)){a=b;}");
foldSame("while(!(x<y)){a=b;}");
foldSame("while(!(x<=y)){a=b;}");
foldSame("while(!(x<=NaN)){a=b;}");
// NOT forces a boolean context
fold("x = !(y() && true)", "x = !y()");
// This will be further optimized by PeepholeFoldConstants.
fold("x = !true", "x = !1");
}
public void testFoldRegExpConstructor() {
enableNormalize();
// Cannot fold all the way to a literal because there are too few arguments.
fold("x = new RegExp", "x = RegExp()");
// Empty regexp should not fold to // since that is a line comment in JS
fold("x = new RegExp(\"\")", "x = RegExp(\"\")");
fold("x = new RegExp(\"\", \"i\")", "x = RegExp(\"\",\"i\")");
// Bogus flags should not fold
fold("x = new RegExp(\"foobar\", \"bogus\")",
"x = RegExp(\"foobar\",\"bogus\")",
PeepholeSubstituteAlternateSyntax.INVALID_REGULAR_EXPRESSION_FLAGS);
// Can Fold
fold("x = new RegExp(\"foobar\")", "x = /foobar/");
fold("x = RegExp(\"foobar\")", "x = /foobar/");
fold("x = new RegExp(\"foobar\", \"i\")", "x = /foobar/i");
// Make sure that escaping works
fold("x = new RegExp(\"\\\\.\", \"i\")", "x = /\\./i");
fold("x = new RegExp(\"/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"[/]\", \"\")", "x = /[/]/");
fold("x = new RegExp(\"///\", \"\")", "x = /\\/\\/\\//");
fold("x = new RegExp(\"\\\\\\/\", \"\")", "x = /\\//");
fold("x = new RegExp(\"\\n\")", "x = /\\n/");
fold("x = new RegExp('\\\\\\r')", "x = /\\r/");
// Don't fold really long regexp literals, because Opera 9.2's
// regexp parser will explode.
String longRegexp = "";
for (int i = 0; i < 200; i++) longRegexp += "x";
foldSame("x = RegExp(\"" + longRegexp + "\")");
// Shouldn't fold RegExp unnormalized because
// we can't be sure that RegExp hasn't been redefined
disableNormalize();
foldSame("x = new RegExp(\"foobar\")");
}
public void testVersionSpecificRegExpQuirks() {
enableNormalize();
// Don't fold if the flags contain 'g'
enableEcmaScript5(false);
fold("x = new RegExp(\"foobar\", \"g\")",
"x = RegExp(\"foobar\",\"g\")");
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = RegExp(\"foobar\",\"ig\")");
// ... unless in ECMAScript 5 mode per section 7.8.5 of ECMAScript 5.
enableEcmaScript5(true);
fold("x = new RegExp(\"foobar\", \"ig\")",
"x = /foobar/ig");
// Don't fold things that crash older versions of Safari and that don't work
// as regex literals on other old versions of Safari
enableEcmaScript5(false);
fold("x = new RegExp(\"\\u2028\")", "x = RegExp(\"\\u2028\")");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
// Sunset Safari exclusions for ECMAScript 5 and later.
enableEcmaScript5(true);
fold("x = new RegExp(\"\\u2028\\u2029\")", "x = /\\u2028\\u2029/");
fold("x = new RegExp(\"\\\\u2028\")", "x = /\\u2028/");
fold("x = new RegExp(\"\\\\\\\\u2028\")", "x = /\\\\u2028/");
}
public void testFoldRegExpConstructorStringCompare() {
// Might have something to do with the internal representation of \n and how
// it is used in node comparison.
assertResultString("x=new RegExp(\"\\n\", \"i\")", "x=/\\n/i", true);
}
public void testContainsUnicodeEscape() throws Exception {
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(""));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"\\u2028"));
assertTrue(
PeepholeSubstituteAlternateSyntax.containsUnicodeEscape("foo\\u2028"));
assertTrue(!PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028"));
assertTrue(PeepholeSubstituteAlternateSyntax.containsUnicodeEscape(
"foo\\\\u2028bar\\u2028"));
}
public void testFoldLiteralObjectConstructors() {
enableNormalize();
// Can fold when normalized
fold("x = new Object", "x = ({})");
fold("x = new Object()", "x = ({})");
fold("x = Object()", "x = ({})");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Object");
foldSame("x = new Object()");
foldSame("x = Object()");
enableNormalize();
// Cannot fold, the constructor being used is actually a local function
foldSame("x = " +
"(function f(){function Object(){this.x=4};return new Object();})();");
}
public void testFoldLiteralArrayConstructors() {
enableNormalize();
// No arguments - can fold when normalized
fold("x = new Array", "x = []");
fold("x = new Array()", "x = []");
fold("x = Array()", "x = []");
// One argument - can be fold when normalized
fold("x = new Array(0)", "x = []");
fold("x = Array(0)", "x = []");
fold("x = new Array(\"a\")", "x = [\"a\"]");
fold("x = Array(\"a\")", "x = [\"a\"]");
// One argument - cannot be fold when normalized
fold("x = new Array(7)", "x = Array(7)");
fold("x = Array(7)", "x = Array(7)");
fold("x = new Array(y)", "x = Array(y)");
fold("x = Array(y)", "x = Array(y)");
fold("x = new Array(foo())", "x = Array(foo())");
fold("x = Array(foo())", "x = Array(foo())");
// More than one argument - can be fold when normalized
fold("x = new Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = Array(1, 2, 3, 4)", "x = [1, 2, 3, 4]");
fold("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')",
"x = ['a', 1, 2, 'bc', 3, {}, 'abc']");
fold("x = new Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = Array(Array(1, '2', 3, '4'))", "x = [[1, '2', 3, '4']]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]]");
fold("x = new Array(Object(), Array(\"abc\", Object(), Array(Array())))",
"x = [{}, [\"abc\", {}, [[]]]]");
disableNormalize();
// Cannot fold above when not normalized
foldSame("x = new Array");
foldSame("x = new Array()");
foldSame("x = Array()");
foldSame("x = new Array(0)");
foldSame("x = Array(0)");
foldSame("x = new Array(\"a\")");
foldSame("x = Array(\"a\")");
foldSame("x = new Array(7)");
foldSame("x = Array(7)");
foldSame("x = new Array(foo())");
foldSame("x = Array(foo())");
foldSame("x = new Array(1, 2, 3, 4)");
foldSame("x = Array(1, 2, 3, 4)");
foldSame("x = new Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = Array('a', 1, 2, 'bc', 3, {}, 'abc')");
foldSame("x = new Array(Array(1, '2', 3, '4'))");
foldSame("x = Array(Array(1, '2', 3, '4'))");
foldSame("x = new Array(" +
"Object(), Array(\"abc\", Object(), Array(Array())))");
foldSame("x = new Array(" +
"Object(), Array(\"abc\", Object(), Array(Array())))");
}
public void testMinimizeExprCondition() {
fold("(x ? true : false) && y()", "x&&y()");
fold("(x ? false : true) && y()", "(!x)&&y()");
fold("(x ? true : y) && y()", "(x || y)&&y()");
fold("(x ? y : false) && y()", "(x && y)&&y()");
fold("(x && true) && y()", "x && y()");
fold("(x && false) && y()", "0&&y()");
fold("(x || true) && y()", "1&&y()");
fold("(x || false) && y()", "x&&y()");
}
public void testMinimizeWhileCondition() {
// This test uses constant folding logic, so is only here for completeness.
fold("while(!!true) foo()", "while(1) foo()");
// These test tryMinimizeCondition
fold("while(!!x) foo()", "while(x) foo()");
fold("while(!(!x&&!y)) foo()", "while(x||y) foo()");
fold("while(x||!!y) foo()", "while(x||y) foo()");
fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()");
fold("while(!(!x&&y)) foo()", "while(x||!y) foo()");
fold("while(!(x||!y)) foo()", "while(!x&&y) foo()");
fold("while(!(x||y)) foo()", "while(!x&&!y) foo()");
fold("while(!(!x||y-z)) foo()", "while(x&&!(y-z)) foo()");
fold("while(!(!(x/y)||z+w)) foo()", "while(x/y&&!(z+w)) foo()");
foldSame("while(!(x+y||z)) foo()");
foldSame("while(!(x&&y*z)) foo()");
fold("while(!(!!x&&y)) foo()", "while(!x||!y) foo()");
fold("while(x&&!0) foo()", "while(x) foo()");
fold("while(x||!1) foo()", "while(x) foo()");
fold("while(!((x,y)&&z)) foo()", "while(!(x,y)||!z) foo()");
}
public void testMinimizeForCondition() {
// This test uses constant folding logic, so is only here for completeness.
// These could be simplified to "for(;;) ..."
fold("for(;!!true;) foo()", "for(;1;) foo()");
// Don't bother with FOR inits as there are normalized out.
fold("for(!!true;;) foo()", "for(!0;;) foo()");
// These test tryMinimizeCondition
fold("for(;!!x;) foo()", "for(;x;) foo()");
// sanity check
foldSame("for(a in b) foo()");
foldSame("for(a in {}) foo()");
foldSame("for(a in []) foo()");
fold("for(a in !!true) foo()", "for(a in !0) foo()");
}
public void testMinimizeCondition_example1() {
// Based on a real failing code sample.
fold("if(!!(f() > 20)) {foo();foo()}", "if(f() > 20){foo();foo()}");
}
public void testFoldLoopBreakLate() {
late = true;
fold("for(;;) if (a) break", "for(;!a;);");
foldSame("for(;;) if (a) { f(); break }");
fold("for(;;) if (a) break; else f()", "for(;!a;) { { f(); } }");
fold("for(;a;) if (b) break", "for(;a && !b;);");
fold("for(;a;) { if (b) break; if (c) break; }", "for(;(a && !b) && !c;);");
// 'while' is normalized to 'for'
enableNormalize(true);
fold("while(true) if (a) break", "for(;1&&!a;);");
}
public void testFoldLoopBreakEarly() {
late = false;
foldSame("for(;;) if (a) break");
foldSame("for(;;) if (a) { f(); break }");
foldSame("for(;;) if (a) break; else f()");
foldSame("for(;a;) if (b) break");
foldSame("for(;a;) { if (b) break; if (c) break; }");
foldSame("while(1) if (a) break");
enableNormalize(true);
foldSame("while(1) if (a) break");
}
public void testFoldConditionalVarDeclaration() {
fold("if(x) var y=1;else y=2", "var y=x?1:2");
fold("if(x) y=1;else var y=2", "var y=x?1:2");
foldSame("if(x) var y = 1; z = 2");
foldSame("if(x||y) y = 1; var z = 2");
foldSame("if(x) { var y = 1; print(y)} else y = 2 ");
foldSame("if(x) var y = 1; else {y = 2; print(y)}");
}
public void testFoldReturnResult() {
fold("function f(){return false;}", "function f(){return !1}");
foldSame("function f(){return null;}");
fold("function f(){return void 0;}",
"function f(){}");
foldSame("function f(){return void foo();}");
fold("function f(){return undefined;}",
"function f(){}");
fold("function f(){if(a()){return undefined;}}",
"function f(){if(a()){}}");
}
public void testFoldStandardConstructors() {
foldSame("new Foo('a')");
foldSame("var x = new goog.Foo(1)");
foldSame("var x = new String(1)");
foldSame("var x = new Number(1)");
foldSame("var x = new Boolean(1)");
enableNormalize();
fold("var x = new Object('a')", "var x = Object('a')");
fold("var x = new RegExp('')", "var x = RegExp('')");
fold("var x = new Error('20')", "var x = Error(\"20\")");
fold("var x = new Array(20)", "var x = Array(20)");
}
public void testSubsituteReturn() {
fold("function f() { while(x) { return }}",
"function f() { while(x) { break }}");
foldSame("function f() { while(x) { return 5 } }");
foldSame("function f() { a: { return 5 } }");
fold("function f() { while(x) { return 5} return 5}",
"function f() { while(x) { break } return 5}");
fold("function f() { while(x) { return x} return x}",
"function f() { while(x) { break } return x}");
fold("function f() { while(x) { if (y) { return }}}",
"function f() { while(x) { if (y) { break }}}");
fold("function f() { while(x) { if (y) { return }} return}",
"function f() { while(x) { if (y) { break }}}");
fold("function f() { while(x) { if (y) { return 5 }} return 5}",
"function f() { while(x) { if (y) { break }} return 5}");
// It doesn't matter if x is changed between them. We are still returning
// x at whatever x value current holds. The whole x = 1 is skipped.
fold("function f() { while(x) { if (y) { return x } x = 1} return x}",
"function f() { while(x) { if (y) { break } x = 1} return x}");
// RemoveUnreachableCode would take care of the useless breaks.
fold("function f() { while(x) { if (y) { return x } return x} return x}",
"function f() { while(x) { if (y) {} break }return x}");
// A break here only breaks out of the inner loop.
foldSame("function f() { while(x) { while (y) { return } } }");
foldSame("function f() { while(1) { return 7} return 5}");
foldSame("function f() {" +
" try { while(x) {return f()}} catch (e) { } return f()}");
foldSame("function f() {" +
" try { while(x) {return f()}} finally {alert(1)} return f()}");
// Both returns has the same handler
fold("function f() {" +
" try { while(x) { return f() } return f() } catch (e) { } }",
"function f() {" +
" try { while(x) { break } return f() } catch (e) { } }");
// We can't fold this because it'll change the order of when foo is called.
foldSame("function f() {" +
" try { while(x) { return foo() } } finally { alert(1) } " +
" return foo()}");
// This is fine, we have no side effect in the return value.
fold("function f() {" +
" try { while(x) { return 1 } } finally { alert(1) } return 1}",
"function f() {" +
" try { while(x) { break } } finally { alert(1) } return 1}"
);
foldSame("function f() { try{ return a } finally { a = 2 } return a; }");
fold(
"function f() { switch(a){ case 1: return a; default: g();} return a;}",
"function f() { switch(a){ case 1: break; default: g();} return a; }");
}
public void testSubsituteBreakForThrow() {
foldSame("function f() { while(x) { throw Error }}");
fold("function f() { while(x) { throw Error } throw Error }",
"function f() { while(x) { break } throw Error}");
foldSame("function f() { while(x) { throw Error(1) } throw Error(2)}");
foldSame("function f() { while(x) { throw Error(1) } return Error(2)}");
foldSame("function f() { while(x) { throw 5 } }");
foldSame("function f() { a: { throw 5 } }");
fold("function f() { while(x) { throw 5} throw 5}",
"function f() { while(x) { break } throw 5}");
fold("function f() { while(x) { throw x} throw x}",
"function f() { while(x) { break } throw x}");
foldSame("function f() { while(x) { if (y) { throw Error }}}");
fold("function f() { while(x) { if (y) { throw Error }} throw Error}",
"function f() { while(x) { if (y) { break }} throw Error}");
fold("function f() { while(x) { if (y) { throw 5 }} throw 5}",
"function f() { while(x) { if (y) { break }} throw 5}");
// It doesn't matter if x is changed between them. We are still throwing
// x at whatever x value current holds. The whole x = 1 is skipped.
fold("function f() { while(x) { if (y) { throw x } x = 1} throw x}",
"function f() { while(x) { if (y) { break } x = 1} throw x}");
// RemoveUnreachableCode would take care of the useless breaks.
fold("function f() { while(x) { if (y) { throw x } throw x} throw x}",
"function f() { while(x) { if (y) {} break }throw x}");
// A break here only breaks out of the inner loop.
foldSame("function f() { while(x) { while (y) { throw Error } } }");
foldSame("function f() { while(1) { throw 7} throw 5}");
foldSame("function f() {" +
" try { while(x) {throw f()}} catch (e) { } throw f()}");
foldSame("function f() {" +
" try { while(x) {throw f()}} finally {alert(1)} throw f()}");
// Both throws has the same handler
fold("function f() {" +
" try { while(x) { throw f() } throw f() } catch (e) { } }",
"function f() {" +
" try { while(x) { break } throw f() } catch (e) { } }");
// We can't fold this because it'll change the order of when foo is called.
foldSame("function f() {" +
" try { while(x) { throw foo() } } finally { alert(1) } " +
" throw foo()}");
// This is fine, we have no side effect in the throw value.
fold("function f() {" +
" try { while(x) { throw 1 } } finally { alert(1) } throw 1}",
"function f() {" +
" try { while(x) { break } } finally { alert(1) } throw 1}"
);
foldSame("function f() { try{ throw a } finally { a = 2 } throw a; }");
fold(
"function f() { switch(a){ case 1: throw a; default: g();} throw a;}",
"function f() { switch(a){ case 1: break; default: g();} throw a; }");
}
public void testRemoveDuplicateReturn() {
fold("function f() { return; }",
"function f(){}");
foldSame("function f() { return a; }");
fold("function f() { if (x) { return a } return a; }",
"function f() { if (x) {} return a; }");
foldSame(
"function f() { try { if (x) { return a } } catch(e) {} return a; }");
foldSame(
"function f() { try { if (x) {} } catch(e) {} return 1; }");
// finally clauses may have side effects
foldSame(
"function f() { try { if (x) { return a } } finally { a++ } return a; }");
// but they don't matter if the result doesn't have side effects and can't
// be affect by side-effects.
fold("function f() { try { if (x) { return 1 } } finally {} return 1; }",
"function f() { try { if (x) {} } finally {} return 1; }");
fold("function f() { switch(a){ case 1: return a; } return a; }",
"function f() { switch(a){ case 1: } return a; }");
fold("function f() { switch(a){ " +
" case 1: return a; case 2: return a; } return a; }",
"function f() { switch(a){ " +
" case 1: break; case 2: } return a; }");
}
public void testRemoveDuplicateThrow() {
foldSame("function f() { throw a; }");
fold("function f() { if (x) { throw a } throw a; }",
"function f() { if (x) {} throw a; }");
foldSame(
"function f() { try { if (x) {throw a} } catch(e) {} throw a; }");
foldSame(
"function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }");
foldSame(
"function f() { try { if (x) {throw 1} } catch(e) {f()} throw 1; }");
foldSame(
"function f() { try { if (x) {throw 1} } catch(e) {throw 1}}");
fold(
"function f() { try { if (x) {throw 1} } catch(e) {throw 1} throw 1; }",
"function f() { try { if (x) {throw 1} } catch(e) {} throw 1; }");
// finally clauses may have side effects
foldSame(
"function f() { try { if (x) { throw a } } finally { a++ } throw a; }");
// but they don't matter if the result doesn't have side effects and can't
// be affect by side-effects.
fold("function f() { try { if (x) { throw 1 } } finally {} throw 1; }",
"function f() { try { if (x) {} } finally {} throw 1; }");
fold("function f() { switch(a){ case 1: throw a; } throw a; }",
"function f() { switch(a){ case 1: } throw a; }");
fold("function f() { switch(a){ " +
"case 1: throw a; case 2: throw a; } throw a; }",
"function f() { switch(a){ case 1: break; case 2: } throw a; }");
}
public void testNestedIfCombine() {
fold("if(x)if(y){while(1){}}", "if(x&&y){while(1){}}");
fold("if(x||z)if(y){while(1){}}", "if((x||z)&&y){while(1){}}");
fold("if(x)if(y||z){while(1){}}", "if((x)&&(y||z)){while(1){}}");
foldSame("if(x||z)if(y||z){while(1){}}");
fold("if(x)if(y){if(z){while(1){}}}", "if(x&&y&&z){while(1){}}");
}
public void testFoldTrueFalse() {
fold("x = true", "x = !0");
fold("x = false", "x = !1");
}
public void testIssue291() {
fold("if (true) { f.onchange(); }", "if (1) f.onchange();");
foldSame("if (f) { f.onchange(); }");
foldSame("if (f) { f.bar(); } else { f.onchange(); }");
fold("if (f) { f.bonchange(); }", "f && f.bonchange();");
foldSame("if (f) { f['x'](); }");
}
public void testUndefined() {
foldSame("var x = undefined");
foldSame("function f(f) {var undefined=2;var x = undefined;}");
this.enableNormalize();
fold("var x = undefined", "var x=void 0");
foldSame(
"var undefined = 1;" +
"function f() {var undefined=2;var x = undefined;}");
foldSame("function f(undefined) {}");
foldSame("try {} catch(undefined) {}");
foldSame("for (undefined in {}) {}");
foldSame("undefined++;");
fold("undefined += undefined;", "undefined += void 0;");
}
public void testSplitCommaExpressions() {
late = false;
// Don't try to split in expressions.
foldSame("while (foo(), !0) boo()");
foldSame("var a = (foo(), !0);");
foldSame("a = (foo(), !0);");
// Don't try to split COMMA under LABELs.
foldSame("a:a(),b()");
fold("(x=2), foo()", "x=2; foo()");
fold("foo(), boo();", "foo(); boo()");
fold("(a(), b()), (c(), d());", "a(); b(); c(); d();");
fold("foo(), true", "foo();1");
fold("function x(){foo(), !0}", "function x(){foo(); 1}");
}
public void testComma1() {
late = false;
fold("1, 2", "1; 1");
late = true;
foldSame("1, 2");
}
public void testComma2() {
late = false;
test("1, a()", "1; a()");
late = true;
foldSame("1, a()");
}
public void testComma3() {
late = false;
test("1, a(), b()", "1; a(); b()");
late = true;
foldSame("1, a(), b()");
}
public void testComma4() {
late = false;
test("a(), b()", "a();b()");
late = true;
foldSame("a(), b()");
}
public void testComma5() {
late = false;
test("a(), b(), 1", "a();b();1");
late = true;
foldSame("a(), b(), 1");
}
public void testObjectLiteral() {
test("({})", "1");
test("({a:1})", "1");
testSame("({a:foo()})");
testSame("({'a':foo()})");
}
public void testArrayLiteral() {
test("([])", "1");
test("([1])", "1");
test("([a])", "1");
testSame("([foo()])");
}
public void testStringArraySplitting() {
testSame("var x=['1','2','3','4']");
testSame("var x=['1','2','3','4','5']");
test("var x=['1','2','3','4','5','6']",
"var x='123456'.split('')");
test("var x=['1','2','3','4','5','00']",
"var x='1 2 3 4 5 00'.split(' ')");
test("var x=['1','2','3','4','5','6','7']",
"var x='1234567'.split('')");
test("var x=['1','2','3','4','5','6','00']",
"var x='1 2 3 4 5 6 00'.split(' ')");
test("var x=[' ,',',',',',',',',',',']",
"var x=' ,;,;,;,;,;,'.split(';')");
test("var x=[',,',' ',',',',',',',',']",
"var x=',,; ;,;,;,;,'.split(';')");
test("var x=['a,',' ',',',',',',',',']",
"var x='a,; ;,;,;,;,'.split(';')");
// all possible delimiters used, leave it alone
testSame("var x=[',', ' ', ';', '{', '}']");
}
public void testRemoveElseCause() {
test("function f() {" +
" if(x) return 1;" +
" else if(x) return 2;" +
" else if(x) return 3 }",
"function f() {" +
" if(x) return 1;" +
"{ if(x) return 2;" +
"{ if(x) return 3 } } }");
}
public void testRemoveElseCause1() {
test("function f() { if (x) throw 1; else f() }",
"function f() { if (x) throw 1; { f() } }");
}
public void testRemoveElseCause2() {
test("function f() { if (x) return 1; else f() }",
"function f() { if (x) return 1; { f() } }");
test("function f() { if (x) return; else f() }",
"function f() { if (x) {} else { f() } }");
// This case is handled by minimize exit points.
testSame("function f() { if (x) return; f() }");
}
public void testRemoveElseCause3() {
testSame("function f() { a:{if (x) break a; else f() } }");
testSame("function f() { if (x) { a:{ break a } } else f() }");
testSame("function f() { if (x) a:{ break a } else f() }");
}
public void testRemoveElseCause4() {
testSame("function f() { if (x) { if (y) { return 1; } } else f() }");
}
public void testBindToCall1() {
test("(goog.bind(f))()", "f()");
test("(goog.bind(f,a))()", "f.call(a)");
test("(goog.bind(f,a,b))()", "f.call(a,b)");
test("(goog.bind(f))(a)", "f(a)");
test("(goog.bind(f,a))(b)", "f.call(a,b)");
test("(goog.bind(f,a,b))(c)", "f.call(a,b,c)");
test("(goog.partial(f))()", "f()");
test("(goog.partial(f,a))()", "f(a)");
test("(goog.partial(f,a,b))()", "f(a,b)");
test("(goog.partial(f))(a)", "f(a)");
test("(goog.partial(f,a))(b)", "f(a,b)");
test("(goog.partial(f,a,b))(c)", "f(a,b,c)");
test("((function(){}).bind())()", "((function(){}))()");
test("((function(){}).bind(a))()", "((function(){})).call(a)");
test("((function(){}).bind(a,b))()", "((function(){})).call(a,b)");
test("((function(){}).bind())(a)", "((function(){}))(a)");
test("((function(){}).bind(a))(b)", "((function(){})).call(a,b)");
test("((function(){}).bind(a,b))(c)", "((function(){})).call(a,b,c)");
// Without using type information we don't know "f" is a function.
testSame("(f.bind())()");
testSame("(f.bind(a))()");
testSame("(f.bind())(a)");
testSame("(f.bind(a))(b)");
// Don't rewrite if the bind isn't the immediate call target
testSame("(goog.bind(f)).call(g)");
}
public void testBindToCall2() {
test("(goog$bind(f))()", "f()");
test("(goog$bind(f,a))()", "f.call(a)");
test("(goog$bind(f,a,b))()", "f.call(a,b)");
test("(goog$bind(f))(a)", "f(a)");
test("(goog$bind(f,a))(b)", "f.call(a,b)");
test("(goog$bind(f,a,b))(c)", "f.call(a,b,c)");
test("(goog$partial(f))()", "f()");
test("(goog$partial(f,a))()", "f(a)");
test("(goog$partial(f,a,b))()", "f(a,b)");
test("(goog$partial(f))(a)", "f(a)");
test("(goog$partial(f,a))(b)", "f(a,b)");
test("(goog$partial(f,a,b))(c)", "f(a,b,c)");
// Don't rewrite if the bind isn't the immediate call target
testSame("(goog$bind(f)).call(g)");
}
public void testBindToCall3() {
// TODO(johnlenz): The code generator wraps free calls with (0,...) to
// prevent leaking "this", but the parser doesn't unfold it, making a
// AST comparison fail. For now do a string comparison to validate the
// correct code is in fact generated.
// The FREE call wrapping should be moved out of the code generator
// and into a denormalizing pass.
new StringCompareTestCase().testBindToCall3();
}
public void testSimpleFunctionCall() {
test("var a = String(23)", "var a = '' + 23");
test("var a = String('hello')", "var a = '' + 'hello'");
testSame("var a = String('hello', bar());");
testSame("var a = String({valueOf: function() { return 1; }});");
}
private static class StringCompareTestCase extends CompilerTestCase {
StringCompareTestCase() {
super("", false);
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
CompilerPass peepholePass =
new PeepholeOptimizationsPass(compiler,
new PeepholeSubstituteAlternateSyntax(false));
return peepholePass;
}
public void testBindToCall3() {
test("(goog.bind(f.m))()", "(0,f.m)()");
test("(goog.bind(f.m,a))()", "f.m.call(a)");
test("(goog.bind(f.m))(a)", "(0,f.m)(a)");
test("(goog.bind(f.m,a))(b)", "f.m.call(a,b)");
test("(goog.partial(f.m))()", "(0,f.m)()");
test("(goog.partial(f.m,a))()", "(0,f.m)(a)");
test("(goog.partial(f.m))(a)", "(0,f.m)(a)");
test("(goog.partial(f.m,a))(b)", "(0,f.m)(a,b)");
// Without using type information we don't know "f" is a function.
testSame("f.m.bind()()");
testSame("f.m.bind(a)()");
testSame("f.m.bind()(a)");
testSame("f.m.bind(a)(b)");
// Don't rewrite if the bind isn't the immediate call target
testSame("goog.bind(f.m).call(g)");
}
}
} |
||
public void testDateDefaultShape() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
// No @JsonFormat => default to user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// Empty @JsonFormat => default to user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// @JsonFormat with Shape.ANY and pattern => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json);
// @JsonFormat with Shape.ANY and locale => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// @JsonFormat with Shape.ANY and timezone => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json);
} | com.fasterxml.jackson.databind.ser.DateSerializationTest::testDateDefaultShape | src/test/java/com/fasterxml/jackson/databind/ser/DateSerializationTest.java | 307 | src/test/java/com/fasterxml/jackson/databind/ser/DateSerializationTest.java | testDateDefaultShape | package com.fasterxml.jackson.databind.ser;
import java.io.*;
import java.text.*;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.*;
public class DateSerializationTest
extends BaseMapTest
{
static class TimeZoneBean {
private TimeZone tz;
public TimeZoneBean(String name) {
tz = TimeZone.getTimeZone(name);
}
public TimeZone getTz() { return tz; }
}
static class DateAsNumberBean {
@JsonFormat(shape=JsonFormat.Shape.NUMBER)
public Date date;
public DateAsNumberBean(long l) { date = new java.util.Date(l); }
}
static class SqlDateAsDefaultBean {
public java.sql.Date date;
public SqlDateAsDefaultBean(long l) { date = new java.sql.Date(l); }
}
static class SqlDateAsNumberBean {
@JsonFormat(shape=JsonFormat.Shape.NUMBER)
public java.sql.Date date;
public SqlDateAsNumberBean(long l) { date = new java.sql.Date(l); }
}
static class DateAsStringBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
public Date date;
public DateAsStringBean(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultStringBean {
@JsonFormat(shape=JsonFormat.Shape.STRING)
public Date date;
public DateAsDefaultStringBean(long l) { date = new java.util.Date(l); }
}
static class DateInCETBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
public Date date;
public DateInCETBean(long l) { date = new java.util.Date(l); }
}
static class CalendarAsStringBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
public Calendar value;
public CalendarAsStringBean(long l) {
value = new GregorianCalendar();
value.setTimeInMillis(l);
}
}
static class DateAsDefaultBean {
public Date date;
public DateAsDefaultBean(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithEmptyJsonFormat {
@JsonFormat
public Date date;
public DateAsDefaultBeanWithEmptyJsonFormat(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithPattern {
@JsonFormat(pattern="yyyy-MM-dd")
public Date date;
public DateAsDefaultBeanWithPattern(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithLocale {
@JsonFormat(locale = "fr")
public Date date;
public DateAsDefaultBeanWithLocale(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithTimezone {
@JsonFormat(timezone="CET")
public Date date;
public DateAsDefaultBeanWithTimezone(long l) { date = new java.util.Date(l); }
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDateNumeric() throws IOException
{
// default is to output time stamps...
assertTrue(MAPPER.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS));
// shouldn't matter which offset we give...
String json = MAPPER.writeValueAsString(new Date(199L));
assertEquals("199", json);
}
public void testDateISO8601() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// let's hit epoch start
String json = mapper.writeValueAsString(new Date(0L));
assertEquals("\"1970-01-01T00:00:00.000+0000\"", json);
}
public void testDateOther() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss");
mapper.setDateFormat(df);
mapper.setTimeZone(TimeZone.getTimeZone("PST"));
// let's hit epoch start, offset by a bit
assertEquals(quote("1969-12-31X16:00:00"), mapper.writeValueAsString(new Date(0L)));
}
@SuppressWarnings("deprecation")
public void testSqlDate() throws IOException
{
// use date 1999-04-01 (note: months are 0-based, use constant)
java.sql.Date date = new java.sql.Date(99, Calendar.APRIL, 1);
assertEquals(quote("1999-04-01"), MAPPER.writeValueAsString(date));
java.sql.Date date0 = new java.sql.Date(0L);
assertEquals(aposToQuotes("{'date':'"+date0.toString()+"'}"),
MAPPER.writeValueAsString(new SqlDateAsDefaultBean(0L)));
// but may explicitly force timestamp too
assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsNumberBean(0L)));
}
public void testSqlTime() throws IOException
{
java.sql.Time time = new java.sql.Time(0L);
// not 100% sure what we should expect wrt timezone, but what serializes
// does use is quite simple:
assertEquals(quote(time.toString()), MAPPER.writeValueAsString(time));
}
public void testSqlTimestamp() throws IOException
{
java.sql.Timestamp input = new java.sql.Timestamp(0L);
// just should produce same output as standard `java.util.Date`:
Date altTnput = new Date(0L);
assertEquals(MAPPER.writeValueAsString(altTnput),
MAPPER.writeValueAsString(input));
}
public void testTimeZone() throws IOException
{
TimeZone input = TimeZone.getTimeZone("PST");
String json = MAPPER.writeValueAsString(input);
assertEquals(quote("PST"), json);
}
public void testTimeZoneInBean() throws IOException
{
String json = MAPPER.writeValueAsString(new TimeZoneBean("PST"));
assertEquals("{\"tz\":\"PST\"}", json);
}
public void testDateUsingObjectWriter() throws IOException
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss");
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals(quote("1969-12-31X16:00:00"),
MAPPER.writer(df)
.with(tz)
.writeValueAsString(new Date(0L)));
ObjectWriter w = MAPPER.writer((DateFormat)null);
assertEquals("0", w.writeValueAsString(new Date(0L)));
w = w.with(df).with(tz);
assertEquals(quote("1969-12-31X16:00:00"), w.writeValueAsString(new Date(0L)));
w = w.with((DateFormat) null);
assertEquals("0", w.writeValueAsString(new Date(0L)));
}
public void testDatesAsMapKeys() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
Map<Date,Integer> map = new HashMap<Date,Integer>();
assertFalse(mapper.isEnabled(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS));
map.put(new Date(0L), Integer.valueOf(1));
// by default will serialize as ISO-8601 values...
assertEquals("{\"1970-01-01T00:00:00.000+0000\":1}", mapper.writeValueAsString(map));
// but can change to use timestamps too
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true);
assertEquals("{\"0\":1}", mapper.writeValueAsString(map));
}
public void testDateWithJsonFormat() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
String json;
// first: test overriding writing as timestamp
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsNumberBean(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
// then reverse
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new DateAsStringBean(0L));
assertEquals("{\"date\":\"1970-01-01\"}", json);
// and with different DateFormat; CET is one hour ahead of GMT
json = mapper.writeValueAsString(new DateInCETBean(0L));
assertEquals("{\"date\":\"1970-01-01,01:00\"}", json);
// and for [Issue#423] as well:
json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new CalendarAsStringBean(0L));
assertEquals("{\"value\":\"1970-01-01\"}", json);
// and with default (ISO8601) format (databind#1109)
json = mapper.writeValueAsString(new DateAsDefaultStringBean(0L));
assertEquals("{\"date\":\"1970-01-01T00:00:00.000+0000\"}", json);
}
/**
* Test to ensure that setting a TimeZone _after_ dateformat should enforce
* that timezone on format, regardless of TimeZone format had.
*/
public void testWithTimeZoneOverride() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd/HH:mm z"));
mapper.setTimeZone(TimeZone.getTimeZone("PST"));
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String json = mapper.writeValueAsString(new Date(0));
// pacific time is GMT-8; so midnight becomes 16:00 previous day:
assertEquals(quote("1969-12-31/16:00 PST"), json);
// Let's also verify that Locale won't matter too much...
mapper.setLocale(Locale.FRANCE);
json = mapper.writeValueAsString(new Date(0));
assertEquals(quote("1969-12-31/16:00 PST"), json);
// Also: should be able to dynamically change timezone:
ObjectWriter w = mapper.writer();
w = w.with(TimeZone.getTimeZone("EST"));
json = w.writeValueAsString(new Date(0));
assertEquals(quote("1969-12-31/19:00 EST"), json);
}
/**
* Test to ensure that the default shape is correctly inferred as string or numeric,
* when this shape is not explicitly set with a <code>@JsonFormat</code> annotation
*/
public void testDateDefaultShape() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
// No @JsonFormat => default to user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// Empty @JsonFormat => default to user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// @JsonFormat with Shape.ANY and pattern => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json);
// @JsonFormat with Shape.ANY and locale => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// @JsonFormat with Shape.ANY and timezone => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json);
}
}
| // You are a professional Java test case writer, please create a test case named `testDateDefaultShape` for the issue `JacksonDatabind-1155`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1155
//
// ## Issue-Title:
// Fix for #1154
//
// ## Issue-Description:
// Looks pretty good, but would it be possible to have a unit test that would fail before fix, pass after? Would be great to have something to guard against regression.
//
//
// I may want to change the logic a little bit, however; if shape is explicitly defined as `NUMBER`, textual representation should not be enabled even if `Locale` (etc) happen to be specified: explicit shape value should have precedence. I can make that change, or you can do it, either way is fine.
//
// I'll also need to merge this again 2.7 branch instead of master, to get in 2.7.3.
//
//
//
//
public void testDateDefaultShape() throws Exception {
| 307 | /**
* Test to ensure that the default shape is correctly inferred as string or numeric,
* when this shape is not explicitly set with a <code>@JsonFormat</code> annotation
*/ | 45 | 265 | src/test/java/com/fasterxml/jackson/databind/ser/DateSerializationTest.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1155
## Issue-Title:
Fix for #1154
## Issue-Description:
Looks pretty good, but would it be possible to have a unit test that would fail before fix, pass after? Would be great to have something to guard against regression.
I may want to change the logic a little bit, however; if shape is explicitly defined as `NUMBER`, textual representation should not be enabled even if `Locale` (etc) happen to be specified: explicit shape value should have precedence. I can make that change, or you can do it, either way is fine.
I'll also need to merge this again 2.7 branch instead of master, to get in 2.7.3.
```
You are a professional Java test case writer, please create a test case named `testDateDefaultShape` for the issue `JacksonDatabind-1155`, utilizing the provided issue report information and the following function signature.
```java
public void testDateDefaultShape() throws Exception {
```
| 265 | [
"com.fasterxml.jackson.databind.ser.std.DateTimeSerializerBase"
] | 698c64a37dd383f5c7f03008373bed75b791b82b6a79724d3485b9bf90a3da32 | public void testDateDefaultShape() throws Exception
| // You are a professional Java test case writer, please create a test case named `testDateDefaultShape` for the issue `JacksonDatabind-1155`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1155
//
// ## Issue-Title:
// Fix for #1154
//
// ## Issue-Description:
// Looks pretty good, but would it be possible to have a unit test that would fail before fix, pass after? Would be great to have something to guard against regression.
//
//
// I may want to change the logic a little bit, however; if shape is explicitly defined as `NUMBER`, textual representation should not be enabled even if `Locale` (etc) happen to be specified: explicit shape value should have precedence. I can make that change, or you can do it, either way is fine.
//
// I'll also need to merge this again 2.7 branch instead of master, to get in 2.7.3.
//
//
//
//
| JacksonDatabind | package com.fasterxml.jackson.databind.ser;
import java.io.*;
import java.text.*;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.*;
public class DateSerializationTest
extends BaseMapTest
{
static class TimeZoneBean {
private TimeZone tz;
public TimeZoneBean(String name) {
tz = TimeZone.getTimeZone(name);
}
public TimeZone getTz() { return tz; }
}
static class DateAsNumberBean {
@JsonFormat(shape=JsonFormat.Shape.NUMBER)
public Date date;
public DateAsNumberBean(long l) { date = new java.util.Date(l); }
}
static class SqlDateAsDefaultBean {
public java.sql.Date date;
public SqlDateAsDefaultBean(long l) { date = new java.sql.Date(l); }
}
static class SqlDateAsNumberBean {
@JsonFormat(shape=JsonFormat.Shape.NUMBER)
public java.sql.Date date;
public SqlDateAsNumberBean(long l) { date = new java.sql.Date(l); }
}
static class DateAsStringBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
public Date date;
public DateAsStringBean(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultStringBean {
@JsonFormat(shape=JsonFormat.Shape.STRING)
public Date date;
public DateAsDefaultStringBean(long l) { date = new java.util.Date(l); }
}
static class DateInCETBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
public Date date;
public DateInCETBean(long l) { date = new java.util.Date(l); }
}
static class CalendarAsStringBean {
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
public Calendar value;
public CalendarAsStringBean(long l) {
value = new GregorianCalendar();
value.setTimeInMillis(l);
}
}
static class DateAsDefaultBean {
public Date date;
public DateAsDefaultBean(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithEmptyJsonFormat {
@JsonFormat
public Date date;
public DateAsDefaultBeanWithEmptyJsonFormat(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithPattern {
@JsonFormat(pattern="yyyy-MM-dd")
public Date date;
public DateAsDefaultBeanWithPattern(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithLocale {
@JsonFormat(locale = "fr")
public Date date;
public DateAsDefaultBeanWithLocale(long l) { date = new java.util.Date(l); }
}
static class DateAsDefaultBeanWithTimezone {
@JsonFormat(timezone="CET")
public Date date;
public DateAsDefaultBeanWithTimezone(long l) { date = new java.util.Date(l); }
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDateNumeric() throws IOException
{
// default is to output time stamps...
assertTrue(MAPPER.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS));
// shouldn't matter which offset we give...
String json = MAPPER.writeValueAsString(new Date(199L));
assertEquals("199", json);
}
public void testDateISO8601() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// let's hit epoch start
String json = mapper.writeValueAsString(new Date(0L));
assertEquals("\"1970-01-01T00:00:00.000+0000\"", json);
}
public void testDateOther() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss");
mapper.setDateFormat(df);
mapper.setTimeZone(TimeZone.getTimeZone("PST"));
// let's hit epoch start, offset by a bit
assertEquals(quote("1969-12-31X16:00:00"), mapper.writeValueAsString(new Date(0L)));
}
@SuppressWarnings("deprecation")
public void testSqlDate() throws IOException
{
// use date 1999-04-01 (note: months are 0-based, use constant)
java.sql.Date date = new java.sql.Date(99, Calendar.APRIL, 1);
assertEquals(quote("1999-04-01"), MAPPER.writeValueAsString(date));
java.sql.Date date0 = new java.sql.Date(0L);
assertEquals(aposToQuotes("{'date':'"+date0.toString()+"'}"),
MAPPER.writeValueAsString(new SqlDateAsDefaultBean(0L)));
// but may explicitly force timestamp too
assertEquals(aposToQuotes("{'date':0}"), MAPPER.writeValueAsString(new SqlDateAsNumberBean(0L)));
}
public void testSqlTime() throws IOException
{
java.sql.Time time = new java.sql.Time(0L);
// not 100% sure what we should expect wrt timezone, but what serializes
// does use is quite simple:
assertEquals(quote(time.toString()), MAPPER.writeValueAsString(time));
}
public void testSqlTimestamp() throws IOException
{
java.sql.Timestamp input = new java.sql.Timestamp(0L);
// just should produce same output as standard `java.util.Date`:
Date altTnput = new Date(0L);
assertEquals(MAPPER.writeValueAsString(altTnput),
MAPPER.writeValueAsString(input));
}
public void testTimeZone() throws IOException
{
TimeZone input = TimeZone.getTimeZone("PST");
String json = MAPPER.writeValueAsString(input);
assertEquals(quote("PST"), json);
}
public void testTimeZoneInBean() throws IOException
{
String json = MAPPER.writeValueAsString(new TimeZoneBean("PST"));
assertEquals("{\"tz\":\"PST\"}", json);
}
public void testDateUsingObjectWriter() throws IOException
{
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'X'HH:mm:ss");
TimeZone tz = TimeZone.getTimeZone("PST");
assertEquals(quote("1969-12-31X16:00:00"),
MAPPER.writer(df)
.with(tz)
.writeValueAsString(new Date(0L)));
ObjectWriter w = MAPPER.writer((DateFormat)null);
assertEquals("0", w.writeValueAsString(new Date(0L)));
w = w.with(df).with(tz);
assertEquals(quote("1969-12-31X16:00:00"), w.writeValueAsString(new Date(0L)));
w = w.with((DateFormat) null);
assertEquals("0", w.writeValueAsString(new Date(0L)));
}
public void testDatesAsMapKeys() throws IOException
{
ObjectMapper mapper = new ObjectMapper();
Map<Date,Integer> map = new HashMap<Date,Integer>();
assertFalse(mapper.isEnabled(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS));
map.put(new Date(0L), Integer.valueOf(1));
// by default will serialize as ISO-8601 values...
assertEquals("{\"1970-01-01T00:00:00.000+0000\":1}", mapper.writeValueAsString(map));
// but can change to use timestamps too
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true);
assertEquals("{\"0\":1}", mapper.writeValueAsString(map));
}
public void testDateWithJsonFormat() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
String json;
// first: test overriding writing as timestamp
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsNumberBean(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
// then reverse
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new DateAsStringBean(0L));
assertEquals("{\"date\":\"1970-01-01\"}", json);
// and with different DateFormat; CET is one hour ahead of GMT
json = mapper.writeValueAsString(new DateInCETBean(0L));
assertEquals("{\"date\":\"1970-01-01,01:00\"}", json);
// and for [Issue#423] as well:
json = mapper.writer().with(getUTCTimeZone()).writeValueAsString(new CalendarAsStringBean(0L));
assertEquals("{\"value\":\"1970-01-01\"}", json);
// and with default (ISO8601) format (databind#1109)
json = mapper.writeValueAsString(new DateAsDefaultStringBean(0L));
assertEquals("{\"date\":\"1970-01-01T00:00:00.000+0000\"}", json);
}
/**
* Test to ensure that setting a TimeZone _after_ dateformat should enforce
* that timezone on format, regardless of TimeZone format had.
*/
public void testWithTimeZoneOverride() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd/HH:mm z"));
mapper.setTimeZone(TimeZone.getTimeZone("PST"));
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String json = mapper.writeValueAsString(new Date(0));
// pacific time is GMT-8; so midnight becomes 16:00 previous day:
assertEquals(quote("1969-12-31/16:00 PST"), json);
// Let's also verify that Locale won't matter too much...
mapper.setLocale(Locale.FRANCE);
json = mapper.writeValueAsString(new Date(0));
assertEquals(quote("1969-12-31/16:00 PST"), json);
// Also: should be able to dynamically change timezone:
ObjectWriter w = mapper.writer();
w = w.with(TimeZone.getTimeZone("EST"));
json = w.writeValueAsString(new Date(0));
assertEquals(quote("1969-12-31/19:00 EST"), json);
}
/**
* Test to ensure that the default shape is correctly inferred as string or numeric,
* when this shape is not explicitly set with a <code>@JsonFormat</code> annotation
*/
public void testDateDefaultShape() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
// No @JsonFormat => default to user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBean(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// Empty @JsonFormat => default to user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
assertEquals(aposToQuotes("{'date':0}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithEmptyJsonFormat(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// @JsonFormat with Shape.ANY and pattern => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithPattern(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01'}"), json);
// @JsonFormat with Shape.ANY and locale => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithLocale(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T00:00:00.000+0000'}"), json);
// @JsonFormat with Shape.ANY and timezone => STRING shape, regardless of user config
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
json = mapper.writeValueAsString(new DateAsDefaultBeanWithTimezone(0L));
assertEquals(aposToQuotes("{'date':'1970-01-01T01:00:00.000+0100'}"), json);
}
}
|
|
public void testParseProperInvalidMinus() {
String source = "2 -2 / 3";
try {
Fraction c = properFormat.parse(source);
fail("invalid minus in improper fraction.");
} catch (ParseException ex) {
// expected
}
source = "2 2 / -3";
try {
Fraction c = properFormat.parse(source);
fail("invalid minus in improper fraction.");
} catch (ParseException ex) {
// expected
}
} | org.apache.commons.math.fraction.FractionFormatTest::testParseProperInvalidMinus | src/test/org/apache/commons/math/fraction/FractionFormatTest.java | 246 | src/test/org/apache/commons/math/fraction/FractionFormatTest.java | testParseProperInvalidMinus | /*
* Copyright 2004 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.math.fraction;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import junit.framework.TestCase;
public class FractionFormatTest extends TestCase {
FractionFormat properFormat = null;
FractionFormat improperFormat = null;
protected Locale getLocale() {
return Locale.getDefault();
}
protected void setUp() throws Exception {
properFormat = FractionFormat.getProperInstance(getLocale());
improperFormat = FractionFormat.getImproperInstance(getLocale());
}
public void testFormat() {
Fraction c = new Fraction(1, 2);
String expected = "1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatNegative() {
Fraction c = new Fraction(-1, 2);
String expected = "-1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatZero() {
Fraction c = new Fraction(0, 1);
String expected = "0 / 1";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatImproper() {
Fraction c = new Fraction(5, 3);
String actual = properFormat.format(c);
assertEquals("1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("5 / 3", actual);
}
public void testFormatImproperNegative() {
Fraction c = new Fraction(-5, 3);
String actual = properFormat.format(c);
assertEquals("-1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("-5 / 3", actual);
}
public void testParse() {
String source = "1 / 2";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInteger() {
String source = "10";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
Fraction c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInvalid() {
String source = "a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseInvalidDenominator() {
String source = "10 / a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseNegative() {
try {
String source = "-1 / 2";
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
source = "1 / -2";
c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseProper() {
String source = "1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testParseProperNegative() {
String source = "-1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testParseProperInvalidMinus() {
String source = "2 -2 / 3";
try {
Fraction c = properFormat.parse(source);
fail("invalid minus in improper fraction.");
} catch (ParseException ex) {
// expected
}
source = "2 2 / -3";
try {
Fraction c = properFormat.parse(source);
fail("invalid minus in improper fraction.");
} catch (ParseException ex) {
// expected
}
}
public void testNumeratorFormat() {
NumberFormat old = properFormat.getNumeratorFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
properFormat.setNumeratorFormat(nf);
assertEquals(nf, properFormat.getNumeratorFormat());
properFormat.setNumeratorFormat(old);
old = improperFormat.getNumeratorFormat();
nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
improperFormat.setNumeratorFormat(nf);
assertEquals(nf, improperFormat.getNumeratorFormat());
improperFormat.setNumeratorFormat(old);
}
public void testDenominatorFormat() {
NumberFormat old = properFormat.getDenominatorFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
properFormat.setDenominatorFormat(nf);
assertEquals(nf, properFormat.getDenominatorFormat());
properFormat.setDenominatorFormat(old);
old = improperFormat.getDenominatorFormat();
nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
improperFormat.setDenominatorFormat(nf);
assertEquals(nf, improperFormat.getDenominatorFormat());
improperFormat.setDenominatorFormat(old);
}
public void testWholeFormat() {
ProperFractionFormat format = (ProperFractionFormat)properFormat;
NumberFormat old = format.getWholeFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
format.setWholeFormat(nf);
assertEquals(nf, format.getWholeFormat());
format.setWholeFormat(old);
}
} | // You are a professional Java test case writer, please create a test case named `testParseProperInvalidMinus` for the issue `Math-MATH-60`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-60
//
// ## Issue-Title:
// [math] Function math.fraction.ProperFractionFormat.parse(String, ParsePosition) return illogical result
//
// ## Issue-Description:
//
// Hello,
//
//
// I find illogical returned result from function "Fraction parse(String source,
//
// ParsePostion pos)" (in class ProperFractionFormat of the Fraction Package) of
//
// the Commons Math library. Please see the following code segment for more
//
// details:
//
//
// "
//
// ProperFractionFormat properFormat = new ProperFractionFormat();
//
// result = null;
//
// String source = "1 -1 / 2";
//
// ParsePosition pos = new ParsePosition(0);
//
//
// //Test 1 : fail
//
// public void testParseNegative(){
//
//
// String source = "-1 -2 / 3";
//
// ParsePosition pos = new ParsePosition(0);
//
//
// Fraction actual = properFormat.parse(source, pos);
//
// assertNull(actual);
//
// }
//
//
// // Test2: success
//
// public void testParseNegative(){
//
//
// String source = "-1 -2 / 3";
//
// ParsePosition pos = new ParsePosition(0);
//
//
// Fraction actual = properFormat.parse(source, pos); // return Fraction 1/3
//
// assertEquals(1, source.getNumerator());
//
// assertEquals(3, source.getDenominator());
//
// }
//
//
// "
//
//
// Note: Similarly, when I passed in the following inputs:
//
// input 2: (source = “1 2 / -3”, pos = 0)
//
// input 3: ( source = ” -1 -2 / 3”, pos = 0)
//
//
// Function "Fraction parse(String, ParsePosition)" returned Fraction 1/3 (means
//
// the result Fraction had numerator = 1 and denominator = 3)for all 3 inputs
//
// above.
//
//
// I think the function does not handle parsing the numberator/ denominator
//
// properly incase input string provide invalid numerator/denominator.
//
//
// Thank you!
//
//
//
//
//
public void testParseProperInvalidMinus() {
| 246 | 106 | 231 | src/test/org/apache/commons/math/fraction/FractionFormatTest.java | src/test | ```markdown
## Issue-ID: Math-MATH-60
## Issue-Title:
[math] Function math.fraction.ProperFractionFormat.parse(String, ParsePosition) return illogical result
## Issue-Description:
Hello,
I find illogical returned result from function "Fraction parse(String source,
ParsePostion pos)" (in class ProperFractionFormat of the Fraction Package) of
the Commons Math library. Please see the following code segment for more
details:
"
ProperFractionFormat properFormat = new ProperFractionFormat();
result = null;
String source = "1 -1 / 2";
ParsePosition pos = new ParsePosition(0);
//Test 1 : fail
public void testParseNegative(){
String source = "-1 -2 / 3";
ParsePosition pos = new ParsePosition(0);
Fraction actual = properFormat.parse(source, pos);
assertNull(actual);
}
// Test2: success
public void testParseNegative(){
String source = "-1 -2 / 3";
ParsePosition pos = new ParsePosition(0);
Fraction actual = properFormat.parse(source, pos); // return Fraction 1/3
assertEquals(1, source.getNumerator());
assertEquals(3, source.getDenominator());
}
"
Note: Similarly, when I passed in the following inputs:
input 2: (source = “1 2 / -3”, pos = 0)
input 3: ( source = ” -1 -2 / 3”, pos = 0)
Function "Fraction parse(String, ParsePosition)" returned Fraction 1/3 (means
the result Fraction had numerator = 1 and denominator = 3)for all 3 inputs
above.
I think the function does not handle parsing the numberator/ denominator
properly incase input string provide invalid numerator/denominator.
Thank you!
```
You are a professional Java test case writer, please create a test case named `testParseProperInvalidMinus` for the issue `Math-MATH-60`, utilizing the provided issue report information and the following function signature.
```java
public void testParseProperInvalidMinus() {
```
| 231 | [
"org.apache.commons.math.fraction.ProperFractionFormat"
] | 699ba8d6e9d2f024c08acf89bde04104e04b4caf51696158da1dc06ebbceb0cc | public void testParseProperInvalidMinus() | // You are a professional Java test case writer, please create a test case named `testParseProperInvalidMinus` for the issue `Math-MATH-60`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-60
//
// ## Issue-Title:
// [math] Function math.fraction.ProperFractionFormat.parse(String, ParsePosition) return illogical result
//
// ## Issue-Description:
//
// Hello,
//
//
// I find illogical returned result from function "Fraction parse(String source,
//
// ParsePostion pos)" (in class ProperFractionFormat of the Fraction Package) of
//
// the Commons Math library. Please see the following code segment for more
//
// details:
//
//
// "
//
// ProperFractionFormat properFormat = new ProperFractionFormat();
//
// result = null;
//
// String source = "1 -1 / 2";
//
// ParsePosition pos = new ParsePosition(0);
//
//
// //Test 1 : fail
//
// public void testParseNegative(){
//
//
// String source = "-1 -2 / 3";
//
// ParsePosition pos = new ParsePosition(0);
//
//
// Fraction actual = properFormat.parse(source, pos);
//
// assertNull(actual);
//
// }
//
//
// // Test2: success
//
// public void testParseNegative(){
//
//
// String source = "-1 -2 / 3";
//
// ParsePosition pos = new ParsePosition(0);
//
//
// Fraction actual = properFormat.parse(source, pos); // return Fraction 1/3
//
// assertEquals(1, source.getNumerator());
//
// assertEquals(3, source.getDenominator());
//
// }
//
//
// "
//
//
// Note: Similarly, when I passed in the following inputs:
//
// input 2: (source = “1 2 / -3”, pos = 0)
//
// input 3: ( source = ” -1 -2 / 3”, pos = 0)
//
//
// Function "Fraction parse(String, ParsePosition)" returned Fraction 1/3 (means
//
// the result Fraction had numerator = 1 and denominator = 3)for all 3 inputs
//
// above.
//
//
// I think the function does not handle parsing the numberator/ denominator
//
// properly incase input string provide invalid numerator/denominator.
//
//
// Thank you!
//
//
//
//
//
| Math | /*
* Copyright 2004 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.math.fraction;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import junit.framework.TestCase;
public class FractionFormatTest extends TestCase {
FractionFormat properFormat = null;
FractionFormat improperFormat = null;
protected Locale getLocale() {
return Locale.getDefault();
}
protected void setUp() throws Exception {
properFormat = FractionFormat.getProperInstance(getLocale());
improperFormat = FractionFormat.getImproperInstance(getLocale());
}
public void testFormat() {
Fraction c = new Fraction(1, 2);
String expected = "1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatNegative() {
Fraction c = new Fraction(-1, 2);
String expected = "-1 / 2";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatZero() {
Fraction c = new Fraction(0, 1);
String expected = "0 / 1";
String actual = properFormat.format(c);
assertEquals(expected, actual);
actual = improperFormat.format(c);
assertEquals(expected, actual);
}
public void testFormatImproper() {
Fraction c = new Fraction(5, 3);
String actual = properFormat.format(c);
assertEquals("1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("5 / 3", actual);
}
public void testFormatImproperNegative() {
Fraction c = new Fraction(-5, 3);
String actual = properFormat.format(c);
assertEquals("-1 2 / 3", actual);
actual = improperFormat.format(c);
assertEquals("-5 / 3", actual);
}
public void testParse() {
String source = "1 / 2";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInteger() {
String source = "10";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
Fraction c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(10, c.getNumerator());
assertEquals(1, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseInvalid() {
String source = "a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseInvalidDenominator() {
String source = "10 / a";
String msg = "should not be able to parse '10 / a'.";
try {
properFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
try {
improperFormat.parse(source);
fail(msg);
} catch (ParseException ex) {
// success
}
}
public void testParseNegative() {
try {
String source = "-1 / 2";
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
source = "1 / -2";
c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
c = improperFormat.parse(source);
assertNotNull(c);
assertEquals(-1, c.getNumerator());
assertEquals(2, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
}
public void testParseProper() {
String source = "1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testParseProperNegative() {
String source = "-1 2 / 3";
try {
Fraction c = properFormat.parse(source);
assertNotNull(c);
assertEquals(-5, c.getNumerator());
assertEquals(3, c.getDenominator());
} catch (ParseException ex) {
fail(ex.getMessage());
}
try {
improperFormat.parse(source);
fail("invalid improper fraction.");
} catch (ParseException ex) {
// success
}
}
public void testParseProperInvalidMinus() {
String source = "2 -2 / 3";
try {
Fraction c = properFormat.parse(source);
fail("invalid minus in improper fraction.");
} catch (ParseException ex) {
// expected
}
source = "2 2 / -3";
try {
Fraction c = properFormat.parse(source);
fail("invalid minus in improper fraction.");
} catch (ParseException ex) {
// expected
}
}
public void testNumeratorFormat() {
NumberFormat old = properFormat.getNumeratorFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
properFormat.setNumeratorFormat(nf);
assertEquals(nf, properFormat.getNumeratorFormat());
properFormat.setNumeratorFormat(old);
old = improperFormat.getNumeratorFormat();
nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
improperFormat.setNumeratorFormat(nf);
assertEquals(nf, improperFormat.getNumeratorFormat());
improperFormat.setNumeratorFormat(old);
}
public void testDenominatorFormat() {
NumberFormat old = properFormat.getDenominatorFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
properFormat.setDenominatorFormat(nf);
assertEquals(nf, properFormat.getDenominatorFormat());
properFormat.setDenominatorFormat(old);
old = improperFormat.getDenominatorFormat();
nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
improperFormat.setDenominatorFormat(nf);
assertEquals(nf, improperFormat.getDenominatorFormat());
improperFormat.setDenominatorFormat(old);
}
public void testWholeFormat() {
ProperFractionFormat format = (ProperFractionFormat)properFormat;
NumberFormat old = format.getWholeFormat();
NumberFormat nf = NumberFormat.getInstance();
nf.setParseIntegerOnly(true);
format.setWholeFormat(nf);
assertEquals(nf, format.getWholeFormat());
format.setWholeFormat(old);
}
} |
||
@Test
public void handlesLTinScript() {
// https://github.com/jhy/jsoup/issues/1139
String html = "<script> var a=\"<?\"; var b=\"?>\"; </script>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<script> var a=\"\n <!--?\"; var b=\"?-->\"; </script>", doc.html()); // converted from pseudo xmldecl to comment
} | org.jsoup.parser.XmlTreeBuilderTest::handlesLTinScript | src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java | 246 | src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java | handlesLTinScript | package org.jsoup.parser;
import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.CDataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.nodes.XmlDeclaration;
import org.jsoup.select.Elements;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import static org.jsoup.nodes.Document.OutputSettings.Syntax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* Tests XmlTreeBuilder.
*
* @author Jonathan Hedley
*/
public class XmlTreeBuilderTest {
@Test
public void testSimpleXmlParse() {
String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, "http://foo.com/");
assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>",
TextUtil.stripNewlines(doc.html()));
assertEquals(doc.getElementById("2").absUrl("href"), "http://foo.com/bar");
}
@Test
public void testPopToClose() {
// test: </val> closes Two, </bar> ignored
String xml = "<doc><val>One<val>Two</val></bar>Three</doc>";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, "http://foo.com/");
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testCommentAndDocType() {
String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, "http://foo.com/");
assertEquals("<!DOCTYPE HTML><!-- a comment -->One <qux />Two",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testSupplyParserToJsoupClass() {
String xml = "<doc><val>One<val>Two</val></bar>Three</doc>";
Document doc = Jsoup.parse(xml, "http://foo.com/", Parser.xmlParser());
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(doc.html()));
}
@Ignore
@Test
public void testSupplyParserToConnection() throws IOException {
String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml";
// parse with both xml and html parser, ensure different
Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get();
Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get();
Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(xmlDoc.html()));
assertFalse(htmlDoc.equals(xmlDoc));
assertEquals(xmlDoc, autoXmlDoc);
assertEquals(1, htmlDoc.select("head").size()); // html parser normalises
assertEquals(0, xmlDoc.select("head").size()); // xml parser does not
assertEquals(0, autoXmlDoc.select("head").size()); // xml parser does not
}
@Test
public void testSupplyParserToDataStream() throws IOException, URISyntaxException {
File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI());
InputStream inStream = new FileInputStream(xmlFile);
Document doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser());
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testDoesNotForceSelfClosingKnownTags() {
// html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag.
Document htmlDoc = Jsoup.parse("<br>one</br>");
assertEquals("<br>one\n<br>", htmlDoc.body().html());
Document xmlDoc = Jsoup.parse("<br>one</br>", "", Parser.xmlParser());
assertEquals("<br>one</br>", xmlDoc.html());
}
@Test public void handlesXmlDeclarationAsDeclaration() {
String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->",
StringUtil.normaliseWhitespace(doc.outerHtml()));
assertEquals("#declaration", doc.childNode(0).nodeName());
assertEquals("#comment", doc.childNode(2).nodeName());
}
@Test public void xmlFragment() {
String xml = "<one src='/foo/' />Two<three><four /></three>";
List<Node> nodes = Parser.parseXmlFragment(xml, "http://example.com/");
assertEquals(3, nodes.size());
assertEquals("http://example.com/foo/", nodes.get(0).absUrl("src"));
assertEquals("one", nodes.get(0).nodeName());
assertEquals("Two", ((TextNode)nodes.get(1)).text());
}
@Test public void xmlParseDefaultsToHtmlOutputSyntax() {
Document doc = Jsoup.parse("x", "", Parser.xmlParser());
assertEquals(Syntax.xml, doc.outputSettings().syntax());
}
@Test
public void testDoesHandleEOFInTag() {
String html = "<img src=asdf onerror=\"alert(1)\" x=";
Document xmlDoc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html());
}
@Test
public void testDetectCharsetEncodingDeclaration() throws IOException, URISyntaxException {
File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI());
InputStream inStream = new FileInputStream(xmlFile);
Document doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser());
assertEquals("ISO-8859-1", doc.charset().name());
assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testParseDeclarationAttributes() {
String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
XmlDeclaration decl = (XmlDeclaration) doc.childNode(0);
assertEquals("1", decl.attr("version"));
assertEquals("UTF-8", decl.attr("encoding"));
assertEquals("else", decl.attr("something"));
assertEquals("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration());
assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml());
}
@Test
public void caseSensitiveDeclaration() {
String xml = "<?XML version='1' encoding='UTF-8' something='else'?>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml());
}
@Test
public void testCreatesValidProlog() {
Document document = Document.createShell("");
document.outputSettings().syntax(Syntax.xml);
document.charset(Charset.forName("utf-8"));
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<html>\n" +
" <head></head>\n" +
" <body></body>\n" +
"</html>", document.outerHtml());
}
@Test
public void preservesCaseByDefault() {
String xml = "<CHECK>One</CHECK><TEST ID=1>Check</TEST>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals("<CHECK>One</CHECK><TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html()));
}
@Test
public void appendPreservesCaseByDefault() {
String xml = "<One>One</One>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements one = doc.select("One");
one.append("<Two ID=2>Two</Two>");
assertEquals("<One>One<Two ID=\"2\">Two</Two></One>", TextUtil.stripNewlines(doc.html()));
}
@Test
public void canNormalizeCase() {
String xml = "<TEST ID=1>Check</TEST>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault));
assertEquals("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html()));
}
@Test public void normalizesDiscordantTags() {
Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault);
Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser);
assertEquals("<div>\n test\n</div>\n<p></p>", document.html());
// was failing -> toString() = "<div>\n test\n <p></p>\n</div>"
}
@Test public void roundTripsCdata() {
String xml = "<div id=1><![CDATA[\n<html>\n <foo><&]]></div>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Element div = doc.getElementById("1");
assertEquals("<html>\n <foo><&", div.text());
assertEquals(0, div.children().size());
assertEquals(1, div.childNodeSize()); // no elements, one text node
assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&]]>\n</div>", div.outerHtml());
CDataNode cdata = (CDataNode) div.textNodes().get(0);
assertEquals("\n<html>\n <foo><&", cdata.text());
}
@Test public void cdataPreservesWhiteSpace() {
String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals(xml, doc.outerHtml());
assertEquals("//\n\n foo();\n//", doc.selectFirst("script").text());
}
@Test
public void handlesDodgyXmlDecl() {
String xml = "<?xml version='1.0'><val>One</val>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals("One", doc.select("val").text());
}
@Test
public void handlesLTinScript() {
// https://github.com/jhy/jsoup/issues/1139
String html = "<script> var a=\"<?\"; var b=\"?>\"; </script>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<script> var a=\"\n <!--?\"; var b=\"?-->\"; </script>", doc.html()); // converted from pseudo xmldecl to comment
}
} | // You are a professional Java test case writer, please create a test case named `handlesLTinScript` for the issue `Jsoup-1139`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-1139
//
// ## Issue-Title:
// Jsoup 1.11.3: IndexOutOfBoundsException
//
// ## Issue-Description:
// Hi, I am using Jsoup 1.11.3. While trying to parse HTML content, I'm getting IndexOutOfBoundsException.
//
//
// I am using such Jsoup call as this is the only way to parse iframe content.
//
//
// Jsoup call:
//
//
// `Jsoup.parse(html, "", Parser.xmlParser())`
//
//
// HTML is here: <https://files.fm/u/v43yemgb>. I can't add it to the body as it's huge.
//
//
//
//
@Test
public void handlesLTinScript() {
| 246 | 86 | 240 | src/test/java/org/jsoup/parser/XmlTreeBuilderTest.java | src/test/java | ```markdown
## Issue-ID: Jsoup-1139
## Issue-Title:
Jsoup 1.11.3: IndexOutOfBoundsException
## Issue-Description:
Hi, I am using Jsoup 1.11.3. While trying to parse HTML content, I'm getting IndexOutOfBoundsException.
I am using such Jsoup call as this is the only way to parse iframe content.
Jsoup call:
`Jsoup.parse(html, "", Parser.xmlParser())`
HTML is here: <https://files.fm/u/v43yemgb>. I can't add it to the body as it's huge.
```
You are a professional Java test case writer, please create a test case named `handlesLTinScript` for the issue `Jsoup-1139`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void handlesLTinScript() {
```
| 240 | [
"org.jsoup.nodes.Comment"
] | 69ef6fbd3fcee75d102474ad2c583956f03f2ad80209435eb2d74c5c8d8526f7 | @Test
public void handlesLTinScript() | // You are a professional Java test case writer, please create a test case named `handlesLTinScript` for the issue `Jsoup-1139`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Jsoup-1139
//
// ## Issue-Title:
// Jsoup 1.11.3: IndexOutOfBoundsException
//
// ## Issue-Description:
// Hi, I am using Jsoup 1.11.3. While trying to parse HTML content, I'm getting IndexOutOfBoundsException.
//
//
// I am using such Jsoup call as this is the only way to parse iframe content.
//
//
// Jsoup call:
//
//
// `Jsoup.parse(html, "", Parser.xmlParser())`
//
//
// HTML is here: <https://files.fm/u/v43yemgb>. I can't add it to the body as it's huge.
//
//
//
//
| Jsoup | package org.jsoup.parser;
import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.CDataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.nodes.XmlDeclaration;
import org.jsoup.select.Elements;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import static org.jsoup.nodes.Document.OutputSettings.Syntax;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* Tests XmlTreeBuilder.
*
* @author Jonathan Hedley
*/
public class XmlTreeBuilderTest {
@Test
public void testSimpleXmlParse() {
String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, "http://foo.com/");
assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>",
TextUtil.stripNewlines(doc.html()));
assertEquals(doc.getElementById("2").absUrl("href"), "http://foo.com/bar");
}
@Test
public void testPopToClose() {
// test: </val> closes Two, </bar> ignored
String xml = "<doc><val>One<val>Two</val></bar>Three</doc>";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, "http://foo.com/");
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testCommentAndDocType() {
String xml = "<!DOCTYPE HTML><!-- a comment -->One <qux />Two";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, "http://foo.com/");
assertEquals("<!DOCTYPE HTML><!-- a comment -->One <qux />Two",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testSupplyParserToJsoupClass() {
String xml = "<doc><val>One<val>Two</val></bar>Three</doc>";
Document doc = Jsoup.parse(xml, "http://foo.com/", Parser.xmlParser());
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(doc.html()));
}
@Ignore
@Test
public void testSupplyParserToConnection() throws IOException {
String xmlUrl = "http://direct.infohound.net/tools/jsoup-xml-test.xml";
// parse with both xml and html parser, ensure different
Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get();
Document htmlDoc = Jsoup.connect(xmlUrl).parser(Parser.htmlParser()).get();
Document autoXmlDoc = Jsoup.connect(xmlUrl).get(); // check connection auto detects xml, uses xml parser
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(xmlDoc.html()));
assertFalse(htmlDoc.equals(xmlDoc));
assertEquals(xmlDoc, autoXmlDoc);
assertEquals(1, htmlDoc.select("head").size()); // html parser normalises
assertEquals(0, xmlDoc.select("head").size()); // xml parser does not
assertEquals(0, autoXmlDoc.select("head").size()); // xml parser does not
}
@Test
public void testSupplyParserToDataStream() throws IOException, URISyntaxException {
File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-test.xml").toURI());
InputStream inStream = new FileInputStream(xmlFile);
Document doc = Jsoup.parse(inStream, null, "http://foo.com", Parser.xmlParser());
assertEquals("<doc><val>One<val>Two</val>Three</val></doc>",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testDoesNotForceSelfClosingKnownTags() {
// html will force "<br>one</br>" to logically "<br />One<br />". XML should be stay "<br>one</br> -- don't recognise tag.
Document htmlDoc = Jsoup.parse("<br>one</br>");
assertEquals("<br>one\n<br>", htmlDoc.body().html());
Document xmlDoc = Jsoup.parse("<br>one</br>", "", Parser.xmlParser());
assertEquals("<br>one</br>", xmlDoc.html());
}
@Test public void handlesXmlDeclarationAsDeclaration() {
String html = "<?xml encoding='UTF-8' ?><body>One</body><!-- comment -->";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<?xml encoding=\"UTF-8\"?> <body> One </body> <!-- comment -->",
StringUtil.normaliseWhitespace(doc.outerHtml()));
assertEquals("#declaration", doc.childNode(0).nodeName());
assertEquals("#comment", doc.childNode(2).nodeName());
}
@Test public void xmlFragment() {
String xml = "<one src='/foo/' />Two<three><four /></three>";
List<Node> nodes = Parser.parseXmlFragment(xml, "http://example.com/");
assertEquals(3, nodes.size());
assertEquals("http://example.com/foo/", nodes.get(0).absUrl("src"));
assertEquals("one", nodes.get(0).nodeName());
assertEquals("Two", ((TextNode)nodes.get(1)).text());
}
@Test public void xmlParseDefaultsToHtmlOutputSyntax() {
Document doc = Jsoup.parse("x", "", Parser.xmlParser());
assertEquals(Syntax.xml, doc.outputSettings().syntax());
}
@Test
public void testDoesHandleEOFInTag() {
String html = "<img src=asdf onerror=\"alert(1)\" x=";
Document xmlDoc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<img src=\"asdf\" onerror=\"alert(1)\" x=\"\" />", xmlDoc.html());
}
@Test
public void testDetectCharsetEncodingDeclaration() throws IOException, URISyntaxException {
File xmlFile = new File(XmlTreeBuilder.class.getResource("/htmltests/xml-charset.xml").toURI());
InputStream inStream = new FileInputStream(xmlFile);
Document doc = Jsoup.parse(inStream, null, "http://example.com/", Parser.xmlParser());
assertEquals("ISO-8859-1", doc.charset().name());
assertEquals("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> <data>äöåéü</data>",
TextUtil.stripNewlines(doc.html()));
}
@Test
public void testParseDeclarationAttributes() {
String xml = "<?xml version='1' encoding='UTF-8' something='else'?><val>One</val>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
XmlDeclaration decl = (XmlDeclaration) doc.childNode(0);
assertEquals("1", decl.attr("version"));
assertEquals("UTF-8", decl.attr("encoding"));
assertEquals("else", decl.attr("something"));
assertEquals("version=\"1\" encoding=\"UTF-8\" something=\"else\"", decl.getWholeDeclaration());
assertEquals("<?xml version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", decl.outerHtml());
}
@Test
public void caseSensitiveDeclaration() {
String xml = "<?XML version='1' encoding='UTF-8' something='else'?>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals("<?XML version=\"1\" encoding=\"UTF-8\" something=\"else\"?>", doc.outerHtml());
}
@Test
public void testCreatesValidProlog() {
Document document = Document.createShell("");
document.outputSettings().syntax(Syntax.xml);
document.charset(Charset.forName("utf-8"));
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<html>\n" +
" <head></head>\n" +
" <body></body>\n" +
"</html>", document.outerHtml());
}
@Test
public void preservesCaseByDefault() {
String xml = "<CHECK>One</CHECK><TEST ID=1>Check</TEST>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals("<CHECK>One</CHECK><TEST ID=\"1\">Check</TEST>", TextUtil.stripNewlines(doc.html()));
}
@Test
public void appendPreservesCaseByDefault() {
String xml = "<One>One</One>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Elements one = doc.select("One");
one.append("<Two ID=2>Two</Two>");
assertEquals("<One>One<Two ID=\"2\">Two</Two></One>", TextUtil.stripNewlines(doc.html()));
}
@Test
public void canNormalizeCase() {
String xml = "<TEST ID=1>Check</TEST>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser().settings(ParseSettings.htmlDefault));
assertEquals("<test id=\"1\">Check</test>", TextUtil.stripNewlines(doc.html()));
}
@Test public void normalizesDiscordantTags() {
Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault);
Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser);
assertEquals("<div>\n test\n</div>\n<p></p>", document.html());
// was failing -> toString() = "<div>\n test\n <p></p>\n</div>"
}
@Test public void roundTripsCdata() {
String xml = "<div id=1><![CDATA[\n<html>\n <foo><&]]></div>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
Element div = doc.getElementById("1");
assertEquals("<html>\n <foo><&", div.text());
assertEquals(0, div.children().size());
assertEquals(1, div.childNodeSize()); // no elements, one text node
assertEquals("<div id=\"1\"><![CDATA[\n<html>\n <foo><&]]>\n</div>", div.outerHtml());
CDataNode cdata = (CDataNode) div.textNodes().get(0);
assertEquals("\n<html>\n <foo><&", cdata.text());
}
@Test public void cdataPreservesWhiteSpace() {
String xml = "<script type=\"text/javascript\">//<![CDATA[\n\n foo();\n//]]></script>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals(xml, doc.outerHtml());
assertEquals("//\n\n foo();\n//", doc.selectFirst("script").text());
}
@Test
public void handlesDodgyXmlDecl() {
String xml = "<?xml version='1.0'><val>One</val>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
assertEquals("One", doc.select("val").text());
}
@Test
public void handlesLTinScript() {
// https://github.com/jhy/jsoup/issues/1139
String html = "<script> var a=\"<?\"; var b=\"?>\"; </script>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
assertEquals("<script> var a=\"\n <!--?\"; var b=\"?-->\"; </script>", doc.html()); // converted from pseudo xmldecl to comment
}
} |
||
public void testUnknownTypeIDRecovery() throws Exception
{
ObjectReader reader = MAPPER.readerFor(CallRecord.class).without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
String json = aposToQuotes("{'version':0.0,'application':'123',"
+"'item':{'type':'xevent','location':'location1'},"
+"'item2':{'type':'event','location':'location1'}}");
// can't read item2 - which is valid
CallRecord r = reader.readValue(json);
assertNull(r.item);
assertNotNull(r.item2);
json = aposToQuotes("{'item':{'type':'xevent','location':'location1'}, 'version':0.0,'application':'123'}");
CallRecord r3 = reader.readValue(json);
assertNull(r3.item);
assertEquals("123", r3.application);
} | com.fasterxml.jackson.databind.jsontype.TestPolymorphicWithDefaultImpl::testUnknownTypeIDRecovery | src/test/java/com/fasterxml/jackson/databind/jsontype/TestPolymorphicWithDefaultImpl.java | 230 | src/test/java/com/fasterxml/jackson/databind/jsontype/TestPolymorphicWithDefaultImpl.java | testUnknownTypeIDRecovery | package com.fasterxml.jackson.databind.jsontype;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.annotation.NoClass;
/**
* Unit tests related to specialized handling of "default implementation"
* ({@link JsonTypeInfo#defaultImpl}), as well as related
* cases that allow non-default settings (such as missing type id).
*/
public class TestPolymorphicWithDefaultImpl extends BaseMapTest
{
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = LegacyInter.class)
@JsonSubTypes(value = {@JsonSubTypes.Type(name = "mine", value = MyInter.class)})
public static interface Inter { }
public static class MyInter implements Inter {
@JsonProperty("blah") public List<String> blah;
}
public static class LegacyInter extends MyInter
{
@JsonCreator
LegacyInter(Object obj)
{
if (obj instanceof List) {
blah = new ArrayList<String>();
for (Object o : (List<?>) obj) {
blah.add(o.toString());
}
}
else if (obj instanceof String) {
blah = Arrays.asList(((String) obj).split(","));
}
else {
throw new IllegalArgumentException("Unknown type: " + obj.getClass());
}
}
}
/**
* Note: <code>NoClass</code> here has special meaning, of mapping invalid
* types into null instances.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = NoClass.class)
public static class DefaultWithNoClass { }
/**
* Also another variant to verify that from 2.5 on, can use non-deprecated
* value for the same.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = Void.class)
public static class DefaultWithVoidAsDefault { }
// and then one with no defaultImpl nor listed subtypes
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
abstract static class MysteryPolymorphic { }
// [Databind#511] types
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes(@JsonSubTypes.Type(name="sub1", value = BadSub1.class))
public static class BadItem {}
public static class BadSub1 extends BadItem {
public String a ;
}
public static class Good {
public List<GoodItem> many;
}
public static class Bad {
public List<BadItem> many;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@JsonSubTypes.Type(name="sub1", value = GoodSub1.class),
@JsonSubTypes.Type(name="sub2", value = GoodSub2.class) })
public static class GoodItem {}
public static class GoodSub1 extends GoodItem {
public String a;
}
public static class GoodSub2 extends GoodItem {
public String b;
}
// for [databind#656]
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT, defaultImpl=ImplFor656.class)
static abstract class BaseFor656 { }
static class ImplFor656 extends BaseFor656 {
public int a;
}
static class CallRecord {
public float version;
public String application;
public Item item;
public Item item2;
public CallRecord() {}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({@JsonSubTypes.Type(value = Event.class, name = "event")})
@JsonIgnoreProperties(ignoreUnknown=true)
public interface Item { }
static class Event implements Item {
public String location;
public Event() {}
}
/*
/**********************************************************
/* Unit tests, deserialization
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDeserializationWithObject() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("{\"type\": \"mine\", \"blah\": [\"a\", \"b\", \"c\"]}");
assertTrue(inter instanceof MyInter);
assertFalse(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c"), ((MyInter) inter).blah);
}
public void testDeserializationWithString() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("\"a,b,c,d\"");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArray() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\", \"c\", \"d\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArrayOfSize2() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b"), ((MyInter) inter).blah);
}
// [Databind#148]
public void testDefaultAsNoClass() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// same, with 2.5 and Void.class
public void testDefaultAsVoid() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// [Databind#148]
public void testBadTypeAsNull() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
Object ob = mapper.readValue("{}", MysteryPolymorphic.class);
assertNull(ob);
ob = mapper.readValue("{ \"whatever\":13}", MysteryPolymorphic.class);
assertNull(ob);
}
// [Databind#511]
public void testInvalidTypeId511() throws Exception {
ObjectReader reader = MAPPER.reader().without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES
);
String json = "{\"many\":[{\"sub1\":{\"a\":\"foo\"}},{\"sub2\":{\"b\":\"bar\"}}]}" ;
Good goodResult = reader.forType(Good.class).readValue(json) ;
assertNotNull(goodResult) ;
Bad badResult = reader.forType(Bad.class).readValue(json);
assertNotNull(badResult);
}
// [Databind#656]
public void testDefaultImplWithObjectWrapper() throws Exception
{
BaseFor656 value = MAPPER.readValue(aposToQuotes("{'foobar':{'a':3}}"), BaseFor656.class);
assertNotNull(value);
assertEquals(ImplFor656.class, value.getClass());
assertEquals(3, ((ImplFor656) value).a);
}
public void testUnknownTypeIDRecovery() throws Exception
{
ObjectReader reader = MAPPER.readerFor(CallRecord.class).without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
String json = aposToQuotes("{'version':0.0,'application':'123',"
+"'item':{'type':'xevent','location':'location1'},"
+"'item2':{'type':'event','location':'location1'}}");
// can't read item2 - which is valid
CallRecord r = reader.readValue(json);
assertNull(r.item);
assertNotNull(r.item2);
json = aposToQuotes("{'item':{'type':'xevent','location':'location1'}, 'version':0.0,'application':'123'}");
CallRecord r3 = reader.readValue(json);
assertNull(r3.item);
assertEquals("123", r3.application);
}
/*
/**********************************************************
/* Unit tests, serialization
/**********************************************************
*/
/*
public void testDontWriteIfDefaultImpl() throws Exception {
String json = MAPPER.writeValueAsString(new MyInter());
assertEquals("{\"blah\":null}", json);
}
*/
} | // You are a professional Java test case writer, please create a test case named `testUnknownTypeIDRecovery` for the issue `JacksonDatabind-1108`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1108
//
// ## Issue-Title:
// Jackson not continue to parse after DeserializationFeature.FAIL_ON_INVALID_SUBTYPE error
//
// ## Issue-Description:
// After FAIL\_ON\_INVALID\_SUBTYPE error, jackson should continue to parse, but seems jackson doesn't.
//
//
// The output:
//
//
//
// ```
// CallRecord [version=0.0, application=123, ] // doesn't read item2 which is valid
// CallRecord [version=0.0, application=123, ]
// CallRecord [version=0.0, ] // doesn't read application after invalid item.
//
// ```
//
//
// ```
// @JsonInclude(Include.NON_NULL)
// public class CallRecord {
// public float version;
// public String application;
// public Item item;
// public Item item2;
// public CallRecord() {}
//
// public static void main(final String[] args) throws IOException {
// final ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
// DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
// final CallRecord call = new CallRecord();
//
// final Event event = new Event();
// event.location = "location1";
// call.item = event;
// call.item2 = event;
// call.application = "123";
// // System.out.println(objectMapper.writeValueAsString(call));
// String json =
// "{\"version\":0.0,\"application\":\"123\",\"item\":{\"type\":\"xevent\",\"location\":\"location1\"},\"item2\":{\"type\":\"event\",\"location\":\"location1\"}}";
// // can't read item2 - which is valid
// System.out.println(objectMapper.readValue(json, CallRecord.class));
//
// json = "{\"version\":0.0,\"application\":\"123\"},{\"item\":{\"type\":\"xevent\",\"location\":\"location1\"}";
// System.out.println(objectMapper.readValue(json, CallRecord.class));
//
// json = "{\"item\":{\"type\":\"xevent\",\"location\":\"location1\"}, \"version\":0.0,\"application\":\"123\"}";
// // order matters: move item to the fornt, now it can't read application property
// System.out.println(objectMapper.readValue(json, CallRecord.class));
// }
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("CallRecord [version=").append(version).append(", ");
// if (application != null) {
// builder.append("application=").append(application).append(", ");
// }
// if (item != null) {
// builder.append("item=").append(item);
// }
// builder.append("]");
// return builder.toString();
// }
// }
//
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
// @JsonSubTypes({@Type(value = Event.class, name = Event.TYPE)})
// public interface Item {
// }
public void testUnknownTypeIDRecovery() throws Exception {
| 230 | 39 | 214 | src/test/java/com/fasterxml/jackson/databind/jsontype/TestPolymorphicWithDefaultImpl.java | src/test/java | ```markdown
## Issue-ID: JacksonDatabind-1108
## Issue-Title:
Jackson not continue to parse after DeserializationFeature.FAIL_ON_INVALID_SUBTYPE error
## Issue-Description:
After FAIL\_ON\_INVALID\_SUBTYPE error, jackson should continue to parse, but seems jackson doesn't.
The output:
```
CallRecord [version=0.0, application=123, ] // doesn't read item2 which is valid
CallRecord [version=0.0, application=123, ]
CallRecord [version=0.0, ] // doesn't read application after invalid item.
```
```
@JsonInclude(Include.NON_NULL)
public class CallRecord {
public float version;
public String application;
public Item item;
public Item item2;
public CallRecord() {}
public static void main(final String[] args) throws IOException {
final ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
final CallRecord call = new CallRecord();
final Event event = new Event();
event.location = "location1";
call.item = event;
call.item2 = event;
call.application = "123";
// System.out.println(objectMapper.writeValueAsString(call));
String json =
"{\"version\":0.0,\"application\":\"123\",\"item\":{\"type\":\"xevent\",\"location\":\"location1\"},\"item2\":{\"type\":\"event\",\"location\":\"location1\"}}";
// can't read item2 - which is valid
System.out.println(objectMapper.readValue(json, CallRecord.class));
json = "{\"version\":0.0,\"application\":\"123\"},{\"item\":{\"type\":\"xevent\",\"location\":\"location1\"}";
System.out.println(objectMapper.readValue(json, CallRecord.class));
json = "{\"item\":{\"type\":\"xevent\",\"location\":\"location1\"}, \"version\":0.0,\"application\":\"123\"}";
// order matters: move item to the fornt, now it can't read application property
System.out.println(objectMapper.readValue(json, CallRecord.class));
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("CallRecord [version=").append(version).append(", ");
if (application != null) {
builder.append("application=").append(application).append(", ");
}
if (item != null) {
builder.append("item=").append(item);
}
builder.append("]");
return builder.toString();
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({@Type(value = Event.class, name = Event.TYPE)})
public interface Item {
}
```
You are a professional Java test case writer, please create a test case named `testUnknownTypeIDRecovery` for the issue `JacksonDatabind-1108`, utilizing the provided issue report information and the following function signature.
```java
public void testUnknownTypeIDRecovery() throws Exception {
```
| 214 | [
"com.fasterxml.jackson.databind.deser.std.NullifyingDeserializer"
] | 6a39d7f3d99b9dce69511831d4ae90cfd5aba865ad3cafeba892620e943f2cc2 | public void testUnknownTypeIDRecovery() throws Exception
| // You are a professional Java test case writer, please create a test case named `testUnknownTypeIDRecovery` for the issue `JacksonDatabind-1108`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: JacksonDatabind-1108
//
// ## Issue-Title:
// Jackson not continue to parse after DeserializationFeature.FAIL_ON_INVALID_SUBTYPE error
//
// ## Issue-Description:
// After FAIL\_ON\_INVALID\_SUBTYPE error, jackson should continue to parse, but seems jackson doesn't.
//
//
// The output:
//
//
//
// ```
// CallRecord [version=0.0, application=123, ] // doesn't read item2 which is valid
// CallRecord [version=0.0, application=123, ]
// CallRecord [version=0.0, ] // doesn't read application after invalid item.
//
// ```
//
//
// ```
// @JsonInclude(Include.NON_NULL)
// public class CallRecord {
// public float version;
// public String application;
// public Item item;
// public Item item2;
// public CallRecord() {}
//
// public static void main(final String[] args) throws IOException {
// final ObjectMapper objectMapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
// DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
// final CallRecord call = new CallRecord();
//
// final Event event = new Event();
// event.location = "location1";
// call.item = event;
// call.item2 = event;
// call.application = "123";
// // System.out.println(objectMapper.writeValueAsString(call));
// String json =
// "{\"version\":0.0,\"application\":\"123\",\"item\":{\"type\":\"xevent\",\"location\":\"location1\"},\"item2\":{\"type\":\"event\",\"location\":\"location1\"}}";
// // can't read item2 - which is valid
// System.out.println(objectMapper.readValue(json, CallRecord.class));
//
// json = "{\"version\":0.0,\"application\":\"123\"},{\"item\":{\"type\":\"xevent\",\"location\":\"location1\"}";
// System.out.println(objectMapper.readValue(json, CallRecord.class));
//
// json = "{\"item\":{\"type\":\"xevent\",\"location\":\"location1\"}, \"version\":0.0,\"application\":\"123\"}";
// // order matters: move item to the fornt, now it can't read application property
// System.out.println(objectMapper.readValue(json, CallRecord.class));
// }
// @Override
// public String toString() {
// final StringBuilder builder = new StringBuilder();
// builder.append("CallRecord [version=").append(version).append(", ");
// if (application != null) {
// builder.append("application=").append(application).append(", ");
// }
// if (item != null) {
// builder.append("item=").append(item);
// }
// builder.append("]");
// return builder.toString();
// }
// }
//
// @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
// @JsonSubTypes({@Type(value = Event.class, name = Event.TYPE)})
// public interface Item {
// }
| JacksonDatabind | package com.fasterxml.jackson.databind.jsontype;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.annotation.NoClass;
/**
* Unit tests related to specialized handling of "default implementation"
* ({@link JsonTypeInfo#defaultImpl}), as well as related
* cases that allow non-default settings (such as missing type id).
*/
public class TestPolymorphicWithDefaultImpl extends BaseMapTest
{
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = LegacyInter.class)
@JsonSubTypes(value = {@JsonSubTypes.Type(name = "mine", value = MyInter.class)})
public static interface Inter { }
public static class MyInter implements Inter {
@JsonProperty("blah") public List<String> blah;
}
public static class LegacyInter extends MyInter
{
@JsonCreator
LegacyInter(Object obj)
{
if (obj instanceof List) {
blah = new ArrayList<String>();
for (Object o : (List<?>) obj) {
blah.add(o.toString());
}
}
else if (obj instanceof String) {
blah = Arrays.asList(((String) obj).split(","));
}
else {
throw new IllegalArgumentException("Unknown type: " + obj.getClass());
}
}
}
/**
* Note: <code>NoClass</code> here has special meaning, of mapping invalid
* types into null instances.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = NoClass.class)
public static class DefaultWithNoClass { }
/**
* Also another variant to verify that from 2.5 on, can use non-deprecated
* value for the same.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type",
defaultImpl = Void.class)
public static class DefaultWithVoidAsDefault { }
// and then one with no defaultImpl nor listed subtypes
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
abstract static class MysteryPolymorphic { }
// [Databind#511] types
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes(@JsonSubTypes.Type(name="sub1", value = BadSub1.class))
public static class BadItem {}
public static class BadSub1 extends BadItem {
public String a ;
}
public static class Good {
public List<GoodItem> many;
}
public static class Bad {
public List<BadItem> many;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({@JsonSubTypes.Type(name="sub1", value = GoodSub1.class),
@JsonSubTypes.Type(name="sub2", value = GoodSub2.class) })
public static class GoodItem {}
public static class GoodSub1 extends GoodItem {
public String a;
}
public static class GoodSub2 extends GoodItem {
public String b;
}
// for [databind#656]
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.WRAPPER_OBJECT, defaultImpl=ImplFor656.class)
static abstract class BaseFor656 { }
static class ImplFor656 extends BaseFor656 {
public int a;
}
static class CallRecord {
public float version;
public String application;
public Item item;
public Item item2;
public CallRecord() {}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true)
@JsonSubTypes({@JsonSubTypes.Type(value = Event.class, name = "event")})
@JsonIgnoreProperties(ignoreUnknown=true)
public interface Item { }
static class Event implements Item {
public String location;
public Event() {}
}
/*
/**********************************************************
/* Unit tests, deserialization
/**********************************************************
*/
private final ObjectMapper MAPPER = new ObjectMapper();
public void testDeserializationWithObject() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("{\"type\": \"mine\", \"blah\": [\"a\", \"b\", \"c\"]}");
assertTrue(inter instanceof MyInter);
assertFalse(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c"), ((MyInter) inter).blah);
}
public void testDeserializationWithString() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("\"a,b,c,d\"");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArray() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\", \"c\", \"d\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b", "c", "d"), ((MyInter) inter).blah);
}
public void testDeserializationWithArrayOfSize2() throws Exception
{
Inter inter = MAPPER.readerFor(Inter.class).readValue("[\"a\", \"b\"]");
assertTrue(inter instanceof LegacyInter);
assertEquals(Arrays.asList("a", "b"), ((MyInter) inter).blah);
}
// [Databind#148]
public void testDefaultAsNoClass() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithNoClass.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// same, with 2.5 and Void.class
public void testDefaultAsVoid() throws Exception
{
Object ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ }");
assertNull(ob);
ob = MAPPER.readerFor(DefaultWithVoidAsDefault.class).readValue("{ \"bogus\":3 }");
assertNull(ob);
}
// [Databind#148]
public void testBadTypeAsNull() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
Object ob = mapper.readValue("{}", MysteryPolymorphic.class);
assertNull(ob);
ob = mapper.readValue("{ \"whatever\":13}", MysteryPolymorphic.class);
assertNull(ob);
}
// [Databind#511]
public void testInvalidTypeId511() throws Exception {
ObjectReader reader = MAPPER.reader().without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES
);
String json = "{\"many\":[{\"sub1\":{\"a\":\"foo\"}},{\"sub2\":{\"b\":\"bar\"}}]}" ;
Good goodResult = reader.forType(Good.class).readValue(json) ;
assertNotNull(goodResult) ;
Bad badResult = reader.forType(Bad.class).readValue(json);
assertNotNull(badResult);
}
// [Databind#656]
public void testDefaultImplWithObjectWrapper() throws Exception
{
BaseFor656 value = MAPPER.readValue(aposToQuotes("{'foobar':{'a':3}}"), BaseFor656.class);
assertNotNull(value);
assertEquals(ImplFor656.class, value.getClass());
assertEquals(3, ((ImplFor656) value).a);
}
public void testUnknownTypeIDRecovery() throws Exception
{
ObjectReader reader = MAPPER.readerFor(CallRecord.class).without(
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
String json = aposToQuotes("{'version':0.0,'application':'123',"
+"'item':{'type':'xevent','location':'location1'},"
+"'item2':{'type':'event','location':'location1'}}");
// can't read item2 - which is valid
CallRecord r = reader.readValue(json);
assertNull(r.item);
assertNotNull(r.item2);
json = aposToQuotes("{'item':{'type':'xevent','location':'location1'}, 'version':0.0,'application':'123'}");
CallRecord r3 = reader.readValue(json);
assertNull(r3.item);
assertEquals("123", r3.application);
}
/*
/**********************************************************
/* Unit tests, serialization
/**********************************************************
*/
/*
public void testDontWriteIfDefaultImpl() throws Exception {
String json = MAPPER.writeValueAsString(new MyInter());
assertEquals("{\"blah\":null}", json);
}
*/
} |
||
@Test
public void testPerformClusterAnalysisDegenerate() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
new EuclideanIntegerPoint(new int[] { 1959, 325100 }),
new EuclideanIntegerPoint(new int[] { 1960, 373200 }), };
List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
assertEquals(1, clusters.size());
assertEquals(2, (clusters.get(0).getPoints().size()));
EuclideanIntegerPoint pt1 = new EuclideanIntegerPoint(new int[] { 1959, 325100 });
EuclideanIntegerPoint pt2 = new EuclideanIntegerPoint(new int[] { 1960, 373200 });
assertTrue(clusters.get(0).getPoints().contains(pt1));
assertTrue(clusters.get(0).getPoints().contains(pt2));
} | org.apache.commons.math.stat.clustering.KMeansPlusPlusClustererTest::testPerformClusterAnalysisDegenerate | src/test/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClustererTest.java | 116 | src/test/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClustererTest.java | testPerformClusterAnalysisDegenerate | /*
* 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.clustering;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Test;
public class KMeansPlusPlusClustererTest {
@Test
public void dimension2() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer =
new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
// first expected cluster
new EuclideanIntegerPoint(new int[] { -15, 3 }),
new EuclideanIntegerPoint(new int[] { -15, 4 }),
new EuclideanIntegerPoint(new int[] { -15, 5 }),
new EuclideanIntegerPoint(new int[] { -14, 3 }),
new EuclideanIntegerPoint(new int[] { -14, 5 }),
new EuclideanIntegerPoint(new int[] { -13, 3 }),
new EuclideanIntegerPoint(new int[] { -13, 4 }),
new EuclideanIntegerPoint(new int[] { -13, 5 }),
// second expected cluster
new EuclideanIntegerPoint(new int[] { -1, 0 }),
new EuclideanIntegerPoint(new int[] { -1, -1 }),
new EuclideanIntegerPoint(new int[] { 0, -1 }),
new EuclideanIntegerPoint(new int[] { 1, -1 }),
new EuclideanIntegerPoint(new int[] { 1, -2 }),
// third expected cluster
new EuclideanIntegerPoint(new int[] { 13, 3 }),
new EuclideanIntegerPoint(new int[] { 13, 4 }),
new EuclideanIntegerPoint(new int[] { 14, 4 }),
new EuclideanIntegerPoint(new int[] { 14, 7 }),
new EuclideanIntegerPoint(new int[] { 16, 5 }),
new EuclideanIntegerPoint(new int[] { 16, 6 }),
new EuclideanIntegerPoint(new int[] { 17, 4 }),
new EuclideanIntegerPoint(new int[] { 17, 7 })
};
List<Cluster<EuclideanIntegerPoint>> clusters =
transformer.cluster(Arrays.asList(points), 3, 10);
assertEquals(3, clusters.size());
boolean cluster1Found = false;
boolean cluster2Found = false;
boolean cluster3Found = false;
for (Cluster<EuclideanIntegerPoint> cluster : clusters) {
int[] center = cluster.getCenter().getPoint();
if (center[0] < 0) {
cluster1Found = true;
assertEquals(8, cluster.getPoints().size());
assertEquals(-14, center[0]);
assertEquals( 4, center[1]);
} else if (center[1] < 0) {
cluster2Found = true;
assertEquals(5, cluster.getPoints().size());
assertEquals( 0, center[0]);
assertEquals(-1, center[1]);
} else {
cluster3Found = true;
assertEquals(8, cluster.getPoints().size());
assertEquals(15, center[0]);
assertEquals(5, center[1]);
}
}
assertTrue(cluster1Found);
assertTrue(cluster2Found);
assertTrue(cluster3Found);
}
/**
* JIRA: MATH-305
*
* Two points, one cluster, one iteration
*/
@Test
public void testPerformClusterAnalysisDegenerate() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
new EuclideanIntegerPoint(new int[] { 1959, 325100 }),
new EuclideanIntegerPoint(new int[] { 1960, 373200 }), };
List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
assertEquals(1, clusters.size());
assertEquals(2, (clusters.get(0).getPoints().size()));
EuclideanIntegerPoint pt1 = new EuclideanIntegerPoint(new int[] { 1959, 325100 });
EuclideanIntegerPoint pt2 = new EuclideanIntegerPoint(new int[] { 1960, 373200 });
assertTrue(clusters.get(0).getPoints().contains(pt1));
assertTrue(clusters.get(0).getPoints().contains(pt2));
}
} | // You are a professional Java test case writer, please create a test case named `testPerformClusterAnalysisDegenerate` for the issue `Math-MATH-305`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-305
//
// ## Issue-Title:
// NPE in KMeansPlusPlusClusterer unittest
//
// ## Issue-Description:
//
// When running this unittest, I am facing this NPE:
//
// java.lang.NullPointerException
//
// at org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer.assignPointsToClusters(KMeansPlusPlusClusterer.java:91)
//
//
// This is the unittest:
//
//
// package org.fao.fisheries.chronicles.calcuation.cluster;
//
//
// import static org.junit.Assert.assertEquals;
//
// import static org.junit.Assert.assertTrue;
//
//
// import java.util.Arrays;
//
// import java.util.List;
//
// import java.util.Random;
//
//
// import org.apache.commons.math.stat.clustering.Cluster;
//
// import org.apache.commons.math.stat.clustering.EuclideanIntegerPoint;
//
// import org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer;
//
// import org.fao.fisheries.chronicles.input.CsvImportProcess;
//
// import org.fao.fisheries.chronicles.input.Top200Csv;
//
// import org.junit.Test;
//
//
// public class ClusterAnalysisTest {
//
//
// @Test
//
// public void testPerformClusterAnalysis2() {
//
// KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
//
// new Random(1746432956321l));
//
// EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
//
// new EuclideanIntegerPoint(new int[]
//
//
// { 1959, 325100 }
// ),
//
// new EuclideanIntegerPoint(new int[]
//
//
// { 1960, 373200 }
// ), };
//
// List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
//
// assertEquals(1, clusters.size());
//
//
// }
//
//
// }
//
//
//
//
//
@Test
public void testPerformClusterAnalysisDegenerate() {
| 116 | /**
* JIRA: MATH-305
*
* Two points, one cluster, one iteration
*/ | 79 | 101 | src/test/java/org/apache/commons/math/stat/clustering/KMeansPlusPlusClustererTest.java | src/test/java | ```markdown
## Issue-ID: Math-MATH-305
## Issue-Title:
NPE in KMeansPlusPlusClusterer unittest
## Issue-Description:
When running this unittest, I am facing this NPE:
java.lang.NullPointerException
at org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer.assignPointsToClusters(KMeansPlusPlusClusterer.java:91)
This is the unittest:
package org.fao.fisheries.chronicles.calcuation.cluster;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.apache.commons.math.stat.clustering.Cluster;
import org.apache.commons.math.stat.clustering.EuclideanIntegerPoint;
import org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer;
import org.fao.fisheries.chronicles.input.CsvImportProcess;
import org.fao.fisheries.chronicles.input.Top200Csv;
import org.junit.Test;
public class ClusterAnalysisTest {
@Test
public void testPerformClusterAnalysis2() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
new EuclideanIntegerPoint(new int[]
{ 1959, 325100 }
),
new EuclideanIntegerPoint(new int[]
{ 1960, 373200 }
), };
List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
assertEquals(1, clusters.size());
}
}
```
You are a professional Java test case writer, please create a test case named `testPerformClusterAnalysisDegenerate` for the issue `Math-MATH-305`, utilizing the provided issue report information and the following function signature.
```java
@Test
public void testPerformClusterAnalysisDegenerate() {
```
| 101 | [
"org.apache.commons.math.util.MathUtils"
] | 6a52ad6338a734ba0ddd0cfbc215e4d5f81e6f976f51ea32cf5ef28c71d22d79 | @Test
public void testPerformClusterAnalysisDegenerate() | // You are a professional Java test case writer, please create a test case named `testPerformClusterAnalysisDegenerate` for the issue `Math-MATH-305`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Math-MATH-305
//
// ## Issue-Title:
// NPE in KMeansPlusPlusClusterer unittest
//
// ## Issue-Description:
//
// When running this unittest, I am facing this NPE:
//
// java.lang.NullPointerException
//
// at org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer.assignPointsToClusters(KMeansPlusPlusClusterer.java:91)
//
//
// This is the unittest:
//
//
// package org.fao.fisheries.chronicles.calcuation.cluster;
//
//
// import static org.junit.Assert.assertEquals;
//
// import static org.junit.Assert.assertTrue;
//
//
// import java.util.Arrays;
//
// import java.util.List;
//
// import java.util.Random;
//
//
// import org.apache.commons.math.stat.clustering.Cluster;
//
// import org.apache.commons.math.stat.clustering.EuclideanIntegerPoint;
//
// import org.apache.commons.math.stat.clustering.KMeansPlusPlusClusterer;
//
// import org.fao.fisheries.chronicles.input.CsvImportProcess;
//
// import org.fao.fisheries.chronicles.input.Top200Csv;
//
// import org.junit.Test;
//
//
// public class ClusterAnalysisTest {
//
//
// @Test
//
// public void testPerformClusterAnalysis2() {
//
// KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
//
// new Random(1746432956321l));
//
// EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
//
// new EuclideanIntegerPoint(new int[]
//
//
// { 1959, 325100 }
// ),
//
// new EuclideanIntegerPoint(new int[]
//
//
// { 1960, 373200 }
// ), };
//
// List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
//
// assertEquals(1, clusters.size());
//
//
// }
//
//
// }
//
//
//
//
//
| 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.clustering;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Test;
public class KMeansPlusPlusClustererTest {
@Test
public void dimension2() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer =
new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
// first expected cluster
new EuclideanIntegerPoint(new int[] { -15, 3 }),
new EuclideanIntegerPoint(new int[] { -15, 4 }),
new EuclideanIntegerPoint(new int[] { -15, 5 }),
new EuclideanIntegerPoint(new int[] { -14, 3 }),
new EuclideanIntegerPoint(new int[] { -14, 5 }),
new EuclideanIntegerPoint(new int[] { -13, 3 }),
new EuclideanIntegerPoint(new int[] { -13, 4 }),
new EuclideanIntegerPoint(new int[] { -13, 5 }),
// second expected cluster
new EuclideanIntegerPoint(new int[] { -1, 0 }),
new EuclideanIntegerPoint(new int[] { -1, -1 }),
new EuclideanIntegerPoint(new int[] { 0, -1 }),
new EuclideanIntegerPoint(new int[] { 1, -1 }),
new EuclideanIntegerPoint(new int[] { 1, -2 }),
// third expected cluster
new EuclideanIntegerPoint(new int[] { 13, 3 }),
new EuclideanIntegerPoint(new int[] { 13, 4 }),
new EuclideanIntegerPoint(new int[] { 14, 4 }),
new EuclideanIntegerPoint(new int[] { 14, 7 }),
new EuclideanIntegerPoint(new int[] { 16, 5 }),
new EuclideanIntegerPoint(new int[] { 16, 6 }),
new EuclideanIntegerPoint(new int[] { 17, 4 }),
new EuclideanIntegerPoint(new int[] { 17, 7 })
};
List<Cluster<EuclideanIntegerPoint>> clusters =
transformer.cluster(Arrays.asList(points), 3, 10);
assertEquals(3, clusters.size());
boolean cluster1Found = false;
boolean cluster2Found = false;
boolean cluster3Found = false;
for (Cluster<EuclideanIntegerPoint> cluster : clusters) {
int[] center = cluster.getCenter().getPoint();
if (center[0] < 0) {
cluster1Found = true;
assertEquals(8, cluster.getPoints().size());
assertEquals(-14, center[0]);
assertEquals( 4, center[1]);
} else if (center[1] < 0) {
cluster2Found = true;
assertEquals(5, cluster.getPoints().size());
assertEquals( 0, center[0]);
assertEquals(-1, center[1]);
} else {
cluster3Found = true;
assertEquals(8, cluster.getPoints().size());
assertEquals(15, center[0]);
assertEquals(5, center[1]);
}
}
assertTrue(cluster1Found);
assertTrue(cluster2Found);
assertTrue(cluster3Found);
}
/**
* JIRA: MATH-305
*
* Two points, one cluster, one iteration
*/
@Test
public void testPerformClusterAnalysisDegenerate() {
KMeansPlusPlusClusterer<EuclideanIntegerPoint> transformer = new KMeansPlusPlusClusterer<EuclideanIntegerPoint>(
new Random(1746432956321l));
EuclideanIntegerPoint[] points = new EuclideanIntegerPoint[] {
new EuclideanIntegerPoint(new int[] { 1959, 325100 }),
new EuclideanIntegerPoint(new int[] { 1960, 373200 }), };
List<Cluster<EuclideanIntegerPoint>> clusters = transformer.cluster(Arrays.asList(points), 1, 1);
assertEquals(1, clusters.size());
assertEquals(2, (clusters.get(0).getPoints().size()));
EuclideanIntegerPoint pt1 = new EuclideanIntegerPoint(new int[] { 1959, 325100 });
EuclideanIntegerPoint pt2 = new EuclideanIntegerPoint(new int[] { 1960, 373200 });
assertTrue(clusters.get(0).getPoints().contains(pt1));
assertTrue(clusters.get(0).getPoints().contains(pt2));
}
} |
|
public void testReadWinZipArchive() throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-winzip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, null, true);
assertCanRead(zf, ASCII_TXT);
assertCanRead(zf, EURO_FOR_DOLLAR_TXT);
assertCanRead(zf, OIL_BARREL_TXT);
} finally {
ZipFile.closeQuietly(zf);
}
} | org.apache.commons.compress.archivers.zip.UTF8ZipFilesTest::testReadWinZipArchive | src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java | 137 | src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java | testReadWinZipArchive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.zip.CRC32;
import org.apache.commons.compress.AbstractTestCase;
public class UTF8ZipFilesTest extends AbstractTestCase {
private static final String UTF_8 = "utf-8";
private static final String CP437 = "cp437";
private static final String US_ASCII = "US-ASCII";
private static final String ASCII_TXT = "ascii.txt";
private static final String EURO_FOR_DOLLAR_TXT = "\u20AC_for_Dollar.txt";
private static final String OIL_BARREL_TXT = "\u00D6lf\u00E4sser.txt";
public void testUtf8FileRoundtripExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, true, true);
}
public void testUtf8FileRoundtripNoEFSExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, false, true);
}
public void testCP437FileRoundtripExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(CP437, false, true);
}
public void testASCIIFileRoundtripExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(US_ASCII, false, true);
}
public void testUtf8FileRoundtripImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, true, false);
}
public void testUtf8FileRoundtripNoEFSImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, false, false);
}
public void testCP437FileRoundtripImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(CP437, false, false);
}
public void testASCIIFileRoundtripImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(US_ASCII, false, false);
}
/*
* 7-ZIP created archive, uses EFS to signal UTF-8 filenames.
*
* 7-ZIP doesn't use EFS for strings that can be encoded in CP437
* - which is true for OIL_BARREL_TXT.
*/
public void testRead7ZipArchive() throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, CP437, false);
assertNotNull(zf.getEntry(ASCII_TXT));
assertNotNull(zf.getEntry(EURO_FOR_DOLLAR_TXT));
assertNotNull(zf.getEntry(OIL_BARREL_TXT));
} finally {
ZipFile.closeQuietly(zf);
}
}
public void testRead7ZipArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
FileInputStream archive =
new FileInputStream(new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive, CP437, false);
assertEquals(ASCII_TXT, zi.getNextEntry().getName());
assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
assertEquals(EURO_FOR_DOLLAR_TXT, zi.getNextEntry().getName());
} finally {
if (zi != null) {
zi.close();
}
}
}
/*
* WinZIP created archive, uses Unicode Extra Fields but only in
* the central directory.
*/
public void testReadWinZipArchive() throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-winzip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, null, true);
assertCanRead(zf, ASCII_TXT);
assertCanRead(zf, EURO_FOR_DOLLAR_TXT);
assertCanRead(zf, OIL_BARREL_TXT);
} finally {
ZipFile.closeQuietly(zf);
}
}
private void assertCanRead(ZipFile zf, String fileName) throws IOException {
ZipArchiveEntry entry = zf.getEntry(fileName);
assertNotNull("Entry doesn't exist", entry);
InputStream is = zf.getInputStream(entry);
assertNotNull("InputStream is null", is);
try {
is.read();
} finally {
is.close();
}
}
public void testReadWinZipArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/utf8-winzip-test.zip");
FileInputStream archive =
new FileInputStream(new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive, null, true);
assertEquals(EURO_FOR_DOLLAR_TXT, zi.getNextEntry().getName());
assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
assertEquals(ASCII_TXT, zi.getNextEntry().getName());
} finally {
if (zi != null) {
zi.close();
}
}
}
public void testZipFileReadsUnicodeFields() throws IOException {
File file = File.createTempFile("unicode-test", ".zip");
file.deleteOnExit();
ZipArchiveInputStream zi = null;
try {
createTestFile(file, US_ASCII, false, true);
FileInputStream archive = new FileInputStream(file);
zi = new ZipArchiveInputStream(archive, US_ASCII, true);
assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
assertEquals(EURO_FOR_DOLLAR_TXT, zi.getNextEntry().getName());
assertEquals(ASCII_TXT, zi.getNextEntry().getName());
} finally {
if (zi != null) {
zi.close();
}
tryHardToDelete(file);
}
}
public void testZipArchiveInputStreamReadsUnicodeFields()
throws IOException {
File file = File.createTempFile("unicode-test", ".zip");
file.deleteOnExit();
ZipFile zf = null;
try {
createTestFile(file, US_ASCII, false, true);
zf = new ZipFile(file, US_ASCII, true);
assertNotNull(zf.getEntry(ASCII_TXT));
assertNotNull(zf.getEntry(EURO_FOR_DOLLAR_TXT));
assertNotNull(zf.getEntry(OIL_BARREL_TXT));
} finally {
ZipFile.closeQuietly(zf);
tryHardToDelete(file);
}
}
public void testRawNameReadFromZipFile()
throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, CP437, false);
assertRawNameOfAcsiiTxt(zf.getEntry(ASCII_TXT));
} finally {
ZipFile.closeQuietly(zf);
}
}
public void testRawNameReadFromStream()
throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
FileInputStream archive =
new FileInputStream(new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive, CP437, false);
assertRawNameOfAcsiiTxt((ZipArchiveEntry) zi.getNextEntry());
} finally {
if (zi != null) {
zi.close();
}
}
}
private static void testFileRoundtrip(String encoding, boolean withEFS,
boolean withExplicitUnicodeExtra)
throws IOException {
File file = File.createTempFile(encoding + "-test", ".zip");
file.deleteOnExit();
try {
createTestFile(file, encoding, withEFS, withExplicitUnicodeExtra);
testFile(file, encoding);
} finally {
tryHardToDelete(file);
}
}
private static void createTestFile(File file, String encoding,
boolean withEFS,
boolean withExplicitUnicodeExtra)
throws UnsupportedEncodingException, IOException {
ZipEncoding zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
ZipArchiveOutputStream zos = null;
try {
zos = new ZipArchiveOutputStream(file);
zos.setEncoding(encoding);
zos.setUseLanguageEncodingFlag(withEFS);
zos.setCreateUnicodeExtraFields(withExplicitUnicodeExtra ?
ZipArchiveOutputStream
.UnicodeExtraFieldPolicy.NEVER
: ZipArchiveOutputStream
.UnicodeExtraFieldPolicy.ALWAYS);
ZipArchiveEntry ze = new ZipArchiveEntry(OIL_BARREL_TXT);
if (withExplicitUnicodeExtra
&& !zipEncoding.canEncode(ze.getName())) {
ByteBuffer en = zipEncoding.encode(ze.getName());
ze.addExtraField(new UnicodePathExtraField(ze.getName(),
en.array(),
en.arrayOffset(),
en.limit()));
}
zos.putArchiveEntry(ze);
zos.write("Hello, world!".getBytes("US-ASCII"));
zos.closeArchiveEntry();
ze = new ZipArchiveEntry(EURO_FOR_DOLLAR_TXT);
if (withExplicitUnicodeExtra
&& !zipEncoding.canEncode(ze.getName())) {
ByteBuffer en = zipEncoding.encode(ze.getName());
ze.addExtraField(new UnicodePathExtraField(ze.getName(),
en.array(),
en.arrayOffset(),
en.limit()));
}
zos.putArchiveEntry(ze);
zos.write("Give me your money!".getBytes("US-ASCII"));
zos.closeArchiveEntry();
ze = new ZipArchiveEntry(ASCII_TXT);
if (withExplicitUnicodeExtra
&& !zipEncoding.canEncode(ze.getName())) {
ByteBuffer en = zipEncoding.encode(ze.getName());
ze.addExtraField(new UnicodePathExtraField(ze.getName(),
en.array(),
en.arrayOffset(),
en.limit()));
}
zos.putArchiveEntry(ze);
zos.write("ascii".getBytes("US-ASCII"));
zos.closeArchiveEntry();
zos.finish();
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) { /* swallow */ }
}
}
}
private static void testFile(File file, String encoding)
throws IOException {
ZipFile zf = null;
try {
zf = new ZipFile(file, encoding, false);
Enumeration<ZipArchiveEntry> e = zf.getEntries();
while (e.hasMoreElements()) {
ZipArchiveEntry ze = e.nextElement();
if (ze.getName().endsWith("sser.txt")) {
assertUnicodeName(ze, OIL_BARREL_TXT, encoding);
} else if (ze.getName().endsWith("_for_Dollar.txt")) {
assertUnicodeName(ze, EURO_FOR_DOLLAR_TXT, encoding);
} else if (!ze.getName().equals(ASCII_TXT)) {
throw new AssertionError("Urecognized ZIP entry with name ["
+ ze.getName() + "] found.");
}
}
} finally {
ZipFile.closeQuietly(zf);
}
}
private static UnicodePathExtraField findUniCodePath(ZipArchiveEntry ze) {
return (UnicodePathExtraField)
ze.getExtraField(UnicodePathExtraField.UPATH_ID);
}
private static void assertUnicodeName(ZipArchiveEntry ze,
String expectedName,
String encoding)
throws IOException {
if (!expectedName.equals(ze.getName())) {
UnicodePathExtraField ucpf = findUniCodePath(ze);
assertNotNull(ucpf);
ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encoding);
ByteBuffer ne = enc.encode(ze.getName());
CRC32 crc = new CRC32();
crc.update(ne.array(),ne.arrayOffset(),ne.limit());
assertEquals(crc.getValue(), ucpf.getNameCRC32());
assertEquals(expectedName, new String(ucpf.getUnicodeName(),
UTF_8));
}
}
public void testUtf8Interoperability() throws IOException {
File file1 = super.getFile("utf8-7zip-test.zip");
File file2 = super.getFile("utf8-winzip-test.zip");
testFile(file1,CP437);
testFile(file2,CP437);
}
private static void assertRawNameOfAcsiiTxt(ZipArchiveEntry ze) {
byte[] b = ze.getRawName();
assertNotNull(b);
final int len = ASCII_TXT.length();
assertEquals(len, b.length);
for (int i = 0; i < len; i++) {
assertEquals("Byte " + i, (byte) ASCII_TXT.charAt(i), b[i]);
}
assertNotSame(b, ze.getRawName());
}
}
| // You are a professional Java test case writer, please create a test case named `testReadWinZipArchive` for the issue `Compress-COMPRESS-164`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-164
//
// ## Issue-Title:
// Cannot Read Winzip Archives With Unicode Extra Fields
//
// ## Issue-Description:
//
// I have a zip file created with WinZip containing Unicode extra fields. Upon attempting to extract it with org.apache.commons.compress.archivers.zip.ZipFile, ZipFile.getInputStream() returns null for ZipArchiveEntries previously retrieved with ZipFile.getEntry() or even ZipFile.getEntries(). See UTF8ZipFilesTest.patch in the attachments for a test case exposing the bug. The original test case stopped short of trying to read the entries, that's why this wasn't flagged up before.
//
//
// The problem lies in the fact that inside ZipFile.java entries are stored in a HashMap. However, at one point after populating the HashMap, the unicode extra fields are read, which leads to a change of the ZipArchiveEntry name, and therefore a change of its hash code. Because of this, subsequent gets on the HashMap fail to retrieve the original values.
//
//
// ZipFile.patch contains an (admittedly simple-minded) fix for this problem by reconstructing the entries HashMap after the Unicode extra fields have been parsed. The purpose of this patch is mainly to show that the problem is indeed what I think, rather than providing a well-designed solution.
//
//
// The patches have been tested against revision 1210416.
//
//
//
//
//
public void testReadWinZipArchive() throws IOException, URISyntaxException {
| 137 | /*
* WinZIP created archive, uses Unicode Extra Fields but only in
* the central directory.
*/ | 10 | 125 | src/test/java/org/apache/commons/compress/archivers/zip/UTF8ZipFilesTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-164
## Issue-Title:
Cannot Read Winzip Archives With Unicode Extra Fields
## Issue-Description:
I have a zip file created with WinZip containing Unicode extra fields. Upon attempting to extract it with org.apache.commons.compress.archivers.zip.ZipFile, ZipFile.getInputStream() returns null for ZipArchiveEntries previously retrieved with ZipFile.getEntry() or even ZipFile.getEntries(). See UTF8ZipFilesTest.patch in the attachments for a test case exposing the bug. The original test case stopped short of trying to read the entries, that's why this wasn't flagged up before.
The problem lies in the fact that inside ZipFile.java entries are stored in a HashMap. However, at one point after populating the HashMap, the unicode extra fields are read, which leads to a change of the ZipArchiveEntry name, and therefore a change of its hash code. Because of this, subsequent gets on the HashMap fail to retrieve the original values.
ZipFile.patch contains an (admittedly simple-minded) fix for this problem by reconstructing the entries HashMap after the Unicode extra fields have been parsed. The purpose of this patch is mainly to show that the problem is indeed what I think, rather than providing a well-designed solution.
The patches have been tested against revision 1210416.
```
You are a professional Java test case writer, please create a test case named `testReadWinZipArchive` for the issue `Compress-COMPRESS-164`, utilizing the provided issue report information and the following function signature.
```java
public void testReadWinZipArchive() throws IOException, URISyntaxException {
```
| 125 | [
"org.apache.commons.compress.archivers.zip.ZipFile"
] | 6a76ff01253aecbc60ee6aa5757838b163bc15b9f8c1142f2b7919644aff19cd | public void testReadWinZipArchive() throws IOException, URISyntaxException | // You are a professional Java test case writer, please create a test case named `testReadWinZipArchive` for the issue `Compress-COMPRESS-164`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-164
//
// ## Issue-Title:
// Cannot Read Winzip Archives With Unicode Extra Fields
//
// ## Issue-Description:
//
// I have a zip file created with WinZip containing Unicode extra fields. Upon attempting to extract it with org.apache.commons.compress.archivers.zip.ZipFile, ZipFile.getInputStream() returns null for ZipArchiveEntries previously retrieved with ZipFile.getEntry() or even ZipFile.getEntries(). See UTF8ZipFilesTest.patch in the attachments for a test case exposing the bug. The original test case stopped short of trying to read the entries, that's why this wasn't flagged up before.
//
//
// The problem lies in the fact that inside ZipFile.java entries are stored in a HashMap. However, at one point after populating the HashMap, the unicode extra fields are read, which leads to a change of the ZipArchiveEntry name, and therefore a change of its hash code. Because of this, subsequent gets on the HashMap fail to retrieve the original values.
//
//
// ZipFile.patch contains an (admittedly simple-minded) fix for this problem by reconstructing the entries HashMap after the Unicode extra fields have been parsed. The purpose of this patch is mainly to show that the problem is indeed what I think, rather than providing a well-designed solution.
//
//
// The patches have been tested against revision 1210416.
//
//
//
//
//
| Compress | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.commons.compress.archivers.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.zip.CRC32;
import org.apache.commons.compress.AbstractTestCase;
public class UTF8ZipFilesTest extends AbstractTestCase {
private static final String UTF_8 = "utf-8";
private static final String CP437 = "cp437";
private static final String US_ASCII = "US-ASCII";
private static final String ASCII_TXT = "ascii.txt";
private static final String EURO_FOR_DOLLAR_TXT = "\u20AC_for_Dollar.txt";
private static final String OIL_BARREL_TXT = "\u00D6lf\u00E4sser.txt";
public void testUtf8FileRoundtripExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, true, true);
}
public void testUtf8FileRoundtripNoEFSExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, false, true);
}
public void testCP437FileRoundtripExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(CP437, false, true);
}
public void testASCIIFileRoundtripExplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(US_ASCII, false, true);
}
public void testUtf8FileRoundtripImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, true, false);
}
public void testUtf8FileRoundtripNoEFSImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(UTF_8, false, false);
}
public void testCP437FileRoundtripImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(CP437, false, false);
}
public void testASCIIFileRoundtripImplicitUnicodeExtra()
throws IOException {
testFileRoundtrip(US_ASCII, false, false);
}
/*
* 7-ZIP created archive, uses EFS to signal UTF-8 filenames.
*
* 7-ZIP doesn't use EFS for strings that can be encoded in CP437
* - which is true for OIL_BARREL_TXT.
*/
public void testRead7ZipArchive() throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, CP437, false);
assertNotNull(zf.getEntry(ASCII_TXT));
assertNotNull(zf.getEntry(EURO_FOR_DOLLAR_TXT));
assertNotNull(zf.getEntry(OIL_BARREL_TXT));
} finally {
ZipFile.closeQuietly(zf);
}
}
public void testRead7ZipArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
FileInputStream archive =
new FileInputStream(new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive, CP437, false);
assertEquals(ASCII_TXT, zi.getNextEntry().getName());
assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
assertEquals(EURO_FOR_DOLLAR_TXT, zi.getNextEntry().getName());
} finally {
if (zi != null) {
zi.close();
}
}
}
/*
* WinZIP created archive, uses Unicode Extra Fields but only in
* the central directory.
*/
public void testReadWinZipArchive() throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-winzip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, null, true);
assertCanRead(zf, ASCII_TXT);
assertCanRead(zf, EURO_FOR_DOLLAR_TXT);
assertCanRead(zf, OIL_BARREL_TXT);
} finally {
ZipFile.closeQuietly(zf);
}
}
private void assertCanRead(ZipFile zf, String fileName) throws IOException {
ZipArchiveEntry entry = zf.getEntry(fileName);
assertNotNull("Entry doesn't exist", entry);
InputStream is = zf.getInputStream(entry);
assertNotNull("InputStream is null", is);
try {
is.read();
} finally {
is.close();
}
}
public void testReadWinZipArchiveForStream() throws IOException,
URISyntaxException {
URL zip = getClass().getResource("/utf8-winzip-test.zip");
FileInputStream archive =
new FileInputStream(new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive, null, true);
assertEquals(EURO_FOR_DOLLAR_TXT, zi.getNextEntry().getName());
assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
assertEquals(ASCII_TXT, zi.getNextEntry().getName());
} finally {
if (zi != null) {
zi.close();
}
}
}
public void testZipFileReadsUnicodeFields() throws IOException {
File file = File.createTempFile("unicode-test", ".zip");
file.deleteOnExit();
ZipArchiveInputStream zi = null;
try {
createTestFile(file, US_ASCII, false, true);
FileInputStream archive = new FileInputStream(file);
zi = new ZipArchiveInputStream(archive, US_ASCII, true);
assertEquals(OIL_BARREL_TXT, zi.getNextEntry().getName());
assertEquals(EURO_FOR_DOLLAR_TXT, zi.getNextEntry().getName());
assertEquals(ASCII_TXT, zi.getNextEntry().getName());
} finally {
if (zi != null) {
zi.close();
}
tryHardToDelete(file);
}
}
public void testZipArchiveInputStreamReadsUnicodeFields()
throws IOException {
File file = File.createTempFile("unicode-test", ".zip");
file.deleteOnExit();
ZipFile zf = null;
try {
createTestFile(file, US_ASCII, false, true);
zf = new ZipFile(file, US_ASCII, true);
assertNotNull(zf.getEntry(ASCII_TXT));
assertNotNull(zf.getEntry(EURO_FOR_DOLLAR_TXT));
assertNotNull(zf.getEntry(OIL_BARREL_TXT));
} finally {
ZipFile.closeQuietly(zf);
tryHardToDelete(file);
}
}
public void testRawNameReadFromZipFile()
throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
File archive = new File(new URI(zip.toString()));
ZipFile zf = null;
try {
zf = new ZipFile(archive, CP437, false);
assertRawNameOfAcsiiTxt(zf.getEntry(ASCII_TXT));
} finally {
ZipFile.closeQuietly(zf);
}
}
public void testRawNameReadFromStream()
throws IOException, URISyntaxException {
URL zip = getClass().getResource("/utf8-7zip-test.zip");
FileInputStream archive =
new FileInputStream(new File(new URI(zip.toString())));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive, CP437, false);
assertRawNameOfAcsiiTxt((ZipArchiveEntry) zi.getNextEntry());
} finally {
if (zi != null) {
zi.close();
}
}
}
private static void testFileRoundtrip(String encoding, boolean withEFS,
boolean withExplicitUnicodeExtra)
throws IOException {
File file = File.createTempFile(encoding + "-test", ".zip");
file.deleteOnExit();
try {
createTestFile(file, encoding, withEFS, withExplicitUnicodeExtra);
testFile(file, encoding);
} finally {
tryHardToDelete(file);
}
}
private static void createTestFile(File file, String encoding,
boolean withEFS,
boolean withExplicitUnicodeExtra)
throws UnsupportedEncodingException, IOException {
ZipEncoding zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
ZipArchiveOutputStream zos = null;
try {
zos = new ZipArchiveOutputStream(file);
zos.setEncoding(encoding);
zos.setUseLanguageEncodingFlag(withEFS);
zos.setCreateUnicodeExtraFields(withExplicitUnicodeExtra ?
ZipArchiveOutputStream
.UnicodeExtraFieldPolicy.NEVER
: ZipArchiveOutputStream
.UnicodeExtraFieldPolicy.ALWAYS);
ZipArchiveEntry ze = new ZipArchiveEntry(OIL_BARREL_TXT);
if (withExplicitUnicodeExtra
&& !zipEncoding.canEncode(ze.getName())) {
ByteBuffer en = zipEncoding.encode(ze.getName());
ze.addExtraField(new UnicodePathExtraField(ze.getName(),
en.array(),
en.arrayOffset(),
en.limit()));
}
zos.putArchiveEntry(ze);
zos.write("Hello, world!".getBytes("US-ASCII"));
zos.closeArchiveEntry();
ze = new ZipArchiveEntry(EURO_FOR_DOLLAR_TXT);
if (withExplicitUnicodeExtra
&& !zipEncoding.canEncode(ze.getName())) {
ByteBuffer en = zipEncoding.encode(ze.getName());
ze.addExtraField(new UnicodePathExtraField(ze.getName(),
en.array(),
en.arrayOffset(),
en.limit()));
}
zos.putArchiveEntry(ze);
zos.write("Give me your money!".getBytes("US-ASCII"));
zos.closeArchiveEntry();
ze = new ZipArchiveEntry(ASCII_TXT);
if (withExplicitUnicodeExtra
&& !zipEncoding.canEncode(ze.getName())) {
ByteBuffer en = zipEncoding.encode(ze.getName());
ze.addExtraField(new UnicodePathExtraField(ze.getName(),
en.array(),
en.arrayOffset(),
en.limit()));
}
zos.putArchiveEntry(ze);
zos.write("ascii".getBytes("US-ASCII"));
zos.closeArchiveEntry();
zos.finish();
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) { /* swallow */ }
}
}
}
private static void testFile(File file, String encoding)
throws IOException {
ZipFile zf = null;
try {
zf = new ZipFile(file, encoding, false);
Enumeration<ZipArchiveEntry> e = zf.getEntries();
while (e.hasMoreElements()) {
ZipArchiveEntry ze = e.nextElement();
if (ze.getName().endsWith("sser.txt")) {
assertUnicodeName(ze, OIL_BARREL_TXT, encoding);
} else if (ze.getName().endsWith("_for_Dollar.txt")) {
assertUnicodeName(ze, EURO_FOR_DOLLAR_TXT, encoding);
} else if (!ze.getName().equals(ASCII_TXT)) {
throw new AssertionError("Urecognized ZIP entry with name ["
+ ze.getName() + "] found.");
}
}
} finally {
ZipFile.closeQuietly(zf);
}
}
private static UnicodePathExtraField findUniCodePath(ZipArchiveEntry ze) {
return (UnicodePathExtraField)
ze.getExtraField(UnicodePathExtraField.UPATH_ID);
}
private static void assertUnicodeName(ZipArchiveEntry ze,
String expectedName,
String encoding)
throws IOException {
if (!expectedName.equals(ze.getName())) {
UnicodePathExtraField ucpf = findUniCodePath(ze);
assertNotNull(ucpf);
ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encoding);
ByteBuffer ne = enc.encode(ze.getName());
CRC32 crc = new CRC32();
crc.update(ne.array(),ne.arrayOffset(),ne.limit());
assertEquals(crc.getValue(), ucpf.getNameCRC32());
assertEquals(expectedName, new String(ucpf.getUnicodeName(),
UTF_8));
}
}
public void testUtf8Interoperability() throws IOException {
File file1 = super.getFile("utf8-7zip-test.zip");
File file2 = super.getFile("utf8-winzip-test.zip");
testFile(file1,CP437);
testFile(file2,CP437);
}
private static void assertRawNameOfAcsiiTxt(ZipArchiveEntry ze) {
byte[] b = ze.getRawName();
assertNotNull(b);
final int len = ASCII_TXT.length();
assertEquals(len, b.length);
for (int i = 0; i < len; i++) {
assertEquals("Byte " + i, (byte) ASCII_TXT.charAt(i), b[i]);
}
assertNotSame(b, ze.getRawName());
}
}
|
|
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
} | org.apache.commons.compress.utils.ChecksumCalculatingInputStreamTest::testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne | src/test/java/org/apache/commons/compress/utils/ChecksumCalculatingInputStreamTest.java | 115 | src/test/java/org/apache/commons/compress/utils/ChecksumCalculatingInputStreamTest.java | testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.compress.utils;
import org.junit.Test;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import static org.junit.Assert.*;
/**
* Unit tests for class {@link ChecksumCalculatingInputStream org.apache.commons.compress.utils.ChecksumCalculatingInputStream}.
*
* @date 13.06.2017
* @see ChecksumCalculatingInputStream
**/
public class ChecksumCalculatingInputStreamTest {
@Test
public void testSkipReturningZero() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
long skipResult = checksumCalculatingInputStream.skip(60L);
assertEquals(0L, skipResult);
assertEquals(1L, checksumCalculatingInputStream.getValue());
}
@Test
public void testSkipReturningPositive() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[6];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
long skipResult = checksumCalculatingInputStream.skip((byte)0);
assertEquals(1L, skipResult);
assertEquals(65537L, checksumCalculatingInputStream.getValue());
}
@Test
public void testReadTakingNoArguments() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[6];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
BufferedInputStream bufferedInputStream = new BufferedInputStream(checksumCalculatingInputStream);
int inputStreamReadResult = bufferedInputStream.read(byteArray, 0, 1);
int checkSumCalculationReadResult = checksumCalculatingInputStream.read();
assertFalse(checkSumCalculationReadResult == inputStreamReadResult);
assertEquals((-1), checkSumCalculationReadResult);
assertEquals(0, byteArrayInputStream.available());
assertEquals(393217L, checksumCalculatingInputStream.getValue());
}
@Test
public void testReadTakingByteArray() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[6];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
int readResult = checksumCalculatingInputStream.read(byteArray);
assertEquals(6, readResult);
assertEquals(0, byteArrayInputStream.available());
assertEquals(393217L, checksumCalculatingInputStream.getValue());
}
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
}
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionTwo() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,new ByteArrayInputStream(new byte[1]));
}
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionThree() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(new CRC32(),null);
}
} | // You are a professional Java test case writer, please create a test case named `testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne` for the issue `Compress-COMPRESS-412`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-412
//
// ## Issue-Title:
// NullPointerException defect in ChecksumCalculatingInputStream#getValue()
//
// ## Issue-Description:
//
// NullPointerException defect in ChecksumCalculatingInputStream#getValue() detected as stated in pull request 33: <https://github.com/apache/commons-compress/pull/33>
//
//
// Furthermore the following test describes the problem:
//
//
//
//
// ```
// @Test(expected = NullPointerException.class) //I assume this behaviour to be a bug or at least a defect.
// public void testGetValueThrowsNullPointerException() {
//
// ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
//
// checksumCalculatingInputStream.getValue();
//
//
// }
//
// ```
//
//
//
//
//
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() {
| 115 | 44 | 109 | src/test/java/org/apache/commons/compress/utils/ChecksumCalculatingInputStreamTest.java | src/test/java | ```markdown
## Issue-ID: Compress-COMPRESS-412
## Issue-Title:
NullPointerException defect in ChecksumCalculatingInputStream#getValue()
## Issue-Description:
NullPointerException defect in ChecksumCalculatingInputStream#getValue() detected as stated in pull request 33: <https://github.com/apache/commons-compress/pull/33>
Furthermore the following test describes the problem:
```
@Test(expected = NullPointerException.class) //I assume this behaviour to be a bug or at least a defect.
public void testGetValueThrowsNullPointerException() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
checksumCalculatingInputStream.getValue();
}
```
```
You are a professional Java test case writer, please create a test case named `testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne` for the issue `Compress-COMPRESS-412`, utilizing the provided issue report information and the following function signature.
```java
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() {
```
| 109 | [
"org.apache.commons.compress.utils.ChecksumCalculatingInputStream"
] | 6be01a28b050ffc89a13f5690e46799a2088bedfd818e65701752bc400cea996 | @Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() | // You are a professional Java test case writer, please create a test case named `testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne` for the issue `Compress-COMPRESS-412`, utilizing the provided issue report information and the following function signature.
// ## Issue-ID: Compress-COMPRESS-412
//
// ## Issue-Title:
// NullPointerException defect in ChecksumCalculatingInputStream#getValue()
//
// ## Issue-Description:
//
// NullPointerException defect in ChecksumCalculatingInputStream#getValue() detected as stated in pull request 33: <https://github.com/apache/commons-compress/pull/33>
//
//
// Furthermore the following test describes the problem:
//
//
//
//
// ```
// @Test(expected = NullPointerException.class) //I assume this behaviour to be a bug or at least a defect.
// public void testGetValueThrowsNullPointerException() {
//
// ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
//
// checksumCalculatingInputStream.getValue();
//
//
// }
//
// ```
//
//
//
//
//
| Compress | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.compress.utils;
import org.junit.Test;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import static org.junit.Assert.*;
/**
* Unit tests for class {@link ChecksumCalculatingInputStream org.apache.commons.compress.utils.ChecksumCalculatingInputStream}.
*
* @date 13.06.2017
* @see ChecksumCalculatingInputStream
**/
public class ChecksumCalculatingInputStreamTest {
@Test
public void testSkipReturningZero() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
long skipResult = checksumCalculatingInputStream.skip(60L);
assertEquals(0L, skipResult);
assertEquals(1L, checksumCalculatingInputStream.getValue());
}
@Test
public void testSkipReturningPositive() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[6];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
long skipResult = checksumCalculatingInputStream.skip((byte)0);
assertEquals(1L, skipResult);
assertEquals(65537L, checksumCalculatingInputStream.getValue());
}
@Test
public void testReadTakingNoArguments() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[6];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
BufferedInputStream bufferedInputStream = new BufferedInputStream(checksumCalculatingInputStream);
int inputStreamReadResult = bufferedInputStream.read(byteArray, 0, 1);
int checkSumCalculationReadResult = checksumCalculatingInputStream.read();
assertFalse(checkSumCalculationReadResult == inputStreamReadResult);
assertEquals((-1), checkSumCalculationReadResult);
assertEquals(0, byteArrayInputStream.available());
assertEquals(393217L, checksumCalculatingInputStream.getValue());
}
@Test
public void testReadTakingByteArray() throws IOException {
Adler32 adler32 = new Adler32();
byte[] byteArray = new byte[6];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(adler32, byteArrayInputStream);
int readResult = checksumCalculatingInputStream.read(byteArray);
assertEquals(6, readResult);
assertEquals(0, byteArrayInputStream.available());
assertEquals(393217L, checksumCalculatingInputStream.getValue());
}
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionOne() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,null);
}
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionTwo() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(null,new ByteArrayInputStream(new byte[1]));
}
@Test(expected = NullPointerException.class)
public void testClassInstantiationWithParameterBeingNullThrowsNullPointerExceptionThree() {
ChecksumCalculatingInputStream checksumCalculatingInputStream = new ChecksumCalculatingInputStream(new CRC32(),null);
}
} |