code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link NullsFirstOrdering}.
*
* @author Chris Povirk
*/
public class NullsFirstOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
NullsFirstOrdering<?> instance) {
}
@SuppressWarnings("unchecked") // deserialization is unsafe
public static NullsFirstOrdering<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
return new NullsFirstOrdering<Object>(
(Ordering<Object>) reader.readObject());
}
public static void serialize(SerializationStreamWriter writer,
NullsFirstOrdering<?> instance) throws SerializationException {
writer.writeObject(instance.ordering);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/NullsFirstOrdering_CustomFieldSerializer.java | Java | asf20 | 1,585 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import java.util.Comparator;
/**
* This class implements the GWT serialization of {@link CompoundOrdering}.
*
* @author Chris Povirk
*/
public class CompoundOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
CompoundOrdering<?> instance) {
}
@SuppressWarnings("unchecked") // deserialization is unsafe
public static CompoundOrdering<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
return new CompoundOrdering<Object>(
(ImmutableList<Comparator<Object>>) reader.readObject());
}
public static void serialize(SerializationStreamWriter writer,
CompoundOrdering<?> instance) throws SerializationException {
writer.writeObject(instance.comparators);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/CompoundOrdering_CustomFieldSerializer.java | Java | asf20 | 1,623 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link NaturalOrdering}.
*
* @author Chris Povirk
*/
public class NaturalOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
NaturalOrdering instance) {
}
public static NaturalOrdering instantiate(
SerializationStreamReader reader) {
return NaturalOrdering.INSTANCE;
}
public static void serialize(SerializationStreamWriter writer,
NaturalOrdering instance) {
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/NaturalOrdering_CustomFieldSerializer.java | Java | asf20 | 1,274 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of
* {@link SingletonImmutableList}.
*
* @author Chris Povirk
*/
public class SingletonImmutableList_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
SingletonImmutableList<?> instance) {
}
public static SingletonImmutableList<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
Object element = reader.readObject();
return new SingletonImmutableList<Object>(element);
}
public static void serialize(SerializationStreamWriter writer,
SingletonImmutableList<?> instance) throws SerializationException {
writer.writeObject(instance.element);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/SingletonImmutableList_CustomFieldSerializer.java | Java | asf20 | 1,552 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
/**
* Even though {@link ForwardingImmutableSet} cannot be instantiated, we still
* need a custom field serializer. TODO(cpovirk): why?
*
* @author Hayward Chan
*/
public final class ForwardingImmutableSet_CustomFieldSerializer {}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ForwardingImmutableSet_CustomFieldSerializer.java | Java | asf20 | 874 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link ExplicitOrdering}.
*
* @author Chris Povirk
*/
public class ExplicitOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
ExplicitOrdering<?> instance) {
}
@SuppressWarnings("unchecked") // deserialization is unsafe
public static ExplicitOrdering<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
return new ExplicitOrdering<Object>(
(ImmutableMap<Object, Integer>) reader.readObject());
}
public static void serialize(SerializationStreamWriter writer,
ExplicitOrdering<?> instance) throws SerializationException {
writer.writeObject(instance.rankMap);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ExplicitOrdering_CustomFieldSerializer.java | Java | asf20 | 1,585 |
/*
* Copyright (C) 2010 The Guava 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.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the server-side GWT serialization of
* {@link RegularImmutableAsList}.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
public class RegularImmutableAsList_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
RegularImmutableAsList<?> instance) {
}
public static RegularImmutableAsList<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
@SuppressWarnings("unchecked") // serialization is necessarily type unsafe
ImmutableCollection<Object> delegateCollection = (ImmutableCollection) reader.readObject();
ImmutableList<?> delegateList = (ImmutableList<?>) reader.readObject();
return new RegularImmutableAsList<Object>(delegateCollection, delegateList);
}
public static void serialize(SerializationStreamWriter writer,
RegularImmutableAsList<?> instance) throws SerializationException {
writer.writeObject(instance.delegateCollection());
writer.writeObject(instance.delegateList());
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/RegularImmutableAsList_CustomFieldSerializer.java | Java | asf20 | 1,942 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link SingletonImmutableBiMap}.
*
* @author Chris Povirk
*/
public class SingletonImmutableBiMap_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
SingletonImmutableBiMap<?, ?> instance) {
}
public static SingletonImmutableBiMap<Object, Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
Object key = checkNotNull(reader.readObject());
Object value = checkNotNull(reader.readObject());
return new SingletonImmutableBiMap<Object, Object>(key, value);
}
public static void serialize(SerializationStreamWriter writer,
SingletonImmutableBiMap<?, ?> instance) throws SerializationException {
writer.writeObject(instance.singleKey);
writer.writeObject(instance.singleValue);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/SingletonImmutableBiMap_CustomFieldSerializer.java | Java | asf20 | 1,758 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link SingletonImmutableTable}.
*
* @author Chris Povirk
*/
public class SingletonImmutableTable_CustomFieldSerializer {
public static void deserialize(
SerializationStreamReader reader, SingletonImmutableTable<?, ?, ?> instance) {
}
public static SingletonImmutableTable<Object, Object, Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
Object rowKey = reader.readObject();
Object columnKey = reader.readObject();
Object value = reader.readObject();
return new SingletonImmutableTable<Object, Object, Object>(rowKey, columnKey, value);
}
public static void serialize(
SerializationStreamWriter writer, SingletonImmutableTable<?, ?, ?> instance)
throws SerializationException {
writer.writeObject(instance.singleRowKey);
writer.writeObject(instance.singleColumnKey);
writer.writeObject(instance.singleValue);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/SingletonImmutableTable_CustomFieldSerializer.java | Java | asf20 | 1,799 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
/**
* Even though {@link ForwardingImmutableList} cannot be instantiated, we still
* need a custom field serializer. TODO(cpovirk): why?
*
* @author Hayward Chan
*/
public final class ForwardingImmutableList_CustomFieldSerializer {}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ForwardingImmutableList_CustomFieldSerializer.java | Java | asf20 | 876 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of
* {@link ReverseNaturalOrdering}.
*
* @author Chris Povirk
*/
public class ReverseNaturalOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
ReverseNaturalOrdering instance) {
}
public static ReverseNaturalOrdering instantiate(
SerializationStreamReader reader) {
return ReverseNaturalOrdering.INSTANCE;
}
public static void serialize(SerializationStreamWriter writer,
ReverseNaturalOrdering instance) {
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ReverseNaturalOrdering_CustomFieldSerializer.java | Java | asf20 | 1,319 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
/**
* Even though {@link ImmutableSet} cannot be instantiated, we still need
* a custom field serializer to unify the type signature of
* {@code ImmutableSet[]} on server and client side.
*
* @author Hayward Chan
*/
public final class ImmutableSet_CustomFieldSerializer {}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableSet_CustomFieldSerializer.java | Java | asf20 | 917 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link AllEqualOrdering}.
*
* @author Chris Povirk
*/
public class AllEqualOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader, AllEqualOrdering instance) {
}
public static AllEqualOrdering instantiate(SerializationStreamReader reader) {
return AllEqualOrdering.INSTANCE;
}
public static void serialize(SerializationStreamWriter writer, AllEqualOrdering instance) {
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/AllEqualOrdering_CustomFieldSerializer.java | Java | asf20 | 1,259 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link ImmutableListMultimap}.
*
* @author Chris Povirk
*/
public class ImmutableListMultimap_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
ImmutableListMultimap<?, ?> instance) {
}
public static ImmutableListMultimap<Object, Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
return (ImmutableListMultimap<Object, Object>)
Multimap_CustomFieldSerializerBase.instantiate(
reader, ImmutableListMultimap.builder());
}
public static void serialize(SerializationStreamWriter writer,
ImmutableListMultimap<?, ?> instance) throws SerializationException {
Multimap_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableListMultimap_CustomFieldSerializer.java | Java | asf20 | 1,645 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
/**
* Even though {@link ImmutableSortedMap} cannot be instantiated, we still need a custom field
* serializer. TODO(cpovirk): why? Does it help if ensure that the GWT and non-GWT classes have the
* same fields? Is that worth the trouble?
*
* @author Chris Povirk
*/
public final class ImmutableSortedMap_CustomFieldSerializer {}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableSortedMap_CustomFieldSerializer.java | Java | asf20 | 974 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
/**
* Even though {@link ImmutableAsList} cannot be instantiated, we still need
* a custom field serializer. TODO(cpovirk): why?
*
* @author Hayward Chan
*/
public final class ImmutableAsList_CustomFieldSerializer {}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableAsList_CustomFieldSerializer.java | Java | asf20 | 860 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import java.util.Comparator;
/**
* This class implements the GWT serialization of {@link TreeMultimap}.
*
* @author Nikhil Singhal
*/
public class TreeMultimap_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader in,
TreeMultimap<?, ?> out) {
}
@SuppressWarnings("unchecked")
public static TreeMultimap<Object, Object> instantiate(
SerializationStreamReader in) throws SerializationException {
Comparator<Object> keyComparator = (Comparator<Object>) in.readObject();
Comparator<Object> valueComparator = (Comparator<Object>) in.readObject();
return (TreeMultimap<Object, Object>)
Multimap_CustomFieldSerializerBase.populate(
in, TreeMultimap.create(keyComparator, valueComparator));
}
public static void serialize(SerializationStreamWriter out,
TreeMultimap<?, ?> multimap) throws SerializationException {
out.writeObject(multimap.keyComparator());
out.writeObject(multimap.valueComparator());
Multimap_CustomFieldSerializerBase.serialize(out, multimap);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/TreeMultimap_CustomFieldSerializer.java | Java | asf20 | 1,903 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import java.util.Comparator;
/**
* This class implements the GWT serialization of {@link ImmutableSetMultimap}.
*
* @author Chris Povirk
*/
public class ImmutableSetMultimap_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
ImmutableSetMultimap<?, ?> instance) {
}
// Serialization type safety is at the caller's mercy.
@SuppressWarnings("unchecked")
public static ImmutableSetMultimap<Object, Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
Comparator<Object> valueComparator = (Comparator<Object>) reader.readObject();
ImmutableSetMultimap.Builder<Object, Object> builder = ImmutableSetMultimap.builder();
if (valueComparator != null) {
builder.orderValuesBy(valueComparator);
}
return (ImmutableSetMultimap<Object, Object>)
Multimap_CustomFieldSerializerBase.instantiate(reader, builder);
}
public static void serialize(SerializationStreamWriter writer,
ImmutableSetMultimap<?, ?> instance) throws SerializationException {
writer.writeObject(instance.valueComparator());
Multimap_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableSetMultimap_CustomFieldSerializer.java | Java | asf20 | 2,035 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase;
import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* This class contains static utility methods for writing {@code ImmutableSortedMap} GWT field
* serializers.
*
* @author Chris Povirk
*/
final class ImmutableSortedMap_CustomFieldSerializerBase {
static ImmutableSortedMap<Object, Object> instantiate(SerializationStreamReader reader)
throws SerializationException {
/*
* Nothing we can do, but we're already assuming the serialized form is
* correctly typed, anyway.
*/
@SuppressWarnings("unchecked")
Comparator<Object> comparator = (Comparator<Object>) reader.readObject();
SortedMap<Object, Object> entries = new TreeMap<Object, Object>(comparator);
Map_CustomFieldSerializerBase.deserialize(reader, entries);
return ImmutableSortedMap.orderedBy(comparator).putAll(entries).build();
}
static void serialize(SerializationStreamWriter writer, ImmutableSortedMap<?, ?> instance)
throws SerializationException {
writer.writeObject(instance.comparator());
Map_CustomFieldSerializerBase.serialize(writer, instance);
}
private ImmutableSortedMap_CustomFieldSerializerBase() {}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableSortedMap_CustomFieldSerializerBase.java | Java | asf20 | 2,106 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase;
import java.util.List;
/**
* This class implements the GWT serialization of {@link RegularImmutableSet}.
*
* @author Hayward Chan
*/
public class RegularImmutableSet_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
RegularImmutableSet<?> instance) {
}
public static RegularImmutableSet<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
List<Object> elements = Lists.newArrayList();
Collection_CustomFieldSerializerBase.deserialize(reader, elements);
/*
* For this custom field serializer to be invoked, the set must have been
* RegularImmutableSet before it's serialized. Since RegularImmutableSet
* always have two or more elements, ImmutableSet.copyOf always return
* a RegularImmutableSet back.
*/
return (RegularImmutableSet<Object>) ImmutableSet.copyOf(elements);
}
public static void serialize(SerializationStreamWriter writer,
RegularImmutableSet<?> instance) throws SerializationException {
Collection_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/RegularImmutableSet_CustomFieldSerializer.java | Java | asf20 | 2,052 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link HashMultiset}.
*
* @author Chris Povirk
*/
public class HashMultiset_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
HashMultiset<?> instance) {
}
public static HashMultiset<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
return (HashMultiset<Object>) Multiset_CustomFieldSerializerBase.populate(
reader, HashMultiset.create());
}
public static void serialize(SerializationStreamWriter writer,
HashMultiset<?> instance) throws SerializationException {
Multiset_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/HashMultiset_CustomFieldSerializer.java | Java | asf20 | 1,544 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of
* {@link EmptyImmutableListMultimap}.
*
* @author Chris Povirk
*/
public class EmptyImmutableListMultimap_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
EmptyImmutableListMultimap instance) {
}
public static EmptyImmutableListMultimap instantiate(
SerializationStreamReader reader) {
return EmptyImmutableListMultimap.INSTANCE;
}
public static void serialize(SerializationStreamWriter writer,
EmptyImmutableListMultimap instance) {
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/EmptyImmutableListMultimap_CustomFieldSerializer.java | Java | asf20 | 1,343 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* This class implements the GWT serialization of
* {@link RegularImmutableBiMap}.
*
* @author Chris Povirk
*/
public class RegularImmutableBiMap_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
RegularImmutableBiMap<?, ?> instance) {
}
public static RegularImmutableBiMap<Object, Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
Map<Object, Object> entries = new LinkedHashMap<Object, Object>();
Map_CustomFieldSerializerBase.deserialize(reader, entries);
/*
* For this custom field serializer to be invoked, the map must have been
* RegularImmutableBiMap before it's serialized. Since RegularImmutableBiMap
* always have one or more elements, ImmutableBiMap.copyOf always return a
* RegularImmutableBiMap back.
*/
return
(RegularImmutableBiMap<Object, Object>) ImmutableBiMap.copyOf(entries);
}
public static void serialize(SerializationStreamWriter writer,
RegularImmutableBiMap<?, ?> instance) throws SerializationException {
Map_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/RegularImmutableBiMap_CustomFieldSerializer.java | Java | asf20 | 2,136 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements the GWT serialization of {@link
* RegularImmutableList}.
*
* @author Hayward Chan
*/
public class RegularImmutableList_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
RegularImmutableList<?> instance) {
}
public static RegularImmutableList<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
List<Object> elements = new ArrayList<Object>();
Collection_CustomFieldSerializerBase.deserialize(reader, elements);
/*
* For this custom field serializer to be invoked, the list must have been
* RegularImmutableList before it's serialized. Since RegularImmutableList
* always have one or more elements, ImmutableList.copyOf always return
* a RegularImmutableList back.
*/
return (RegularImmutableList<Object>) ImmutableList.copyOf(elements);
}
public static void serialize(SerializationStreamWriter writer,
RegularImmutableList<?> instance) throws SerializationException {
Collection_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/RegularImmutableList_CustomFieldSerializer.java | Java | asf20 | 2,098 |
/*
* Copyright (C) 2011 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase;
import java.util.List;
/**
* This class implements the GWT serialization of {@link RegularImmutableMultiset}.
*
* @author Louis Wasserman
*/
public class RegularImmutableMultiset_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
RegularImmutableMultiset<?> instance) {
}
public static RegularImmutableMultiset<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
List<Object> elements = Lists.newArrayList();
Collection_CustomFieldSerializerBase.deserialize(reader, elements);
/*
* For this custom field serializer to be invoked, the set must have been
* RegularImmutableMultiset before it's serialized. Since
* RegularImmutableMultiset always have one or more elements,
* ImmutableMultiset.copyOf always return a RegularImmutableMultiset back.
*/
return (RegularImmutableMultiset<Object>) ImmutableMultiset
.copyOf(elements);
}
public static void serialize(SerializationStreamWriter writer,
RegularImmutableMultiset<?> instance) throws SerializationException {
Collection_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/RegularImmutableMultiset_CustomFieldSerializer.java | Java | asf20 | 2,118 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.common.base.Function;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
/**
* This class implements the GWT serialization of {@link ByFunctionOrdering}.
*
* @author Chris Povirk
*/
public class ByFunctionOrdering_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
ByFunctionOrdering<?, ?> instance) {
}
@SuppressWarnings("unchecked") // deserialization is unsafe
public static ByFunctionOrdering<Object, Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
return new ByFunctionOrdering<Object, Object>(
(Function<Object, Object>) reader.readObject(),
(Ordering<Object>) reader.readObject());
}
public static void serialize(SerializationStreamWriter writer,
ByFunctionOrdering<?, ?> instance) throws SerializationException {
writer.writeObject(instance.function);
writer.writeObject(instance.ordering);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ByFunctionOrdering_CustomFieldSerializer.java | Java | asf20 | 1,746 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase;
import java.util.List;
/**
* This class implements the GWT serialization of {@link ImmutableEnumSet}.
*
* @author Hayward Chan
*/
public class ImmutableEnumSet_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
ImmutableEnumSet<?> instance) {
}
public static <E extends Enum<E>> ImmutableEnumSet<?> instantiate(
SerializationStreamReader reader) throws SerializationException {
List<E> deserialized = Lists.newArrayList();
Collection_CustomFieldSerializerBase.deserialize(reader, deserialized);
/*
* It is safe to cast to ImmutableEnumSet because in order for it to be
* serialized as an ImmutableEnumSet, it must be non-empty to start
* with.
*/
return (ImmutableEnumSet<?>) Sets.immutableEnumSet(deserialized);
}
public static void serialize(SerializationStreamWriter writer,
ImmutableEnumSet<?> instance) throws SerializationException {
Collection_CustomFieldSerializerBase.serialize(writer, instance);
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/ImmutableEnumSet_CustomFieldSerializer.java | Java | asf20 | 1,949 |
/*
* Copyright (C) 2009 The Guava 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.common.collect;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import java.util.Comparator;
/**
* This class implements the GWT serialization of
* {@link EmptyImmutableSortedSet}.
*
* @author Chris Povirk
*/
public class EmptyImmutableSortedSet_CustomFieldSerializer {
public static void deserialize(SerializationStreamReader reader,
EmptyImmutableSortedSet<?> instance) {
}
public static EmptyImmutableSortedSet<Object> instantiate(
SerializationStreamReader reader) throws SerializationException {
/*
* Nothing we can do, but we're already assuming the serialized form is
* correctly typed, anyway.
*/
@SuppressWarnings("unchecked")
Comparator<Object> comparator = (Comparator<Object>) reader.readObject();
/*
* For this custom field serializer to be invoked, the set must have been
* EmptyImmutableSortedSet before it's serialized. Since
* EmptyImmutableSortedSet always has no elements, ImmutableSortedSet.copyOf
* always return an EmptyImmutableSortedSet back.
*/
return (EmptyImmutableSortedSet<Object>)
ImmutableSortedSet.orderedBy(comparator).build();
}
public static void serialize(SerializationStreamWriter writer,
EmptyImmutableSortedSet<?> instance) throws SerializationException {
writer.writeObject(instance.comparator());
}
}
| zzhhhhh-aw4rwer | guava-gwt/src/com/google/common/collect/EmptyImmutableSortedSet_CustomFieldSerializer.java | Java | asf20 | 2,121 |
/*
* Copyright (C) 2012 The Guava 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.common.io;
import static com.google.common.io.BaseEncoding.base16;
import static com.google.common.io.BaseEncoding.base32;
import static com.google.common.io.BaseEncoding.base32Hex;
import static com.google.common.io.BaseEncoding.base64;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.io.BaseEncoding.DecodingException;
import junit.framework.TestCase;
import java.io.UnsupportedEncodingException;
/**
* Tests for {@code BaseEncoding}.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class BaseEncodingTest extends TestCase {
public static void assertEquals(byte[] expected, byte[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], actual[i]);
}
}
public void testSeparatorsExplicitly() {
testEncodes(base64().withSeparator("\n", 3), "foobar", "Zm9\nvYm\nFy");
testEncodes(base64().withSeparator("$", 4), "foobar", "Zm9v$YmFy");
testEncodes(base32().withSeparator("*", 4), "foobar", "MZXW*6YTB*OI==*====");
}
@SuppressWarnings("ReturnValueIgnored")
public void testSeparatorSameAsPadChar() {
try {
base64().withSeparator("=", 3);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
base64().withPadChar('#').withSeparator("!#!", 3);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
@SuppressWarnings("ReturnValueIgnored")
public void testAtMostOneSeparator() {
BaseEncoding separated = base64().withSeparator("\n", 3);
try {
separated.withSeparator("$", 4);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
public void testBase64() {
// The following test vectors are specified in RFC 4648 itself
testEncodingWithSeparators(base64(), "", "");
testEncodingWithSeparators(base64(), "f", "Zg==");
testEncodingWithSeparators(base64(), "fo", "Zm8=");
testEncodingWithSeparators(base64(), "foo", "Zm9v");
testEncodingWithSeparators(base64(), "foob", "Zm9vYg==");
testEncodingWithSeparators(base64(), "fooba", "Zm9vYmE=");
testEncodingWithSeparators(base64(), "foobar", "Zm9vYmFy");
}
public void testBase64LenientPadding() {
testDecodes(base64(), "Zg", "f");
testDecodes(base64(), "Zg=", "f");
testDecodes(base64(), "Zg==", "f"); // proper padding length
testDecodes(base64(), "Zg===", "f");
testDecodes(base64(), "Zg====", "f");
}
public void testBase64InvalidDecodings() {
// These contain bytes not in the decodabet.
assertFailsToDecode(base64(), "\u007f");
assertFailsToDecode(base64(), "Wf2!");
// This sentence just isn't base64() encoded.
assertFailsToDecode(base64(), "let's not talk of love or chains!");
// A 4n+1 length string is never legal base64().
assertFailsToDecode(base64(), "12345");
}
@SuppressWarnings("ReturnValueIgnored")
public void testBase64CannotUpperCase() {
try {
base64().upperCase();
fail();
} catch (IllegalStateException expected) {
// success
}
}
@SuppressWarnings("ReturnValueIgnored")
public void testBase64CannotLowerCase() {
try {
base64().lowerCase();
fail();
} catch (IllegalStateException expected) {
// success
}
}
public void testBase64AlternatePadding() {
BaseEncoding enc = base64().withPadChar('~');
testEncodingWithSeparators(enc, "", "");
testEncodingWithSeparators(enc, "f", "Zg~~");
testEncodingWithSeparators(enc, "fo", "Zm8~");
testEncodingWithSeparators(enc, "foo", "Zm9v");
testEncodingWithSeparators(enc, "foob", "Zm9vYg~~");
testEncodingWithSeparators(enc, "fooba", "Zm9vYmE~");
testEncodingWithSeparators(enc, "foobar", "Zm9vYmFy");
}
public void testBase64OmitPadding() {
BaseEncoding enc = base64().omitPadding();
testEncodingWithSeparators(enc, "", "");
testEncodingWithSeparators(enc, "f", "Zg");
testEncodingWithSeparators(enc, "fo", "Zm8");
testEncodingWithSeparators(enc, "foo", "Zm9v");
testEncodingWithSeparators(enc, "foob", "Zm9vYg");
testEncodingWithSeparators(enc, "fooba", "Zm9vYmE");
testEncodingWithSeparators(enc, "foobar", "Zm9vYmFy");
}
public void testBase32() {
// The following test vectors are specified in RFC 4648 itself
testEncodingWithCasing(base32(), "", "");
testEncodingWithCasing(base32(), "f", "MY======");
testEncodingWithCasing(base32(), "fo", "MZXQ====");
testEncodingWithCasing(base32(), "foo", "MZXW6===");
testEncodingWithCasing(base32(), "foob", "MZXW6YQ=");
testEncodingWithCasing(base32(), "fooba", "MZXW6YTB");
testEncodingWithCasing(base32(), "foobar", "MZXW6YTBOI======");
}
public void testBase32LenientPadding() {
testDecodes(base32(), "MZXW6", "foo");
testDecodes(base32(), "MZXW6=", "foo");
testDecodes(base32(), "MZXW6==", "foo");
testDecodes(base32(), "MZXW6===", "foo"); // proper padding length
testDecodes(base32(), "MZXW6====", "foo");
testDecodes(base32(), "MZXW6=====", "foo");
}
public void testBase32AlternatePadding() {
BaseEncoding enc = base32().withPadChar('~');
testEncodingWithCasing(enc, "", "");
testEncodingWithCasing(enc, "f", "MY~~~~~~");
testEncodingWithCasing(enc, "fo", "MZXQ~~~~");
testEncodingWithCasing(enc, "foo", "MZXW6~~~");
testEncodingWithCasing(enc, "foob", "MZXW6YQ~");
testEncodingWithCasing(enc, "fooba", "MZXW6YTB");
testEncodingWithCasing(enc, "foobar", "MZXW6YTBOI~~~~~~");
}
public void testBase32InvalidDecodings() {
// These contain bytes not in the decodabet.
assertFailsToDecode(base32(), "\u007f");
assertFailsToDecode(base32(), "Wf2!");
// This sentence just isn't base32() encoded.
assertFailsToDecode(base32(), "let's not talk of love or chains!");
// An 8n+{1,3,6} length string is never legal base32.
assertFailsToDecode(base32(), "A");
assertFailsToDecode(base32(), "ABC");
assertFailsToDecode(base32(), "ABCDEF");
}
public void testBase32UpperCaseIsNoOp() {
assertSame(base32(), base32().upperCase());
}
public void testBase32Hex() {
// The following test vectors are specified in RFC 4648 itself
testEncodingWithCasing(base32Hex(), "", "");
testEncodingWithCasing(base32Hex(), "f", "CO======");
testEncodingWithCasing(base32Hex(), "fo", "CPNG====");
testEncodingWithCasing(base32Hex(), "foo", "CPNMU===");
testEncodingWithCasing(base32Hex(), "foob", "CPNMUOG=");
testEncodingWithCasing(base32Hex(), "fooba", "CPNMUOJ1");
testEncodingWithCasing(base32Hex(), "foobar", "CPNMUOJ1E8======");
}
public void testBase32HexLenientPadding() {
testDecodes(base32Hex(), "CPNMU", "foo");
testDecodes(base32Hex(), "CPNMU=", "foo");
testDecodes(base32Hex(), "CPNMU==", "foo");
testDecodes(base32Hex(), "CPNMU===", "foo"); // proper padding length
testDecodes(base32Hex(), "CPNMU====", "foo");
testDecodes(base32Hex(), "CPNMU=====", "foo");
}
public void testBase32HexInvalidDecodings() {
// These contain bytes not in the decodabet.
assertFailsToDecode(base32Hex(), "\u007f");
assertFailsToDecode(base32Hex(), "Wf2!");
// This sentence just isn't base32 encoded.
assertFailsToDecode(base32Hex(), "let's not talk of love or chains!");
// An 8n+{1,3,6} length string is never legal base32.
assertFailsToDecode(base32Hex(), "A");
assertFailsToDecode(base32Hex(), "ABC");
assertFailsToDecode(base32Hex(), "ABCDEF");
}
public void testBase32HexUpperCaseIsNoOp() {
assertSame(base32Hex(), base32Hex().upperCase());
}
public void testBase16() {
testEncodingWithCasing(base16(), "", "");
testEncodingWithCasing(base16(), "f", "66");
testEncodingWithCasing(base16(), "fo", "666F");
testEncodingWithCasing(base16(), "foo", "666F6F");
testEncodingWithCasing(base16(), "foob", "666F6F62");
testEncodingWithCasing(base16(), "fooba", "666F6F6261");
testEncodingWithCasing(base16(), "foobar", "666F6F626172");
}
public void testBase16UpperCaseIsNoOp() {
assertSame(base16(), base16().upperCase());
}
private static void testEncodingWithCasing(
BaseEncoding encoding, String decoded, String encoded) {
testEncodingWithSeparators(encoding, decoded, encoded);
testEncodingWithSeparators(encoding.upperCase(), decoded, Ascii.toUpperCase(encoded));
testEncodingWithSeparators(encoding.lowerCase(), decoded, Ascii.toLowerCase(encoded));
}
private static void testEncodingWithSeparators(
BaseEncoding encoding, String decoded, String encoded) {
testEncoding(encoding, decoded, encoded);
// test separators work
for (int sepLength = 3; sepLength <= 5; sepLength++) {
for (String separator : ImmutableList.of(",", "\n", ";;", "")) {
testEncoding(encoding.withSeparator(separator, sepLength), decoded,
Joiner.on(separator).join(Splitter.fixedLength(sepLength).split(encoded)));
}
}
}
private static void testEncoding(BaseEncoding encoding, String decoded, String encoded) {
testEncodes(encoding, decoded, encoded);
testDecodes(encoding, encoded, decoded);
}
private static void testEncodes(BaseEncoding encoding, String decoded, String encoded) {
byte[] bytes;
try {
// GWT does not support String.getBytes(Charset)
bytes = decoded.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
assertEquals(encoded, encoding.encode(bytes));
}
private static void testDecodes(BaseEncoding encoding, String encoded, String decoded) {
byte[] bytes;
try {
// GWT does not support String.getBytes(Charset)
bytes = decoded.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError();
}
assertEquals(bytes, encoding.decode(encoded));
}
private static void assertFailsToDecode(BaseEncoding encoding, String cannotDecode) {
try {
encoding.decode(cannotDecode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
// success
}
try {
encoding.decodeChecked(cannotDecode);
fail("Expected DecodingException");
} catch (DecodingException expected) {
// success
}
}
public void testToString() {
assertEquals("BaseEncoding.base64().withPadChar(=)", BaseEncoding.base64().toString());
assertEquals("BaseEncoding.base32Hex().omitPadding()",
BaseEncoding.base32Hex().omitPadding().toString());
assertEquals("BaseEncoding.base32().lowerCase().withPadChar($)",
BaseEncoding.base32().lowerCase().withPadChar('$').toString());
assertEquals("BaseEncoding.base16().withSeparator(\"\n\", 10)",
BaseEncoding.base16().withSeparator("\n", 10).toString());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/io/super/com/google/common/io/BaseEncodingTest.java | Java | asf20 | 11,760 |
/*
* Copyright (C) 2011 The Guava 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.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import junit.framework.TestCase;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* Tests for {@link AtomicLongMap}.
*
* @author mike nonemacher
*/
@GwtCompatible(emulated = true)
public class AtomicLongMapTest extends TestCase {
private static final int ITERATIONS = 100;
private static final int MAX_ADDEND = 100;
private Random random = new Random(301);
public void testCreate_map() {
Map<String, Long> in = ImmutableMap.of("1", 1L, "2", 2L, "3", 3L);
AtomicLongMap<String> map = AtomicLongMap.create(in);
assertFalse(map.isEmpty());
assertSame(3, map.size());
assertTrue(map.containsKey("1"));
assertTrue(map.containsKey("2"));
assertTrue(map.containsKey("3"));
assertEquals(1L, map.get("1"));
assertEquals(2L, map.get("2"));
assertEquals(3L, map.get("3"));
}
public void testIncrementAndGet() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.incrementAndGet(key);
long after = map.get(key);
assertEquals(before + 1, after);
assertEquals(after, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(ITERATIONS, (int) map.get(key));
}
public void testIncrementAndGet_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(1L, map.incrementAndGet(key));
assertEquals(1L, map.get(key));
assertEquals(0L, map.decrementAndGet(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(1L, map.incrementAndGet(key));
assertEquals(1L, map.get(key));
}
public void testGetAndIncrement() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.getAndIncrement(key);
long after = map.get(key);
assertEquals(before + 1, after);
assertEquals(before, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(ITERATIONS, (int) map.get(key));
}
public void testGetAndIncrement_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.getAndIncrement(key));
assertEquals(1L, map.get(key));
assertEquals(1L, map.getAndDecrement(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.getAndIncrement(key));
assertEquals(1L, map.get(key));
}
public void testDecrementAndGet() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.decrementAndGet(key);
long after = map.get(key);
assertEquals(before - 1, after);
assertEquals(after, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(-1 * ITERATIONS, (int) map.get(key));
}
public void testDecrementAndGet_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(-1L, map.decrementAndGet(key));
assertEquals(-1L, map.get(key));
assertEquals(0L, map.incrementAndGet(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(-1L, map.decrementAndGet(key));
assertEquals(-1L, map.get(key));
}
public void testGetAndDecrement() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.getAndDecrement(key);
long after = map.get(key);
assertEquals(before - 1, after);
assertEquals(before, result);
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
assertEquals(-1 * ITERATIONS, (int) map.get(key));
}
public void testGetAndDecrement_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.getAndDecrement(key));
assertEquals(-1L, map.get(key));
assertEquals(-1L, map.getAndIncrement(key));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.getAndDecrement(key));
assertEquals(-1L, map.get(key));
}
public void testAddAndGet() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long addend = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.addAndGet(key, addend);
long after = map.get(key);
assertEquals(before + addend, after);
assertEquals(after, result);
addend = after;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testAddAndGet_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(value, map.addAndGet(key, value));
assertEquals(value, map.get(key));
assertEquals(0L, map.addAndGet(key, -1 * value));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(value, map.addAndGet(key, value));
assertEquals(value, map.get(key));
}
public void testGetAndAdd() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long addend = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.getAndAdd(key, addend);
long after = map.get(key);
assertEquals(before + addend, after);
assertEquals(before, result);
addend = after;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testGetAndAdd_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.getAndAdd(key, value));
assertEquals(value, map.get(key));
assertEquals(value, map.getAndAdd(key, -1 * value));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.getAndAdd(key, value));
assertEquals(value, map.get(key));
}
public void testPut() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.put(key, newValue);
long after = map.get(key);
assertEquals(newValue, after);
assertEquals(before, result);
newValue += newValue;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testPut_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.put(key, value));
assertEquals(value, map.get(key));
assertEquals(value, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.put(key, value));
assertEquals(value, map.get(key));
}
public void testPutAll() {
Map<String, Long> in = ImmutableMap.of("1", 1L, "2", 2L, "3", 3L);
AtomicLongMap<String> map = AtomicLongMap.create();
assertTrue(map.isEmpty());
assertSame(0, map.size());
assertFalse(map.containsKey("1"));
assertFalse(map.containsKey("2"));
assertFalse(map.containsKey("3"));
assertEquals(0L, map.get("1"));
assertEquals(0L, map.get("2"));
assertEquals(0L, map.get("3"));
map.putAll(in);
assertFalse(map.isEmpty());
assertSame(3, map.size());
assertTrue(map.containsKey("1"));
assertTrue(map.containsKey("2"));
assertTrue(map.containsKey("3"));
assertEquals(1L, map.get("1"));
assertEquals(2L, map.get("2"));
assertEquals(3L, map.get("3"));
}
public void testPutIfAbsent() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
long result = map.putIfAbsent(key, newValue);
long after = map.get(key);
assertEquals(before, result);
assertEquals(before == 0 ? newValue : before, after);
map.remove(key);
before = map.get(key);
result = map.putIfAbsent(key, newValue);
after = map.get(key);
assertEquals(0, before);
assertEquals(before, result);
assertEquals(newValue, after);
map.put(key, 0L);
before = map.get(key);
result = map.putIfAbsent(key, newValue);
after = map.get(key);
assertEquals(0, before);
assertEquals(before, result);
assertEquals(newValue, after);
newValue += newValue;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testPutIfAbsent_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.putIfAbsent(key, value));
assertEquals(value, map.get(key));
assertEquals(value, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.putIfAbsent(key, value));
assertEquals(value, map.get(key));
}
public void testReplace() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
long before = map.get(key);
assertFalse(map.replace(key, before + 1, newValue + 1));
assertFalse(map.replace(key, before - 1, newValue - 1));
assertTrue(map.replace(key, before, newValue));
long after = map.get(key);
assertEquals(newValue, after);
newValue += newValue;
}
assertEquals(1, map.size());
assertTrue(!map.isEmpty());
assertTrue(map.containsKey(key));
}
public void testReplace_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
long value = random.nextInt(MAX_ADDEND);
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertTrue(map.replace(key, 0L, value));
assertEquals(value, map.get(key));
assertTrue(map.replace(key, value, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertTrue(map.replace(key, 0L, value));
assertEquals(value, map.get(key));
}
public void testRemove() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0, map.size());
assertTrue(map.isEmpty());
assertEquals(0L, map.remove(key));
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
map.put(key, newValue);
assertTrue(map.containsKey(key));
long before = map.get(key);
long result = map.remove(key);
long after = map.get(key);
assertFalse(map.containsKey(key));
assertEquals(before, result);
assertEquals(0L, after);
newValue += newValue;
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
public void testRemove_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.remove(key));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertEquals(0L, map.remove(key));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
}
public void testRemoveValue() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0, map.size());
assertTrue(map.isEmpty());
assertFalse(map.remove(key, 0L));
long newValue = random.nextInt(MAX_ADDEND);
for (int i = 0; i < ITERATIONS; i++) {
map.put(key, newValue);
assertTrue(map.containsKey(key));
long before = map.get(key);
assertFalse(map.remove(key, newValue + 1));
assertFalse(map.remove(key, newValue - 1));
assertTrue(map.remove(key, newValue));
long after = map.get(key);
assertFalse(map.containsKey(key));
assertEquals(0L, after);
newValue += newValue;
}
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
public void testRemoveValue_zero() {
AtomicLongMap<String> map = AtomicLongMap.create();
String key = "key";
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertFalse(map.remove(key, 0L));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
assertEquals(0L, map.put(key, 0L));
assertEquals(0L, map.get(key));
assertTrue(map.containsKey(key));
assertTrue(map.remove(key, 0L));
assertEquals(0L, map.get(key));
assertFalse(map.containsKey(key));
}
public void testRemoveZeros() {
AtomicLongMap<Object> map = AtomicLongMap.create();
Set<Object> nonZeroKeys = Sets.newHashSet();
for (int i = 0; i < ITERATIONS; i++) {
Object key = new Object();
long value = i % 2;
map.put(key, value);
if (value != 0L) {
nonZeroKeys.add(key);
}
}
assertEquals(ITERATIONS, map.size());
assertTrue(map.asMap().containsValue(0L));
map.removeAllZeros();
assertFalse(map.asMap().containsValue(0L));
assertEquals(ITERATIONS / 2, map.size());
assertEquals(nonZeroKeys, map.asMap().keySet());
}
public void testClear() {
AtomicLongMap<Object> map = AtomicLongMap.create();
for (int i = 0; i < ITERATIONS; i++) {
map.put(new Object(), i);
}
assertEquals(ITERATIONS, map.size());
map.clear();
assertEquals(0, map.size());
assertTrue(map.isEmpty());
}
public void testSum() {
AtomicLongMap<Object> map = AtomicLongMap.create();
long sum = 0;
for (int i = 0; i < ITERATIONS; i++) {
map.put(new Object(), i);
sum += i;
}
assertEquals(ITERATIONS, map.size());
assertEquals(sum, map.sum());
}
public void testEmpty() {
AtomicLongMap<String> map = AtomicLongMap.create();
assertEquals(0L, map.get("a"));
assertEquals(0, map.size());
assertTrue(map.isEmpty());
assertFalse(map.remove("a", 1L));
assertFalse(map.remove("a", 0L));
assertFalse(map.replace("a", 1L, 0L));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/AtomicLongMapTest.java | Java | asf20 | 16,402 |
/*
* Copyright (C) 2011 The Guava 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.common.math;
import com.google.common.annotations.GwtCompatible;
/**
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
class TestPlatform {
static boolean intsCanGoOutOfRange() {
return true;
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/math/super/com/google/common/math/TestPlatform.java | Java | asf20 | 837 |
/*
* Copyright (C) 2011 The Guava 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.common.math;
import static com.google.common.math.MathTesting.ALL_INTEGER_CANDIDATES;
import static com.google.common.math.MathTesting.ALL_ROUNDING_MODES;
import static com.google.common.math.MathTesting.ALL_SAFE_ROUNDING_MODES;
import static com.google.common.math.MathTesting.EXPONENTS;
import static com.google.common.math.MathTesting.NEGATIVE_INTEGER_CANDIDATES;
import static com.google.common.math.MathTesting.NONZERO_INTEGER_CANDIDATES;
import static com.google.common.math.MathTesting.POSITIVE_INTEGER_CANDIDATES;
import static com.google.common.math.TestPlatform.intsCanGoOutOfRange;
import static java.math.BigInteger.valueOf;
import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Tests for {@link IntMath}.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class IntMathTest extends TestCase {
public void testLessThanBranchFree() {
for (int x : ALL_INTEGER_CANDIDATES) {
for (int y : ALL_INTEGER_CANDIDATES) {
if (LongMath.fitsInInt((long) x - y)) {
int expected = (x < y) ? 1 : 0;
int actual = IntMath.lessThanBranchFree(x, y);
assertEquals(expected, actual);
}
}
}
}
public void testLog2ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
IntMath.log2(0, mode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testLog2NegativeAlwaysThrows() {
for (int x : NEGATIVE_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
IntMath.log2(x, mode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
}
// Relies on the correctness of BigIntegrerMath.log2 for all modes except UNNECESSARY.
public void testLog2MatchesBigInteger() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
assertEquals(BigIntegerMath.log2(valueOf(x), mode), IntMath.log2(x, mode));
}
}
}
// Relies on the correctness of isPowerOfTwo(int).
public void testLog2Exact() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
// We only expect an exception if x was not a power of 2.
boolean isPowerOf2 = IntMath.isPowerOfTwo(x);
try {
assertEquals(x, 1 << IntMath.log2(x, UNNECESSARY));
assertTrue(isPowerOf2);
} catch (ArithmeticException e) {
assertFalse(isPowerOf2);
}
}
}
// Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY.
// Relies on the correctness of log10(int, FLOOR) and of pow(int, int).
// Simple test to cover sqrt(0) for all types and all modes.
/* Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY. */
/* Relies on the correctness of sqrt(int, FLOOR). */
public void testDivNonZero() {
for (int p : NONZERO_INTEGER_CANDIDATES) {
for (int q : NONZERO_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
// Skip some tests that fail due to GWT's non-compliant int implementation.
// TODO(cpovirk): does this test fail for only some rounding modes or for all?
if (p == -2147483648 && q == -1 && intsCanGoOutOfRange()) {
continue;
}
int expected =
new BigDecimal(valueOf(p)).divide(new BigDecimal(valueOf(q)), 0, mode).intValue();
assertEquals(p + "/" + q, force32(expected), IntMath.divide(p, q, mode));
}
}
}
}
public void testDivNonZeroExact() {
for (int p : NONZERO_INTEGER_CANDIDATES) {
for (int q : NONZERO_INTEGER_CANDIDATES) {
// Skip some tests that fail due to GWT's non-compliant int implementation.
if (p == -2147483648 && q == -1 && intsCanGoOutOfRange()) {
continue;
}
boolean dividesEvenly = (p % q) == 0;
try {
assertEquals(p + "/" + q, p, IntMath.divide(p, q, UNNECESSARY) * q);
assertTrue(p + "/" + q + " not expected to divide evenly", dividesEvenly);
} catch (ArithmeticException e) {
assertFalse(p + "/" + q + " expected to divide evenly", dividesEvenly);
}
}
}
}
public void testZeroDivIsAlwaysZero() {
for (int q : NONZERO_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
assertEquals(0, IntMath.divide(0, q, mode));
}
}
}
public void testDivByZeroAlwaysFails() {
for (int p : ALL_INTEGER_CANDIDATES) {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
IntMath.divide(p, 0, mode);
fail("Expected ArithmeticException");
} catch (ArithmeticException expected) {}
}
}
}
public void testMod() {
for (int x : ALL_INTEGER_CANDIDATES) {
for (int m : POSITIVE_INTEGER_CANDIDATES) {
assertEquals(valueOf(x).mod(valueOf(m)).intValue(), IntMath.mod(x, m));
}
}
}
public void testModNegativeModulusFails() {
for (int x : POSITIVE_INTEGER_CANDIDATES) {
for (int m : NEGATIVE_INTEGER_CANDIDATES) {
try {
IntMath.mod(x, m);
fail("Expected ArithmeticException");
} catch (ArithmeticException expected) {}
}
}
}
public void testModZeroModulusFails() {
for (int x : ALL_INTEGER_CANDIDATES) {
try {
IntMath.mod(x, 0);
fail("Expected ArithmeticException");
} catch (ArithmeticException expected) {}
}
}
public void testGCD() {
for (int a : POSITIVE_INTEGER_CANDIDATES) {
for (int b : POSITIVE_INTEGER_CANDIDATES) {
assertEquals(valueOf(a).gcd(valueOf(b)), valueOf(IntMath.gcd(a, b)));
}
}
}
public void testGCDZero() {
for (int a : POSITIVE_INTEGER_CANDIDATES) {
assertEquals(a, IntMath.gcd(a, 0));
assertEquals(a, IntMath.gcd(0, a));
}
assertEquals(0, IntMath.gcd(0, 0));
}
public void testGCDNegativePositiveThrows() {
for (int a : NEGATIVE_INTEGER_CANDIDATES) {
try {
IntMath.gcd(a, 3);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
IntMath.gcd(3, a);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testGCDNegativeZeroThrows() {
for (int a : NEGATIVE_INTEGER_CANDIDATES) {
try {
IntMath.gcd(a, 0);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
IntMath.gcd(0, a);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testCheckedAdd() {
for (int a : ALL_INTEGER_CANDIDATES) {
for (int b : ALL_INTEGER_CANDIDATES) {
BigInteger expectedResult = valueOf(a).add(valueOf(b));
boolean expectedSuccess = fitsInInt(expectedResult);
try {
assertEquals(a + b, IntMath.checkedAdd(a, b));
assertTrue(expectedSuccess);
} catch (ArithmeticException e) {
assertFalse(expectedSuccess);
}
}
}
}
public void testCheckedSubtract() {
for (int a : ALL_INTEGER_CANDIDATES) {
for (int b : ALL_INTEGER_CANDIDATES) {
BigInteger expectedResult = valueOf(a).subtract(valueOf(b));
boolean expectedSuccess = fitsInInt(expectedResult);
try {
assertEquals(a - b, IntMath.checkedSubtract(a, b));
assertTrue(expectedSuccess);
} catch (ArithmeticException e) {
assertFalse(expectedSuccess);
}
}
}
}
public void testCheckedMultiply() {
for (int a : ALL_INTEGER_CANDIDATES) {
for (int b : ALL_INTEGER_CANDIDATES) {
BigInteger expectedResult = valueOf(a).multiply(valueOf(b));
boolean expectedSuccess = fitsInInt(expectedResult);
try {
assertEquals(a * b, IntMath.checkedMultiply(a, b));
assertTrue(expectedSuccess);
} catch (ArithmeticException e) {
assertFalse(expectedSuccess);
}
}
}
}
public void testCheckedPow() {
for (int b : ALL_INTEGER_CANDIDATES) {
for (int k : EXPONENTS) {
BigInteger expectedResult = valueOf(b).pow(k);
boolean expectedSuccess = fitsInInt(expectedResult);
try {
assertEquals(b + "^" + k, force32(expectedResult.intValue()), IntMath.checkedPow(b, k));
assertTrue(b + "^" + k + " should have succeeded", expectedSuccess);
} catch (ArithmeticException e) {
assertFalse(b + "^" + k + " should have failed", expectedSuccess);
}
}
}
}
// Depends on the correctness of BigIntegerMath.factorial.
public void testFactorial() {
for (int n = 0; n <= 50; n++) {
BigInteger expectedBig = BigIntegerMath.factorial(n);
int expectedInt = fitsInInt(expectedBig) ? expectedBig.intValue() : Integer.MAX_VALUE;
assertEquals(expectedInt, IntMath.factorial(n));
}
}
public void testFactorialNegative() {
for (int n : NEGATIVE_INTEGER_CANDIDATES) {
try {
IntMath.factorial(n);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
// Depends on the correctness of BigIntegerMath.binomial.
/**
* Helper method that asserts the arithmetic mean of x and y is equal
* to the expectedMean.
*/
private static void assertMean(int expectedMean, int x, int y) {
assertEquals("The expectedMean should be the same as computeMeanSafely",
expectedMean, computeMeanSafely(x, y));
assertMean(x, y);
}
/**
* Helper method that asserts the arithmetic mean of x and y is equal
* to the result of computeMeanSafely.
*/
private static void assertMean(int x, int y) {
int expectedMean = computeMeanSafely(x, y);
assertEquals(expectedMean, IntMath.mean(x, y));
assertEquals("The mean of x and y should equal the mean of y and x",
expectedMean, IntMath.mean(y, x));
}
/**
* Computes the mean in a way that is obvious and resilient to
* overflow by using BigInteger arithmetic.
*/
private static int computeMeanSafely(int x, int y) {
BigInteger bigX = BigInteger.valueOf(x);
BigInteger bigY = BigInteger.valueOf(y);
BigDecimal bigMean = new BigDecimal(bigX.add(bigY))
.divide(BigDecimal.valueOf(2), BigDecimal.ROUND_FLOOR);
// parseInt blows up on overflow as opposed to intValue() which does not.
return Integer.parseInt(bigMean.toString());
}
private static boolean fitsInInt(BigInteger big) {
return big.bitLength() <= 31;
}
private static int force32(int value) {
// GWT doesn't consistently overflow values to make them 32-bit, so we need to force it.
return value & 0xffffffff;
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/math/super/com/google/common/math/IntMathTest.java | Java | asf20 | 11,762 |
/*
* Copyright (C) 2011 The Guava 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.common.math;
import static com.google.common.math.MathTesting.ALL_LONG_CANDIDATES;
import static com.google.common.math.MathTesting.ALL_ROUNDING_MODES;
import static com.google.common.math.MathTesting.ALL_SAFE_ROUNDING_MODES;
import static com.google.common.math.MathTesting.NEGATIVE_INTEGER_CANDIDATES;
import static com.google.common.math.MathTesting.NEGATIVE_LONG_CANDIDATES;
import static com.google.common.math.MathTesting.POSITIVE_LONG_CANDIDATES;
import static java.math.BigInteger.valueOf;
import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Tests for LongMath.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class LongMathTest extends TestCase {
public void testLessThanBranchFree() {
for (long x : ALL_LONG_CANDIDATES) {
for (long y : ALL_LONG_CANDIDATES) {
BigInteger difference = BigInteger.valueOf(x).subtract(BigInteger.valueOf(y));
if (fitsInLong(difference)) {
int expected = (x < y) ? 1 : 0;
int actual = LongMath.lessThanBranchFree(x, y);
assertEquals(expected, actual);
}
}
}
}
// Throws an ArithmeticException if "the simple implementation" of binomial coefficients overflows
public void testLog2ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
LongMath.log2(0L, mode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testLog2NegativeAlwaysThrows() {
for (long x : NEGATIVE_LONG_CANDIDATES) {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
LongMath.log2(x, mode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
}
/* Relies on the correctness of BigIntegerMath.log2 for all modes except UNNECESSARY. */
public void testLog2MatchesBigInteger() {
for (long x : POSITIVE_LONG_CANDIDATES) {
for (RoundingMode mode : ALL_SAFE_ROUNDING_MODES) {
// The BigInteger implementation is tested separately, use it as the reference.
assertEquals(BigIntegerMath.log2(valueOf(x), mode), LongMath.log2(x, mode));
}
}
}
/* Relies on the correctness of isPowerOfTwo(long). */
public void testLog2Exact() {
for (long x : POSITIVE_LONG_CANDIDATES) {
// We only expect an exception if x was not a power of 2.
boolean isPowerOf2 = LongMath.isPowerOfTwo(x);
try {
assertEquals(x, 1L << LongMath.log2(x, UNNECESSARY));
assertTrue(isPowerOf2);
} catch (ArithmeticException e) {
assertFalse(isPowerOf2);
}
}
}
// Relies on the correctness of BigIntegerMath.log10 for all modes except UNNECESSARY.
// Relies on the correctness of log10(long, FLOOR) and of pow(long, int).
// Relies on the correctness of BigIntegerMath.sqrt for all modes except UNNECESSARY.
/* Relies on the correctness of sqrt(long, FLOOR). */
public void testGCDExhaustive() {
for (long a : POSITIVE_LONG_CANDIDATES) {
for (long b : POSITIVE_LONG_CANDIDATES) {
assertEquals(valueOf(a).gcd(valueOf(b)), valueOf(LongMath.gcd(a, b)));
}
}
}
// Depends on the correctness of BigIntegerMath.factorial.
// Depends on the correctness of BigIntegerMath.binomial.
public void testBinomial() {
for (int n = 0; n <= 70; n++) {
for (int k = 0; k <= n; k++) {
BigInteger expectedBig = BigIntegerMath.binomial(n, k);
long expectedLong = fitsInLong(expectedBig) ? expectedBig.longValue() : Long.MAX_VALUE;
assertEquals(expectedLong, LongMath.binomial(n, k));
}
}
}
public void testBinomialOutside() {
for (int n = 0; n <= 50; n++) {
try {
LongMath.binomial(n, -1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
LongMath.binomial(n, n + 1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testBinomialNegative() {
for (int n : NEGATIVE_INTEGER_CANDIDATES) {
try {
LongMath.binomial(n, 0);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testSqrtOfLongIsAtMostFloorSqrtMaxLong() {
long sqrtMaxLong = (long) Math.sqrt(Long.MAX_VALUE);
assertTrue(sqrtMaxLong <= LongMath.FLOOR_SQRT_MAX_LONG);
}
/**
* Helper method that asserts the arithmetic mean of x and y is equal
* to the expectedMean.
*/
private static void assertMean(long expectedMean, long x, long y) {
assertEquals("The expectedMean should be the same as computeMeanSafely",
expectedMean, computeMeanSafely(x, y));
assertMean(x, y);
}
/**
* Helper method that asserts the arithmetic mean of x and y is equal
*to the result of computeMeanSafely.
*/
private static void assertMean(long x, long y) {
long expectedMean = computeMeanSafely(x, y);
assertEquals(expectedMean, LongMath.mean(x, y));
assertEquals("The mean of x and y should equal the mean of y and x",
expectedMean, LongMath.mean(y, x));
}
/**
* Computes the mean in a way that is obvious and resilient to
* overflow by using BigInteger arithmetic.
*/
private static long computeMeanSafely(long x, long y) {
BigInteger bigX = BigInteger.valueOf(x);
BigInteger bigY = BigInteger.valueOf(y);
BigDecimal bigMean = new BigDecimal(bigX.add(bigY))
.divide(BigDecimal.valueOf(2), BigDecimal.ROUND_FLOOR);
// parseInt blows up on overflow as opposed to intValue() which does not.
return Long.parseLong(bigMean.toString());
}
private static boolean fitsInLong(BigInteger big) {
return big.bitLength() <= 63;
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/math/super/com/google/common/math/LongMathTest.java | Java | asf20 | 6,639 |
/*
* Copyright (C) 2011 The Guava 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.common.math;
import static com.google.common.math.MathTesting.ALL_BIGINTEGER_CANDIDATES;
import static com.google.common.math.MathTesting.ALL_ROUNDING_MODES;
import static com.google.common.math.MathTesting.POSITIVE_BIGINTEGER_CANDIDATES;
import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.DOWN;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_DOWN;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import static java.math.RoundingMode.UNNECESSARY;
import static java.math.RoundingMode.UP;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Tests for BigIntegerMath.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class BigIntegerMathTest extends TestCase {
public void testIsPowerOfTwo() {
for (BigInteger x : ALL_BIGINTEGER_CANDIDATES) {
// Checks for a single bit set.
boolean expected = x.signum() > 0 & x.and(x.subtract(ONE)).equals(ZERO);
assertEquals(expected, BigIntegerMath.isPowerOfTwo(x));
}
}
public void testLog2ZeroAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
BigIntegerMath.log2(ZERO, mode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testLog2NegativeAlwaysThrows() {
for (RoundingMode mode : ALL_ROUNDING_MODES) {
try {
BigIntegerMath.log2(BigInteger.valueOf(-1), mode);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
public void testLog2Floor() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
for (RoundingMode mode : asList(FLOOR, DOWN)) {
int result = BigIntegerMath.log2(x, mode);
assertTrue(ZERO.setBit(result).compareTo(x) <= 0);
assertTrue(ZERO.setBit(result + 1).compareTo(x) > 0);
}
}
}
public void testLog2Ceiling() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
for (RoundingMode mode : asList(CEILING, UP)) {
int result = BigIntegerMath.log2(x, mode);
assertTrue(ZERO.setBit(result).compareTo(x) >= 0);
assertTrue(result == 0 || ZERO.setBit(result - 1).compareTo(x) < 0);
}
}
}
// Relies on the correctness of isPowerOfTwo(BigInteger).
public void testLog2Exact() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
// We only expect an exception if x was not a power of 2.
boolean isPowerOf2 = BigIntegerMath.isPowerOfTwo(x);
try {
assertEquals(x, ZERO.setBit(BigIntegerMath.log2(x, UNNECESSARY)));
assertTrue(isPowerOf2);
} catch (ArithmeticException e) {
assertFalse(isPowerOf2);
}
}
}
public void testLog2HalfUp() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
int result = BigIntegerMath.log2(x, HALF_UP);
BigInteger x2 = x.pow(2);
// x^2 < 2^(2 * result + 1), or else we would have rounded up
assertTrue(ZERO.setBit(2 * result + 1).compareTo(x2) > 0);
// x^2 >= 2^(2 * result - 1), or else we would have rounded down
assertTrue(result == 0 || ZERO.setBit(2 * result - 1).compareTo(x2) <= 0);
}
}
public void testLog2HalfDown() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
int result = BigIntegerMath.log2(x, HALF_DOWN);
BigInteger x2 = x.pow(2);
// x^2 <= 2^(2 * result + 1), or else we would have rounded up
assertTrue(ZERO.setBit(2 * result + 1).compareTo(x2) >= 0);
// x^2 > 2^(2 * result - 1), or else we would have rounded down
assertTrue(result == 0 || ZERO.setBit(2 * result - 1).compareTo(x2) < 0);
}
}
// Relies on the correctness of log2(BigInteger, {HALF_UP,HALF_DOWN}).
public void testLog2HalfEven() {
for (BigInteger x : POSITIVE_BIGINTEGER_CANDIDATES) {
int halfEven = BigIntegerMath.log2(x, HALF_EVEN);
// Now figure out what rounding mode we should behave like (it depends if FLOOR was
// odd/even).
boolean floorWasEven = (BigIntegerMath.log2(x, FLOOR) & 1) == 0;
assertEquals(BigIntegerMath.log2(x, floorWasEven ? HALF_DOWN : HALF_UP), halfEven);
}
}
// Relies on the correctness of log10(BigInteger, FLOOR).
// Relies on the correctness of log10(BigInteger, {HALF_UP,HALF_DOWN}).
// Relies on the correctness of sqrt(BigInteger, FLOOR).
// Relies on the correctness of sqrt(BigInteger, {HALF_UP,HALF_DOWN}).
public void testFactorial() {
BigInteger expected = BigInteger.ONE;
for (int i = 1; i <= 200; i++) {
expected = expected.multiply(BigInteger.valueOf(i));
assertEquals(expected, BigIntegerMath.factorial(i));
}
}
public void testFactorial0() {
assertEquals(BigInteger.ONE, BigIntegerMath.factorial(0));
}
public void testFactorialNegative() {
try {
BigIntegerMath.factorial(-1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
public void testBinomialSmall() {
runBinomialTest(0, 30);
}
// Depends on the correctness of BigIntegerMath.factorial
private static void runBinomialTest(int firstN, int lastN) {
for (int n = firstN; n <= lastN; n++) {
for (int k = 0; k <= n; k++) {
BigInteger expected = BigIntegerMath
.factorial(n)
.divide(BigIntegerMath.factorial(k))
.divide(BigIntegerMath.factorial(n - k));
assertEquals(expected, BigIntegerMath.binomial(n, k));
}
}
}
public void testBinomialOutside() {
for (int n = 0; n <= 50; n++) {
try {
BigIntegerMath.binomial(n, -1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
try {
BigIntegerMath.binomial(n, n + 1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/math/super/com/google/common/math/BigIntegerMathTest.java | Java | asf20 | 6,825 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link Chars}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class CharsTest extends TestCase {
private static final char[] EMPTY = {};
private static final char[] ARRAY1 = {(char) 1};
private static final char[] ARRAY234
= {(char) 2, (char) 3, (char) 4};
private static final char LEAST = Character.MIN_VALUE;
private static final char GREATEST = Character.MAX_VALUE;
private static final char[] VALUES =
{LEAST, 'a', '\u00e0', '\udcaa', GREATEST};
public void testHashCode() {
for (char value : VALUES) {
assertEquals(((Character) value).hashCode(), Chars.hashCode(value));
}
}
public void testCheckedCast() {
for (char value : VALUES) {
assertEquals(value, Chars.checkedCast((long) value));
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
assertCastFails(Long.MAX_VALUE);
assertCastFails(Long.MIN_VALUE);
}
public void testSaturatedCast() {
for (char value : VALUES) {
assertEquals(value, Chars.saturatedCast((long) value));
}
assertEquals(GREATEST, Chars.saturatedCast(GREATEST + 1L));
assertEquals(LEAST, Chars.saturatedCast(LEAST - 1L));
assertEquals(GREATEST, Chars.saturatedCast(Long.MAX_VALUE));
assertEquals(LEAST, Chars.saturatedCast(Long.MIN_VALUE));
}
private void assertCastFails(long value) {
try {
Chars.checkedCast(value);
fail("Cast to char should have failed: " + value);
} catch (IllegalArgumentException ex) {
assertTrue(value + " not found in exception text: " + ex.getMessage(),
ex.getMessage().contains(String.valueOf(value)));
}
}
public void testCompare() {
for (char x : VALUES) {
for (char y : VALUES) {
// note: spec requires only that the sign is the same
assertEquals(x + ", " + y,
Character.valueOf(x).compareTo(y),
Chars.compare(x, y));
}
}
}
public void testContains() {
assertFalse(Chars.contains(EMPTY, (char) 1));
assertFalse(Chars.contains(ARRAY1, (char) 2));
assertFalse(Chars.contains(ARRAY234, (char) 1));
assertTrue(Chars.contains(new char[] {(char) -1}, (char) -1));
assertTrue(Chars.contains(ARRAY234, (char) 2));
assertTrue(Chars.contains(ARRAY234, (char) 3));
assertTrue(Chars.contains(ARRAY234, (char) 4));
}
public void testIndexOf() {
assertEquals(-1, Chars.indexOf(EMPTY, (char) 1));
assertEquals(-1, Chars.indexOf(ARRAY1, (char) 2));
assertEquals(-1, Chars.indexOf(ARRAY234, (char) 1));
assertEquals(0, Chars.indexOf(
new char[] {(char) -1}, (char) -1));
assertEquals(0, Chars.indexOf(ARRAY234, (char) 2));
assertEquals(1, Chars.indexOf(ARRAY234, (char) 3));
assertEquals(2, Chars.indexOf(ARRAY234, (char) 4));
assertEquals(1, Chars.indexOf(
new char[] { (char) 2, (char) 3, (char) 2, (char) 3 },
(char) 3));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Chars.indexOf(EMPTY, EMPTY));
assertEquals(0, Chars.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Chars.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Chars.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Chars.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Chars.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Chars.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Chars.indexOf(
ARRAY234, new char[] { (char) 2, (char) 3 }));
assertEquals(1, Chars.indexOf(
ARRAY234, new char[] { (char) 3, (char) 4 }));
assertEquals(1, Chars.indexOf(ARRAY234, new char[] { (char) 3 }));
assertEquals(2, Chars.indexOf(ARRAY234, new char[] { (char) 4 }));
assertEquals(1, Chars.indexOf(new char[] { (char) 2, (char) 3,
(char) 3, (char) 3, (char) 3 },
new char[] { (char) 3 }
));
assertEquals(2, Chars.indexOf(
new char[] { (char) 2, (char) 3, (char) 2,
(char) 3, (char) 4, (char) 2, (char) 3},
new char[] { (char) 2, (char) 3, (char) 4}
));
assertEquals(1, Chars.indexOf(
new char[] { (char) 2, (char) 2, (char) 3,
(char) 4, (char) 2, (char) 3, (char) 4},
new char[] { (char) 2, (char) 3, (char) 4}
));
assertEquals(-1, Chars.indexOf(
new char[] { (char) 4, (char) 3, (char) 2},
new char[] { (char) 2, (char) 3, (char) 4}
));
}
public void testLastIndexOf() {
assertEquals(-1, Chars.lastIndexOf(EMPTY, (char) 1));
assertEquals(-1, Chars.lastIndexOf(ARRAY1, (char) 2));
assertEquals(-1, Chars.lastIndexOf(ARRAY234, (char) 1));
assertEquals(0, Chars.lastIndexOf(
new char[] {(char) -1}, (char) -1));
assertEquals(0, Chars.lastIndexOf(ARRAY234, (char) 2));
assertEquals(1, Chars.lastIndexOf(ARRAY234, (char) 3));
assertEquals(2, Chars.lastIndexOf(ARRAY234, (char) 4));
assertEquals(3, Chars.lastIndexOf(
new char[] { (char) 2, (char) 3, (char) 2, (char) 3 },
(char) 3));
}
public void testMax_noArgs() {
try {
Chars.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, Chars.max(LEAST));
assertEquals(GREATEST, Chars.max(GREATEST));
assertEquals((char) 9, Chars.max(
(char) 8, (char) 6, (char) 7,
(char) 5, (char) 3, (char) 0, (char) 9));
}
public void testMin_noArgs() {
try {
Chars.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, Chars.min(LEAST));
assertEquals(GREATEST, Chars.min(GREATEST));
assertEquals((char) 0, Chars.min(
(char) 8, (char) 6, (char) 7,
(char) 5, (char) 3, (char) 0, (char) 9));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Chars.concat()));
assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Chars.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Chars.concat(ARRAY1)));
assertNotSame(ARRAY1, Chars.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Chars.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new char[] {(char) 1, (char) 1, (char) 1},
Chars.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new char[] {(char) 1, (char) 2, (char) 3, (char) 4},
Chars.concat(ARRAY1, ARRAY234)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Chars.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Chars.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new char[] {(char) 1, (char) 0, (char) 0},
Chars.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Chars.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Chars.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testJoin() {
assertEquals("", Chars.join(",", EMPTY));
assertEquals("1", Chars.join(",", '1'));
assertEquals("1,2", Chars.join(",", '1', '2'));
assertEquals("123", Chars.join("", '1', '2', '3'));
}
public void testLexicographicalComparator() {
List<char[]> ordered = Arrays.asList(
new char[] {},
new char[] {LEAST},
new char[] {LEAST, LEAST},
new char[] {LEAST, (char) 1},
new char[] {(char) 1},
new char[] {(char) 1, LEAST},
new char[] {GREATEST, GREATEST - (char) 1},
new char[] {GREATEST, GREATEST},
new char[] {GREATEST, GREATEST, GREATEST});
Comparator<char[]> comparator = Chars.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Character> none = Arrays.<Character>asList();
assertTrue(Arrays.equals(EMPTY, Chars.toArray(none)));
List<Character> one = Arrays.asList((char) 1);
assertTrue(Arrays.equals(ARRAY1, Chars.toArray(one)));
char[] array = {(char) 0, (char) 1, 'A'};
List<Character> three = Arrays.asList((char) 0, (char) 1, 'A');
assertTrue(Arrays.equals(array, Chars.toArray(three)));
assertTrue(Arrays.equals(array, Chars.toArray(Chars.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Character> list = Chars.asList(VALUES).subList(0, i);
Collection<Character> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
char[] arr = Chars.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Character> list = Arrays.asList((char) 0, (char) 1, null);
try {
Chars.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testAsList_isAView() {
char[] array = {(char) 0, (char) 1};
List<Character> list = Chars.asList(array);
list.set(0, (char) 2);
assertTrue(Arrays.equals(new char[] {(char) 2, (char) 1}, array));
array[1] = (char) 3;
assertEquals(Arrays.asList((char) 2, (char) 3), list);
}
public void testAsList_toArray_roundTrip() {
char[] array = { (char) 0, (char) 1, (char) 2 };
List<Character> list = Chars.asList(array);
char[] newArray = Chars.toArray(list);
// Make sure it returned a copy
list.set(0, (char) 4);
assertTrue(Arrays.equals(
new char[] { (char) 0, (char) 1, (char) 2 }, newArray));
newArray[1] = (char) 5;
assertEquals((char) 1, (char) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
char[] array = { (char) 0, (char) 1, (char) 2, (char) 3 };
List<Character> list = Chars.asList(array);
assertTrue(Arrays.equals(new char[] { (char) 1, (char) 2 },
Chars.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new char[] {},
Chars.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Chars.asList(EMPTY));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/CharsTest.java | Java | asf20 | 11,521 |
/*
* Copyright (C) 2011 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableSet;
import junit.framework.TestCase;
import java.math.BigInteger;
/**
* Tests for {@code UnsignedLong}.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class UnsignedLongTest extends TestCase {
private static final ImmutableSet<Long> TEST_LONGS;
private static final ImmutableSet<BigInteger> TEST_BIG_INTEGERS;
static {
ImmutableSet.Builder<Long> testLongsBuilder = ImmutableSet.builder();
ImmutableSet.Builder<BigInteger> testBigIntegersBuilder = ImmutableSet.builder();
for (long i = -3; i <= 3; i++) {
testLongsBuilder
.add(i)
.add(Long.MAX_VALUE + i)
.add(Long.MIN_VALUE + i)
.add(Integer.MIN_VALUE + i)
.add(Integer.MAX_VALUE + i);
BigInteger bigI = BigInteger.valueOf(i);
testBigIntegersBuilder
.add(bigI)
.add(BigInteger.valueOf(Long.MAX_VALUE).add(bigI))
.add(BigInteger.valueOf(Long.MIN_VALUE).add(bigI))
.add(BigInteger.valueOf(Integer.MAX_VALUE).add(bigI))
.add(BigInteger.valueOf(Integer.MIN_VALUE).add(bigI))
.add(BigInteger.ONE.shiftLeft(63).add(bigI))
.add(BigInteger.ONE.shiftLeft(64).add(bigI));
}
TEST_LONGS = testLongsBuilder.build();
TEST_BIG_INTEGERS = testBigIntegersBuilder.build();
}
public void testAsUnsignedAndLongValueAreInverses() {
for (long value : TEST_LONGS) {
assertEquals(
UnsignedLongs.toString(value), value, UnsignedLong.fromLongBits(value).longValue());
}
}
public void testAsUnsignedBigIntegerValue() {
for (long value : TEST_LONGS) {
BigInteger expected = (value >= 0)
? BigInteger.valueOf(value)
: BigInteger.valueOf(value).add(BigInteger.ZERO.setBit(64));
assertEquals(UnsignedLongs.toString(value), expected,
UnsignedLong.fromLongBits(value).bigIntegerValue());
}
}
public void testValueOfLong() {
for (long value : TEST_LONGS) {
boolean expectSuccess = value >= 0;
try {
assertEquals(value, UnsignedLong.valueOf(value).longValue());
assertTrue(expectSuccess);
} catch (IllegalArgumentException e) {
assertFalse(expectSuccess);
}
}
}
public void testValueOfBigInteger() {
BigInteger min = BigInteger.ZERO;
BigInteger max = UnsignedLong.MAX_VALUE.bigIntegerValue();
for (BigInteger big : TEST_BIG_INTEGERS) {
boolean expectSuccess =
big.compareTo(min) >= 0 && big.compareTo(max) <= 0;
try {
assertEquals(big, UnsignedLong.valueOf(big).bigIntegerValue());
assertTrue(expectSuccess);
} catch (IllegalArgumentException e) {
assertFalse(expectSuccess);
}
}
}
public void testToString() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
assertEquals(unsignedValue.bigIntegerValue().toString(), unsignedValue.toString());
}
}
public void testToStringRadixQuick() {
int[] radices = {2, 3, 5, 7, 10, 12, 16, 21, 31, 36};
for (int radix : radices) {
for (long l : TEST_LONGS) {
UnsignedLong value = UnsignedLong.fromLongBits(l);
assertEquals(value.bigIntegerValue().toString(radix), value.toString(radix));
}
}
}
public void testFloatValue() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
assertEquals(unsignedValue.bigIntegerValue().floatValue(), unsignedValue.floatValue());
}
}
public void testDoubleValue() {
for (long value : TEST_LONGS) {
UnsignedLong unsignedValue = UnsignedLong.fromLongBits(value);
assertEquals(unsignedValue.bigIntegerValue().doubleValue(), unsignedValue.doubleValue());
}
}
public void testPlus() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned
.bigIntegerValue()
.add(bUnsigned.bigIntegerValue())
.longValue();
UnsignedLong unsignedSum = aUnsigned.plus(bUnsigned);
assertEquals(expected, unsignedSum.longValue());
}
}
}
public void testMinus() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned
.bigIntegerValue()
.subtract(bUnsigned.bigIntegerValue())
.longValue();
UnsignedLong unsignedSub = aUnsigned.minus(bUnsigned);
assertEquals(expected, unsignedSub.longValue());
}
}
}
public void testTimes() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned
.bigIntegerValue()
.multiply(bUnsigned.bigIntegerValue())
.longValue();
UnsignedLong unsignedMul = aUnsigned.times(bUnsigned);
assertEquals(expected, unsignedMul.longValue());
}
}
}
public void testDividedBy() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
if (b != 0) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned
.bigIntegerValue()
.divide(bUnsigned.bigIntegerValue())
.longValue();
UnsignedLong unsignedDiv = aUnsigned.dividedBy(bUnsigned);
assertEquals(expected, unsignedDiv.longValue());
}
}
}
}
@SuppressWarnings("ReturnValueIgnored")
public void testDivideByZeroThrows() {
for (long a : TEST_LONGS) {
try {
UnsignedLong.fromLongBits(a).dividedBy(UnsignedLong.ZERO);
fail("Expected ArithmeticException");
} catch (ArithmeticException expected) {}
}
}
public void testMod() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
if (b != 0) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
long expected = aUnsigned
.bigIntegerValue()
.remainder(bUnsigned.bigIntegerValue())
.longValue();
UnsignedLong unsignedRem = aUnsigned.mod(bUnsigned);
assertEquals(expected, unsignedRem.longValue());
}
}
}
}
@SuppressWarnings("ReturnValueIgnored")
public void testModByZero() {
for (long a : TEST_LONGS) {
try {
UnsignedLong.fromLongBits(a).mod(UnsignedLong.ZERO);
fail("Expected ArithmeticException");
} catch (ArithmeticException expected) {}
}
}
public void testCompare() {
for (long a : TEST_LONGS) {
for (long b : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
UnsignedLong bUnsigned = UnsignedLong.fromLongBits(b);
assertEquals(aUnsigned.bigIntegerValue().compareTo(bUnsigned.bigIntegerValue()),
aUnsigned.compareTo(bUnsigned));
}
}
}
public void testIntValue() {
for (long a : TEST_LONGS) {
UnsignedLong aUnsigned = UnsignedLong.fromLongBits(a);
int intValue = aUnsigned.bigIntegerValue().intValue();
assertEquals(intValue, aUnsigned.intValue());
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/UnsignedLongTest.java | Java | asf20 | 8,317 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Floats#asList(float[])})}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class FloatArrayAsListTest extends TestCase {
private static List<Float> asList(Float[] values) {
float[] temp = new float[values.length];
for (int i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Floats.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class FloatsAsListGenerator extends TestFloatListGenerator {
@Override protected List<Float> create(Float[] elements) {
return asList(elements);
}
}
public static final class FloatsAsListHeadSubListGenerator extends TestFloatListGenerator {
@Override protected List<Float> create(Float[] elements) {
Float[] suffix = {Float.MIN_VALUE, Float.MAX_VALUE};
Float[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class FloatsAsListTailSubListGenerator extends TestFloatListGenerator {
@Override protected List<Float> create(Float[] elements) {
Float[] prefix = {(float) 86, (float) 99};
Float[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class FloatsAsListMiddleSubListGenerator extends TestFloatListGenerator {
@Override protected List<Float> create(Float[] elements) {
Float[] prefix = {Float.MIN_VALUE, Float.MAX_VALUE};
Float[] suffix = {(float) 86, (float) 99};
Float[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Float[] concat(Float[] left, Float[] right) {
Float[] result = new Float[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestFloatListGenerator
implements TestListGenerator<Float> {
@Override
public SampleElements<Float> samples() {
return new SampleFloats();
}
@Override
public List<Float> create(Object... elements) {
Float[] array = new Float[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Float) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Float> create(Float[] elements);
@Override
public Float[] createArray(int length) {
return new Float[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Float> order(List<Float> insertionOrder) {
return insertionOrder;
}
}
public static class SampleFloats extends SampleElements<Float> {
public SampleFloats() {
super((float) 0, (float) 1, (float) 2, (float) 3, (float) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/FloatArrayAsListTest.java | Java | asf20 | 4,136 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static java.lang.Float.NaN;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link Floats}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class FloatsTest extends TestCase {
private static final float[] EMPTY = {};
private static final float[] ARRAY1 = {(float) 1};
private static final float[] ARRAY234
= {(float) 2, (float) 3, (float) 4};
private static final float LEAST = Float.NEGATIVE_INFINITY;
private static final float GREATEST = Float.POSITIVE_INFINITY;
private static final float[] NUMBERS = new float[] {
LEAST, -Float.MAX_VALUE, -1f, -0f, 0f, 1f, Float.MAX_VALUE, GREATEST,
Float.MIN_NORMAL, -Float.MIN_NORMAL, Float.MIN_VALUE, -Float.MIN_VALUE,
Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE
};
private static final float[] VALUES
= Floats.concat(NUMBERS, new float[] {NaN});
public void testHashCode() {
for (float value : VALUES) {
assertEquals(((Float) value).hashCode(), Floats.hashCode(value));
}
}
public void testIsFinite() {
for (float value : NUMBERS) {
assertEquals(!(Float.isInfinite(value) || Float.isNaN(value)), Floats.isFinite(value));
}
}
public void testCompare() {
for (float x : VALUES) {
for (float y : VALUES) {
// note: spec requires only that the sign is the same
assertEquals(x + ", " + y,
Float.valueOf(x).compareTo(y),
Floats.compare(x, y));
}
}
}
public void testContains() {
assertFalse(Floats.contains(EMPTY, (float) 1));
assertFalse(Floats.contains(ARRAY1, (float) 2));
assertFalse(Floats.contains(ARRAY234, (float) 1));
assertTrue(Floats.contains(new float[] {(float) -1}, (float) -1));
assertTrue(Floats.contains(ARRAY234, (float) 2));
assertTrue(Floats.contains(ARRAY234, (float) 3));
assertTrue(Floats.contains(ARRAY234, (float) 4));
for (float value : NUMBERS) {
assertTrue("" + value, Floats.contains(new float[] {5f, value}, value));
}
assertFalse(Floats.contains(new float[] {5f, NaN}, NaN));
}
public void testIndexOf() {
assertEquals(-1, Floats.indexOf(EMPTY, (float) 1));
assertEquals(-1, Floats.indexOf(ARRAY1, (float) 2));
assertEquals(-1, Floats.indexOf(ARRAY234, (float) 1));
assertEquals(0, Floats.indexOf(
new float[] {(float) -1}, (float) -1));
assertEquals(0, Floats.indexOf(ARRAY234, (float) 2));
assertEquals(1, Floats.indexOf(ARRAY234, (float) 3));
assertEquals(2, Floats.indexOf(ARRAY234, (float) 4));
assertEquals(1, Floats.indexOf(
new float[] { (float) 2, (float) 3, (float) 2, (float) 3 },
(float) 3));
for (float value : NUMBERS) {
assertEquals("" + value, 1,
Floats.indexOf(new float[] {5f, value}, value));
}
assertEquals(-1, Floats.indexOf(new float[] {5f, NaN}, NaN));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Floats.indexOf(EMPTY, EMPTY));
assertEquals(0, Floats.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Floats.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Floats.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Floats.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Floats.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Floats.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Floats.indexOf(
ARRAY234, new float[] { (float) 2, (float) 3 }));
assertEquals(1, Floats.indexOf(
ARRAY234, new float[] { (float) 3, (float) 4 }));
assertEquals(1, Floats.indexOf(ARRAY234, new float[] { (float) 3 }));
assertEquals(2, Floats.indexOf(ARRAY234, new float[] { (float) 4 }));
assertEquals(1, Floats.indexOf(new float[] { (float) 2, (float) 3,
(float) 3, (float) 3, (float) 3 },
new float[] { (float) 3 }
));
assertEquals(2, Floats.indexOf(
new float[] { (float) 2, (float) 3, (float) 2,
(float) 3, (float) 4, (float) 2, (float) 3},
new float[] { (float) 2, (float) 3, (float) 4}
));
assertEquals(1, Floats.indexOf(
new float[] { (float) 2, (float) 2, (float) 3,
(float) 4, (float) 2, (float) 3, (float) 4},
new float[] { (float) 2, (float) 3, (float) 4}
));
assertEquals(-1, Floats.indexOf(
new float[] { (float) 4, (float) 3, (float) 2},
new float[] { (float) 2, (float) 3, (float) 4}
));
for (float value : NUMBERS) {
assertEquals("" + value, 1, Floats.indexOf(
new float[] {5f, value, value, 5f}, new float[] {value, value}));
}
assertEquals(-1, Floats.indexOf(
new float[] {5f, NaN, NaN, 5f}, new float[] {NaN, NaN}));
}
public void testLastIndexOf() {
assertEquals(-1, Floats.lastIndexOf(EMPTY, (float) 1));
assertEquals(-1, Floats.lastIndexOf(ARRAY1, (float) 2));
assertEquals(-1, Floats.lastIndexOf(ARRAY234, (float) 1));
assertEquals(0, Floats.lastIndexOf(
new float[] {(float) -1}, (float) -1));
assertEquals(0, Floats.lastIndexOf(ARRAY234, (float) 2));
assertEquals(1, Floats.lastIndexOf(ARRAY234, (float) 3));
assertEquals(2, Floats.lastIndexOf(ARRAY234, (float) 4));
assertEquals(3, Floats.lastIndexOf(
new float[] { (float) 2, (float) 3, (float) 2, (float) 3 },
(float) 3));
for (float value : NUMBERS) {
assertEquals("" + value,
0, Floats.lastIndexOf(new float[] {value, 5f}, value));
}
assertEquals(-1, Floats.lastIndexOf(new float[] {NaN, 5f}, NaN));
}
public void testMax_noArgs() {
try {
Floats.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(GREATEST, Floats.max(GREATEST));
assertEquals(LEAST, Floats.max(LEAST));
assertEquals((float) 9, Floats.max(
(float) 8, (float) 6, (float) 7,
(float) 5, (float) 3, (float) 0, (float) 9));
assertEquals(0f, Floats.max(-0f, 0f));
assertEquals(0f, Floats.max(0f, -0f));
assertEquals(GREATEST, Floats.max(NUMBERS));
assertTrue(Float.isNaN(Floats.max(VALUES)));
}
public void testMin_noArgs() {
try {
Floats.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, Floats.min(LEAST));
assertEquals(GREATEST, Floats.min(GREATEST));
assertEquals((float) 0, Floats.min(
(float) 8, (float) 6, (float) 7,
(float) 5, (float) 3, (float) 0, (float) 9));
assertEquals(-0f, Floats.min(-0f, 0f));
assertEquals(-0f, Floats.min(0f, -0f));
assertEquals(LEAST, Floats.min(NUMBERS));
assertTrue(Float.isNaN(Floats.min(VALUES)));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Floats.concat()));
assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Floats.concat(ARRAY1)));
assertNotSame(ARRAY1, Floats.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Floats.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new float[] {(float) 1, (float) 1, (float) 1},
Floats.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new float[] {(float) 1, (float) 2, (float) 3, (float) 4},
Floats.concat(ARRAY1, ARRAY234)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Floats.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new float[] {(float) 1, (float) 0, (float) 0},
Floats.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Floats.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Floats.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testLexicographicalComparator() {
List<float[]> ordered = Arrays.asList(
new float[] {},
new float[] {LEAST},
new float[] {LEAST, LEAST},
new float[] {LEAST, (float) 1},
new float[] {(float) 1},
new float[] {(float) 1, LEAST},
new float[] {GREATEST, Float.MAX_VALUE},
new float[] {GREATEST, GREATEST},
new float[] {GREATEST, GREATEST, GREATEST});
Comparator<float[]> comparator = Floats.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Float> none = Arrays.<Float>asList();
assertTrue(Arrays.equals(EMPTY, Floats.toArray(none)));
List<Float> one = Arrays.asList((float) 1);
assertTrue(Arrays.equals(ARRAY1, Floats.toArray(one)));
float[] array = {(float) 0, (float) 1, (float) 3};
List<Float> three = Arrays.asList((float) 0, (float) 1, (float) 3);
assertTrue(Arrays.equals(array, Floats.toArray(three)));
assertTrue(Arrays.equals(array, Floats.toArray(Floats.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Float> list = Floats.asList(VALUES).subList(0, i);
Collection<Float> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
float[] arr = Floats.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Float> list = Arrays.asList((float) 0, (float) 1, null);
try {
Floats.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testToArray_withConversion() {
float[] array = {(float) 0, (float) 1, (float) 2};
List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
List<Integer> ints = Arrays.asList(0, 1, 2);
List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
assertTrue(Arrays.equals(array, Floats.toArray(bytes)));
assertTrue(Arrays.equals(array, Floats.toArray(shorts)));
assertTrue(Arrays.equals(array, Floats.toArray(ints)));
assertTrue(Arrays.equals(array, Floats.toArray(floats)));
assertTrue(Arrays.equals(array, Floats.toArray(longs)));
assertTrue(Arrays.equals(array, Floats.toArray(doubles)));
}
public void testAsList_isAView() {
float[] array = {(float) 0, (float) 1};
List<Float> list = Floats.asList(array);
list.set(0, (float) 2);
assertTrue(Arrays.equals(new float[] {(float) 2, (float) 1}, array));
array[1] = (float) 3;
ASSERT.that(list).has().exactly((float) 2, (float) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
float[] array = { (float) 0, (float) 1, (float) 2 };
List<Float> list = Floats.asList(array);
float[] newArray = Floats.toArray(list);
// Make sure it returned a copy
list.set(0, (float) 4);
assertTrue(Arrays.equals(
new float[] { (float) 0, (float) 1, (float) 2 }, newArray));
newArray[1] = (float) 5;
assertEquals((float) 1, (float) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
float[] array = { (float) 0, (float) 1, (float) 2, (float) 3 };
List<Float> list = Floats.asList(array);
assertTrue(Arrays.equals(new float[] { (float) 1, (float) 2 },
Floats.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new float[] {},
Floats.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Floats.asList(EMPTY));
}
/**
* A reference implementation for {@code tryParse} that just catches the exception from
* {@link Float#valueOf}.
*/
private static Float referenceTryParse(String input) {
if (input.trim().length() < input.length()) {
return null;
}
try {
return Float.valueOf(input);
} catch (NumberFormatException e) {
return null;
}
}
private static final String[] BAD_TRY_PARSE_INPUTS =
{ "", "+-", "+-0", " 5", "32 ", " 55 ", "infinity", "POSITIVE_INFINITY", "0x9A", "0x9A.bE-5",
".", ".e5", "NaNd", "InfinityF" };
public void testStringConverter_convertError() {
try {
Floats.stringConverter().convert("notanumber");
fail();
} catch (NumberFormatException expected) {
}
}
public void testStringConverter_nullConversions() {
assertNull(Floats.stringConverter().convert(null));
assertNull(Floats.stringConverter().reverse().convert(null));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/FloatsTest.java | Java | asf20 | 14,114 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static java.lang.Double.NaN;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link Doubles}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class DoublesTest extends TestCase {
private static final double[] EMPTY = {};
private static final double[] ARRAY1 = {(double) 1};
private static final double[] ARRAY234
= {(double) 2, (double) 3, (double) 4};
private static final double LEAST = Double.NEGATIVE_INFINITY;
private static final double GREATEST = Double.POSITIVE_INFINITY;
private static final double[] NUMBERS = new double[] {
LEAST, -Double.MAX_VALUE, -1.0, -0.5, -0.1, -0.0, 0.0, 0.1, 0.5, 1.0,
Double.MAX_VALUE, GREATEST, Double.MIN_NORMAL, -Double.MIN_NORMAL,
Double.MIN_VALUE, -Double.MIN_VALUE, Integer.MIN_VALUE,
Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE
};
private static final double[] VALUES
= Doubles.concat(NUMBERS, new double[] {NaN});
public void testHashCode() {
for (double value : VALUES) {
assertEquals(((Double) value).hashCode(), Doubles.hashCode(value));
}
}
public void testIsFinite() {
for (double value : NUMBERS) {
assertEquals(!(Double.isNaN(value) || Double.isInfinite(value)), Doubles.isFinite(value));
}
}
public void testCompare() {
for (double x : VALUES) {
for (double y : VALUES) {
// note: spec requires only that the sign is the same
assertEquals(x + ", " + y,
Double.valueOf(x).compareTo(y),
Doubles.compare(x, y));
}
}
}
public void testContains() {
assertFalse(Doubles.contains(EMPTY, (double) 1));
assertFalse(Doubles.contains(ARRAY1, (double) 2));
assertFalse(Doubles.contains(ARRAY234, (double) 1));
assertTrue(Doubles.contains(new double[] {(double) -1}, (double) -1));
assertTrue(Doubles.contains(ARRAY234, (double) 2));
assertTrue(Doubles.contains(ARRAY234, (double) 3));
assertTrue(Doubles.contains(ARRAY234, (double) 4));
for (double value : NUMBERS) {
assertTrue("" + value,
Doubles.contains(new double[] {5.0, value}, value));
}
assertFalse(Doubles.contains(new double[] {5.0, NaN}, NaN));
}
public void testIndexOf() {
assertEquals(-1, Doubles.indexOf(EMPTY, (double) 1));
assertEquals(-1, Doubles.indexOf(ARRAY1, (double) 2));
assertEquals(-1, Doubles.indexOf(ARRAY234, (double) 1));
assertEquals(0, Doubles.indexOf(
new double[] {(double) -1}, (double) -1));
assertEquals(0, Doubles.indexOf(ARRAY234, (double) 2));
assertEquals(1, Doubles.indexOf(ARRAY234, (double) 3));
assertEquals(2, Doubles.indexOf(ARRAY234, (double) 4));
assertEquals(1, Doubles.indexOf(
new double[] { (double) 2, (double) 3, (double) 2, (double) 3 },
(double) 3));
for (double value : NUMBERS) {
assertEquals("" + value,
1, Doubles.indexOf(new double[] {5.0, value}, value));
}
assertEquals(-1, Doubles.indexOf(new double[] {5.0, NaN}, NaN));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Doubles.indexOf(EMPTY, EMPTY));
assertEquals(0, Doubles.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Doubles.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Doubles.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Doubles.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Doubles.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Doubles.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Doubles.indexOf(
ARRAY234, new double[] { (double) 2, (double) 3 }));
assertEquals(1, Doubles.indexOf(
ARRAY234, new double[] { (double) 3, (double) 4 }));
assertEquals(1, Doubles.indexOf(ARRAY234, new double[] { (double) 3 }));
assertEquals(2, Doubles.indexOf(ARRAY234, new double[] { (double) 4 }));
assertEquals(1, Doubles.indexOf(new double[] { (double) 2, (double) 3,
(double) 3, (double) 3, (double) 3 },
new double[] { (double) 3 }
));
assertEquals(2, Doubles.indexOf(
new double[] { (double) 2, (double) 3, (double) 2,
(double) 3, (double) 4, (double) 2, (double) 3},
new double[] { (double) 2, (double) 3, (double) 4}
));
assertEquals(1, Doubles.indexOf(
new double[] { (double) 2, (double) 2, (double) 3,
(double) 4, (double) 2, (double) 3, (double) 4},
new double[] { (double) 2, (double) 3, (double) 4}
));
assertEquals(-1, Doubles.indexOf(
new double[] { (double) 4, (double) 3, (double) 2},
new double[] { (double) 2, (double) 3, (double) 4}
));
for (double value : NUMBERS) {
assertEquals("" + value, 1, Doubles.indexOf(
new double[] {5.0, value, value, 5.0}, new double[] {value, value}));
}
assertEquals(-1, Doubles.indexOf(
new double[] {5.0, NaN, NaN, 5.0}, new double[] {NaN, NaN}));
}
public void testLastIndexOf() {
assertEquals(-1, Doubles.lastIndexOf(EMPTY, (double) 1));
assertEquals(-1, Doubles.lastIndexOf(ARRAY1, (double) 2));
assertEquals(-1, Doubles.lastIndexOf(ARRAY234, (double) 1));
assertEquals(0, Doubles.lastIndexOf(
new double[] {(double) -1}, (double) -1));
assertEquals(0, Doubles.lastIndexOf(ARRAY234, (double) 2));
assertEquals(1, Doubles.lastIndexOf(ARRAY234, (double) 3));
assertEquals(2, Doubles.lastIndexOf(ARRAY234, (double) 4));
assertEquals(3, Doubles.lastIndexOf(
new double[] { (double) 2, (double) 3, (double) 2, (double) 3 },
(double) 3));
for (double value : NUMBERS) {
assertEquals("" + value,
0, Doubles.lastIndexOf(new double[] {value, 5.0}, value));
}
assertEquals(-1, Doubles.lastIndexOf(new double[] {NaN, 5.0}, NaN));
}
public void testMax_noArgs() {
try {
Doubles.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, Doubles.max(LEAST));
assertEquals(GREATEST, Doubles.max(GREATEST));
assertEquals((double) 9, Doubles.max(
(double) 8, (double) 6, (double) 7,
(double) 5, (double) 3, (double) 0, (double) 9));
assertEquals(0.0, Doubles.max(-0.0, 0.0));
assertEquals(0.0, Doubles.max(0.0, -0.0));
assertEquals(GREATEST, Doubles.max(NUMBERS));
assertTrue(Double.isNaN(Doubles.max(VALUES)));
}
public void testMin_noArgs() {
try {
Doubles.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, Doubles.min(LEAST));
assertEquals(GREATEST, Doubles.min(GREATEST));
assertEquals((double) 0, Doubles.min(
(double) 8, (double) 6, (double) 7,
(double) 5, (double) 3, (double) 0, (double) 9));
assertEquals(-0.0, Doubles.min(-0.0, 0.0));
assertEquals(-0.0, Doubles.min(0.0, -0.0));
assertEquals(LEAST, Doubles.min(NUMBERS));
assertTrue(Double.isNaN(Doubles.min(VALUES)));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Doubles.concat()));
assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Doubles.concat(ARRAY1)));
assertNotSame(ARRAY1, Doubles.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Doubles.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new double[] {(double) 1, (double) 1, (double) 1},
Doubles.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new double[] {(double) 1, (double) 2, (double) 3, (double) 4},
Doubles.concat(ARRAY1, ARRAY234)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Doubles.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new double[] {(double) 1, (double) 0, (double) 0},
Doubles.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Doubles.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Doubles.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testJoinNonTrivialDoubles() {
assertEquals("", Doubles.join(",", EMPTY));
assertEquals("1.2", Doubles.join(",", 1.2));
assertEquals("1.3,2.4", Doubles.join(",", 1.3, 2.4));
assertEquals("1.42.53.6", Doubles.join("", 1.4, 2.5, 3.6));
}
public void testLexicographicalComparator() {
List<double[]> ordered = Arrays.asList(
new double[] {},
new double[] {LEAST},
new double[] {LEAST, LEAST},
new double[] {LEAST, (double) 1},
new double[] {(double) 1},
new double[] {(double) 1, LEAST},
new double[] {GREATEST, Double.MAX_VALUE},
new double[] {GREATEST, GREATEST},
new double[] {GREATEST, GREATEST, GREATEST});
Comparator<double[]> comparator = Doubles.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Double> none = Arrays.<Double>asList();
assertTrue(Arrays.equals(EMPTY, Doubles.toArray(none)));
List<Double> one = Arrays.asList((double) 1);
assertTrue(Arrays.equals(ARRAY1, Doubles.toArray(one)));
double[] array = {(double) 0, (double) 1, Math.PI};
List<Double> three = Arrays.asList((double) 0, (double) 1, Math.PI);
assertTrue(Arrays.equals(array, Doubles.toArray(three)));
assertTrue(Arrays.equals(array, Doubles.toArray(Doubles.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Double> list = Doubles.asList(VALUES).subList(0, i);
Collection<Double> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
double[] arr = Doubles.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Double> list = Arrays.asList((double) 0, (double) 1, null);
try {
Doubles.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testToArray_withConversion() {
double[] array = {(double) 0, (double) 1, (double) 2};
List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
List<Integer> ints = Arrays.asList(0, 1, 2);
List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
assertTrue(Arrays.equals(array, Doubles.toArray(bytes)));
assertTrue(Arrays.equals(array, Doubles.toArray(shorts)));
assertTrue(Arrays.equals(array, Doubles.toArray(ints)));
assertTrue(Arrays.equals(array, Doubles.toArray(floats)));
assertTrue(Arrays.equals(array, Doubles.toArray(longs)));
assertTrue(Arrays.equals(array, Doubles.toArray(doubles)));
}
public void testAsList_isAView() {
double[] array = {(double) 0, (double) 1};
List<Double> list = Doubles.asList(array);
list.set(0, (double) 2);
assertTrue(Arrays.equals(new double[] {(double) 2, (double) 1}, array));
array[1] = (double) 3;
ASSERT.that(list).has().exactly((double) 2, (double) 3).inOrder();
}
public void testAsList_toArray_roundTrip() {
double[] array = { (double) 0, (double) 1, (double) 2 };
List<Double> list = Doubles.asList(array);
double[] newArray = Doubles.toArray(list);
// Make sure it returned a copy
list.set(0, (double) 4);
assertTrue(Arrays.equals(
new double[] { (double) 0, (double) 1, (double) 2 }, newArray));
newArray[1] = (double) 5;
assertEquals((double) 1, (double) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
double[] array = { (double) 0, (double) 1, (double) 2, (double) 3 };
List<Double> list = Doubles.asList(array);
assertTrue(Arrays.equals(new double[] { (double) 1, (double) 2 },
Doubles.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new double[] {},
Doubles.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Doubles.asList(EMPTY));
}
/**
* A reference implementation for {@code tryParse} that just catches the exception from
* {@link Double#valueOf}.
*/
private static Double referenceTryParse(String input) {
if (input.trim().length() < input.length()) {
return null;
}
try {
return Double.valueOf(input);
} catch (NumberFormatException e) {
return null;
}
}
private static final String[] BAD_TRY_PARSE_INPUTS =
{ "", "+-", "+-0", " 5", "32 ", " 55 ", "infinity", "POSITIVE_INFINITY", "0x9A", "0x9A.bE-5",
".", ".e5", "NaNd", "InfinityF" };
public void testStringConverter_convert() {
Converter<String, Double> converter = Doubles.stringConverter();
assertEquals((Double) 1.0, converter.convert("1.0"));
assertEquals((Double) 0.0, converter.convert("0.0"));
assertEquals((Double) (-1.0), converter.convert("-1.0"));
assertEquals((Double) 1.0, converter.convert("1"));
assertEquals((Double) 0.0, converter.convert("0"));
assertEquals((Double) (-1.0), converter.convert("-1"));
assertEquals((Double) 1e6, converter.convert("1e6"));
assertEquals((Double) 1e-6, converter.convert("1e-6"));
}
public void testStringConverter_convertError() {
try {
Doubles.stringConverter().convert("notanumber");
fail();
} catch (NumberFormatException expected) {
}
}
public void testStringConverter_nullConversions() {
assertNull(Doubles.stringConverter().convert(null));
assertNull(Doubles.stringConverter().reverse().convert(null));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/DoublesTest.java | Java | asf20 | 15,415 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Longs#asList(long[])}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class LongArrayAsListTest extends TestCase {
private static List<Long> asList(Long[] values) {
long[] temp = new long[values.length];
for (int i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Longs.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class LongsAsListGenerator extends TestLongListGenerator {
@Override protected List<Long> create(Long[] elements) {
return asList(elements);
}
}
public static final class LongsAsListHeadSubListGenerator extends TestLongListGenerator {
@Override protected List<Long> create(Long[] elements) {
Long[] suffix = {Long.MIN_VALUE, Long.MAX_VALUE};
Long[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class LongsAsListTailSubListGenerator extends TestLongListGenerator {
@Override protected List<Long> create(Long[] elements) {
Long[] prefix = {(long) 86, (long) 99};
Long[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class LongsAsListMiddleSubListGenerator extends TestLongListGenerator {
@Override protected List<Long> create(Long[] elements) {
Long[] prefix = {Long.MIN_VALUE, Long.MAX_VALUE};
Long[] suffix = {(long) 86, (long) 99};
Long[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Long[] concat(Long[] left, Long[] right) {
Long[] result = new Long[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestLongListGenerator
implements TestListGenerator<Long> {
@Override
public SampleElements<Long> samples() {
return new SampleLongs();
}
@Override
public List<Long> create(Object... elements) {
Long[] array = new Long[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Long) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Long> create(Long[] elements);
@Override
public Long[] createArray(int length) {
return new Long[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Long> order(List<Long> insertionOrder) {
return insertionOrder;
}
}
public static class SampleLongs extends SampleElements<Long> {
public SampleLongs() {
super((long) 0, (long) 1, (long) 2, (long) 3, (long) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/LongArrayAsListTest.java | Java | asf20 | 4,068 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static java.lang.Long.MAX_VALUE;
import static java.lang.Long.MIN_VALUE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
/**
* Unit test for {@link Longs}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class LongsTest extends TestCase {
private static final long[] EMPTY = {};
private static final long[] ARRAY1 = {(long) 1};
private static final long[] ARRAY234
= {(long) 2, (long) 3, (long) 4};
private static final long[] VALUES =
{ MIN_VALUE, (long) -1, (long) 0, (long) 1, MAX_VALUE };
public void testCompare() {
for (long x : VALUES) {
for (long y : VALUES) {
// note: spec requires only that the sign is the same
assertEquals(x + ", " + y,
Long.valueOf(x).compareTo(y),
Longs.compare(x, y));
}
}
}
public void testContains() {
assertFalse(Longs.contains(EMPTY, (long) 1));
assertFalse(Longs.contains(ARRAY1, (long) 2));
assertFalse(Longs.contains(ARRAY234, (long) 1));
assertTrue(Longs.contains(new long[] {(long) -1}, (long) -1));
assertTrue(Longs.contains(ARRAY234, (long) 2));
assertTrue(Longs.contains(ARRAY234, (long) 3));
assertTrue(Longs.contains(ARRAY234, (long) 4));
}
public void testIndexOf() {
assertEquals(-1, Longs.indexOf(EMPTY, (long) 1));
assertEquals(-1, Longs.indexOf(ARRAY1, (long) 2));
assertEquals(-1, Longs.indexOf(ARRAY234, (long) 1));
assertEquals(0, Longs.indexOf(
new long[] {(long) -1}, (long) -1));
assertEquals(0, Longs.indexOf(ARRAY234, (long) 2));
assertEquals(1, Longs.indexOf(ARRAY234, (long) 3));
assertEquals(2, Longs.indexOf(ARRAY234, (long) 4));
assertEquals(1, Longs.indexOf(
new long[] { (long) 2, (long) 3, (long) 2, (long) 3 },
(long) 3));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Longs.indexOf(EMPTY, EMPTY));
assertEquals(0, Longs.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Longs.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Longs.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Longs.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Longs.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Longs.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Longs.indexOf(
ARRAY234, new long[] { (long) 2, (long) 3 }));
assertEquals(1, Longs.indexOf(
ARRAY234, new long[] { (long) 3, (long) 4 }));
assertEquals(1, Longs.indexOf(ARRAY234, new long[] { (long) 3 }));
assertEquals(2, Longs.indexOf(ARRAY234, new long[] { (long) 4 }));
assertEquals(1, Longs.indexOf(new long[] { (long) 2, (long) 3,
(long) 3, (long) 3, (long) 3 },
new long[] { (long) 3 }
));
assertEquals(2, Longs.indexOf(
new long[] { (long) 2, (long) 3, (long) 2,
(long) 3, (long) 4, (long) 2, (long) 3},
new long[] { (long) 2, (long) 3, (long) 4}
));
assertEquals(1, Longs.indexOf(
new long[] { (long) 2, (long) 2, (long) 3,
(long) 4, (long) 2, (long) 3, (long) 4},
new long[] { (long) 2, (long) 3, (long) 4}
));
assertEquals(-1, Longs.indexOf(
new long[] { (long) 4, (long) 3, (long) 2},
new long[] { (long) 2, (long) 3, (long) 4}
));
}
public void testLastIndexOf() {
assertEquals(-1, Longs.lastIndexOf(EMPTY, (long) 1));
assertEquals(-1, Longs.lastIndexOf(ARRAY1, (long) 2));
assertEquals(-1, Longs.lastIndexOf(ARRAY234, (long) 1));
assertEquals(0, Longs.lastIndexOf(
new long[] {(long) -1}, (long) -1));
assertEquals(0, Longs.lastIndexOf(ARRAY234, (long) 2));
assertEquals(1, Longs.lastIndexOf(ARRAY234, (long) 3));
assertEquals(2, Longs.lastIndexOf(ARRAY234, (long) 4));
assertEquals(3, Longs.lastIndexOf(
new long[] { (long) 2, (long) 3, (long) 2, (long) 3 },
(long) 3));
}
public void testMax_noArgs() {
try {
Longs.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(MIN_VALUE, Longs.max(MIN_VALUE));
assertEquals(MAX_VALUE, Longs.max(MAX_VALUE));
assertEquals((long) 9, Longs.max(
(long) 8, (long) 6, (long) 7,
(long) 5, (long) 3, (long) 0, (long) 9));
}
public void testMin_noArgs() {
try {
Longs.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(MIN_VALUE, Longs.min(MIN_VALUE));
assertEquals(MAX_VALUE, Longs.min(MAX_VALUE));
assertEquals((long) 0, Longs.min(
(long) 8, (long) 6, (long) 7,
(long) 5, (long) 3, (long) 0, (long) 9));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Longs.concat()));
assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Longs.concat(ARRAY1)));
assertNotSame(ARRAY1, Longs.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Longs.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new long[] {(long) 1, (long) 1, (long) 1},
Longs.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new long[] {(long) 1, (long) 2, (long) 3, (long) 4},
Longs.concat(ARRAY1, ARRAY234)));
}
private static void assertByteArrayEquals(byte[] expected, byte[] actual) {
assertTrue(
"Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual),
Arrays.equals(expected, actual));
}
public void testToByteArray() {
assertByteArrayEquals(
new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19},
Longs.toByteArray(0x1213141516171819L));
assertByteArrayEquals(
new byte[] {
(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
(byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88},
Longs.toByteArray(0xFFEEDDCCBBAA9988L));
}
public void testFromByteArray() {
assertEquals(0x1213141516171819L, Longs.fromByteArray(
new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33}));
assertEquals(0xFFEEDDCCBBAA9988L, Longs.fromByteArray(
new byte[] {
(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
(byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88}));
try {
Longs.fromByteArray(new byte[Longs.BYTES - 1]);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testFromBytes() {
assertEquals(0x1213141516171819L, Longs.fromBytes(
(byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15,
(byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19));
assertEquals(0xFFEEDDCCBBAA9988L, Longs.fromBytes(
(byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC,
(byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88));
}
public void testByteArrayRoundTrips() {
Random r = new Random(5);
byte[] b = new byte[Longs.BYTES];
// total overkill, but, it takes 0.1 sec so why not...
for (int i = 0; i < 10000; i++) {
long num = r.nextLong();
assertEquals(num, Longs.fromByteArray(Longs.toByteArray(num)));
r.nextBytes(b);
long value = Longs.fromByteArray(b);
assertTrue("" + value, Arrays.equals(b, Longs.toByteArray(value)));
}
}
public void testEnsureCapacity() {
assertSame(EMPTY, Longs.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new long[] {(long) 1, (long) 0, (long) 0},
Longs.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Longs.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Longs.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testJoin() {
assertEquals("", Longs.join(",", EMPTY));
assertEquals("1", Longs.join(",", ARRAY1));
assertEquals("1,2", Longs.join(",", (long) 1, (long) 2));
assertEquals("123",
Longs.join("", (long) 1, (long) 2, (long) 3));
}
public void testLexicographicalComparator() {
List<long[]> ordered = Arrays.asList(
new long[] {},
new long[] {MIN_VALUE},
new long[] {MIN_VALUE, MIN_VALUE},
new long[] {MIN_VALUE, (long) 1},
new long[] {(long) 1},
new long[] {(long) 1, MIN_VALUE},
new long[] {MAX_VALUE, MAX_VALUE - (long) 1},
new long[] {MAX_VALUE, MAX_VALUE},
new long[] {MAX_VALUE, MAX_VALUE, MAX_VALUE});
Comparator<long[]> comparator = Longs.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Long> none = Arrays.<Long>asList();
assertTrue(Arrays.equals(EMPTY, Longs.toArray(none)));
List<Long> one = Arrays.asList((long) 1);
assertTrue(Arrays.equals(ARRAY1, Longs.toArray(one)));
long[] array = {(long) 0, (long) 1, 0x0FF1C1AL};
List<Long> three = Arrays.asList((long) 0, (long) 1, 0x0FF1C1AL);
assertTrue(Arrays.equals(array, Longs.toArray(three)));
assertTrue(Arrays.equals(array, Longs.toArray(Longs.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Long> list = Longs.asList(VALUES).subList(0, i);
Collection<Long> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
long[] arr = Longs.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Long> list = Arrays.asList((long) 0, (long) 1, null);
try {
Longs.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testToArray_withConversion() {
long[] array = {(long) 0, (long) 1, (long) 2};
List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
List<Integer> ints = Arrays.asList(0, 1, 2);
List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
assertTrue(Arrays.equals(array, Longs.toArray(bytes)));
assertTrue(Arrays.equals(array, Longs.toArray(shorts)));
assertTrue(Arrays.equals(array, Longs.toArray(ints)));
assertTrue(Arrays.equals(array, Longs.toArray(floats)));
assertTrue(Arrays.equals(array, Longs.toArray(longs)));
assertTrue(Arrays.equals(array, Longs.toArray(doubles)));
}
public void testAsList_isAView() {
long[] array = {(long) 0, (long) 1};
List<Long> list = Longs.asList(array);
list.set(0, (long) 2);
assertTrue(Arrays.equals(new long[] {(long) 2, (long) 1}, array));
array[1] = (long) 3;
assertEquals(Arrays.asList((long) 2, (long) 3), list);
}
public void testAsList_toArray_roundTrip() {
long[] array = { (long) 0, (long) 1, (long) 2 };
List<Long> list = Longs.asList(array);
long[] newArray = Longs.toArray(list);
// Make sure it returned a copy
list.set(0, (long) 4);
assertTrue(Arrays.equals(
new long[] { (long) 0, (long) 1, (long) 2 }, newArray));
newArray[1] = (long) 5;
assertEquals((long) 1, (long) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
long[] array = { (long) 0, (long) 1, (long) 2, (long) 3 };
List<Long> list = Longs.asList(array);
assertTrue(Arrays.equals(new long[] { (long) 1, (long) 2 },
Longs.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new long[] {},
Longs.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Longs.asList(EMPTY));
}
public void testStringConverter_convert() {
Converter<String, Long> converter = Longs.stringConverter();
assertEquals((Long) 1L, converter.convert("1"));
assertEquals((Long) 0L, converter.convert("0"));
assertEquals((Long) (-1L), converter.convert("-1"));
assertEquals((Long) 255L, converter.convert("0xff"));
assertEquals((Long) 255L, converter.convert("0xFF"));
assertEquals((Long) (-255L), converter.convert("-0xFF"));
assertEquals((Long) 255L, converter.convert("#0000FF"));
assertEquals((Long) 438L, converter.convert("0666"));
}
public void testStringConverter_convertError() {
try {
Longs.stringConverter().convert("notanumber");
fail();
} catch (NumberFormatException expected) {
}
}
public void testStringConverter_nullConversions() {
assertNull(Longs.stringConverter().convert(null));
assertNull(Longs.stringConverter().reverse().convert(null));
}
public void testStringConverter_reverse() {
Converter<String, Long> converter = Longs.stringConverter();
assertEquals("1", converter.reverse().convert(1L));
assertEquals("0", converter.reverse().convert(0L));
assertEquals("-1", converter.reverse().convert(-1L));
assertEquals("255", converter.reverse().convert(0xffL));
assertEquals("255", converter.reverse().convert(0xFFL));
assertEquals("-255", converter.reverse().convert(-0xFFL));
assertEquals("438", converter.reverse().convert(0666L));
}
/**
* Applies {@link Longs#tryParse(String)} to the given string and asserts that
* the result is as expected.
*/
private static void tryParseAndAssertEquals(Long expected, String value) {
assertEquals(expected, Longs.tryParse(value));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/LongsTest.java | Java | asf20 | 15,073 |
/*
* Copyright (C) 2011 The Guava 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.common.primitives;
import static java.math.BigInteger.ONE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* Tests for UnsignedLongs
*
* @author Brian Milch
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class UnsignedLongsTest extends TestCase {
private static final long LEAST = 0L;
private static final long GREATEST = 0xffffffffffffffffL;
public void testCompare() {
// max value
assertTrue(UnsignedLongs.compare(0, 0xffffffffffffffffL) < 0);
assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0) > 0);
// both with high bit set
assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xffffffffffffffffL) < 0);
assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0xff1a618b7f65ea12L) > 0);
// one with high bit set
assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0xff1a618b7f65ea12L) < 0);
assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0x5a4316b8c153ac4dL) > 0);
// neither with high bit set
assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0x6cf78a4b139a4e2aL) < 0);
assertTrue(UnsignedLongs.compare(0x6cf78a4b139a4e2aL, 0x5a4316b8c153ac4dL) > 0);
// same value
assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xff1a618b7f65ea12L) == 0);
}
public void testMax_noArgs() {
try {
UnsignedLongs.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, UnsignedLongs.max(LEAST));
assertEquals(GREATEST, UnsignedLongs.max(GREATEST));
assertEquals(0xff1a618b7f65ea12L, UnsignedLongs.max(
0x5a4316b8c153ac4dL, 8L, 100L,
0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L));
}
public void testMin_noArgs() {
try {
UnsignedLongs.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, UnsignedLongs.min(LEAST));
assertEquals(GREATEST, UnsignedLongs.min(GREATEST));
assertEquals(0L, UnsignedLongs.min(
0x5a4316b8c153ac4dL, 8L, 100L,
0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L));
}
public void testLexicographicalComparator() {
List<long[]> ordered = Arrays.asList(
new long[] {},
new long[] {LEAST},
new long[] {LEAST, LEAST},
new long[] {LEAST, (long) 1},
new long[] {(long) 1},
new long[] {(long) 1, LEAST},
new long[] {GREATEST, GREATEST - (long) 1},
new long[] {GREATEST, GREATEST},
new long[] {GREATEST, GREATEST, GREATEST});
Comparator<long[]> comparator = UnsignedLongs.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testDivide() {
assertEquals(2, UnsignedLongs.divide(14, 5));
assertEquals(0, UnsignedLongs.divide(0, 50));
assertEquals(1, UnsignedLongs.divide(0xfffffffffffffffeL, 0xfffffffffffffffdL));
assertEquals(0, UnsignedLongs.divide(0xfffffffffffffffdL, 0xfffffffffffffffeL));
assertEquals(281479271743488L, UnsignedLongs.divide(0xfffffffffffffffeL, 65535));
assertEquals(0x7fffffffffffffffL, UnsignedLongs.divide(0xfffffffffffffffeL, 2));
assertEquals(3689348814741910322L, UnsignedLongs.divide(0xfffffffffffffffeL, 5));
}
public void testRemainder() {
assertEquals(4, UnsignedLongs.remainder(14, 5));
assertEquals(0, UnsignedLongs.remainder(0, 50));
assertEquals(1, UnsignedLongs.remainder(0xfffffffffffffffeL, 0xfffffffffffffffdL));
assertEquals(0xfffffffffffffffdL,
UnsignedLongs.remainder(0xfffffffffffffffdL, 0xfffffffffffffffeL));
assertEquals(65534L, UnsignedLongs.remainder(0xfffffffffffffffeL, 65535));
assertEquals(0, UnsignedLongs.remainder(0xfffffffffffffffeL, 2));
assertEquals(4, UnsignedLongs.remainder(0xfffffffffffffffeL, 5));
}
public void testParseLong() {
assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("18446744073709551615"));
assertEquals(0x7fffffffffffffffL, UnsignedLongs.parseUnsignedLong("9223372036854775807"));
assertEquals(0xff1a618b7f65ea12L, UnsignedLongs.parseUnsignedLong("18382112080831834642"));
assertEquals(0x5a4316b8c153ac4dL, UnsignedLongs.parseUnsignedLong("6504067269626408013"));
assertEquals(0x6cf78a4b139a4e2aL, UnsignedLongs.parseUnsignedLong("7851896530399809066"));
try {
// One more than maximum value
UnsignedLongs.parseUnsignedLong("18446744073709551616");
fail();
} catch (NumberFormatException expected) {
}
}
public void testDecodeLong() {
assertEquals(0xffffffffffffffffL, UnsignedLongs.decode("0xffffffffffffffff"));
assertEquals(01234567, UnsignedLongs.decode("01234567")); // octal
assertEquals(0x1234567890abcdefL, UnsignedLongs.decode("#1234567890abcdef"));
assertEquals(987654321012345678L, UnsignedLongs.decode("987654321012345678"));
assertEquals(0x135791357913579L, UnsignedLongs.decode("0x135791357913579"));
assertEquals(0x135791357913579L, UnsignedLongs.decode("0X135791357913579"));
assertEquals(0L, UnsignedLongs.decode("0"));
}
public void testDecodeLongFails() {
try {
// One more than maximum value
UnsignedLongs.decode("0xfffffffffffffffff");
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedLongs.decode("-5");
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedLongs.decode("-0x5");
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedLongs.decode("-05");
fail();
} catch (NumberFormatException expected) {
}
}
public void testParseLongWithRadix() {
assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("ffffffffffffffff", 16));
assertEquals(0x1234567890abcdefL, UnsignedLongs.parseUnsignedLong("1234567890abcdef", 16));
BigInteger max = BigInteger.ZERO.setBit(64).subtract(ONE);
// loops through all legal radix values.
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
// tests can successfully parse a number string with this radix.
String maxAsString = max.toString(radix);
assertEquals(max.longValue(), UnsignedLongs.parseUnsignedLong(maxAsString, radix));
try {
// tests that we get exception whre an overflow would occur.
BigInteger overflow = max.add(ONE);
String overflowAsString = overflow.toString(radix);
UnsignedLongs.parseUnsignedLong(overflowAsString, radix);
fail();
} catch (NumberFormatException expected) {
}
}
try {
UnsignedLongs.parseUnsignedLong("1234567890abcdef1", 16);
fail();
} catch (NumberFormatException expected) {
}
}
public void testParseLongThrowsExceptionForInvalidRadix() {
// Valid radix values are Character.MIN_RADIX to Character.MAX_RADIX, inclusive.
try {
UnsignedLongs.parseUnsignedLong("0", Character.MIN_RADIX - 1);
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedLongs.parseUnsignedLong("0", Character.MAX_RADIX + 1);
fail();
} catch (NumberFormatException expected) {
}
// The radix is used as an array index, so try a negative value.
try {
UnsignedLongs.parseUnsignedLong("0", -1);
fail();
} catch (NumberFormatException expected) {
}
}
public void testToString() {
String[] tests = {
"ffffffffffffffff",
"7fffffffffffffff",
"ff1a618b7f65ea12",
"5a4316b8c153ac4d",
"6cf78a4b139a4e2a"
};
int[] bases = { 2, 5, 7, 8, 10, 16 };
for (int base : bases) {
for (String x : tests) {
BigInteger xValue = new BigInteger(x, 16);
long xLong = xValue.longValue(); // signed
assertEquals(xValue.toString(base), UnsignedLongs.toString(xLong, base));
}
}
}
public void testJoin() {
assertEquals("", UnsignedLongs.join(","));
assertEquals("1", UnsignedLongs.join(",", 1));
assertEquals("1,2", UnsignedLongs.join(",", 1, 2));
assertEquals("18446744073709551615,9223372036854775808",
UnsignedLongs.join(",", -1, Long.MIN_VALUE));
assertEquals("123", UnsignedLongs.join("", 1, 2, 3));
assertEquals("184467440737095516159223372036854775808",
UnsignedLongs.join("", -1, Long.MIN_VALUE));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/UnsignedLongsTest.java | Java | asf20 | 9,181 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Chars#asList(char[])}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class CharArrayAsListTest extends TestCase {
private static List<Character> asList(Character[] values) {
char[] temp = new char[values.length];
for (int i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Chars.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class CharsAsListGenerator extends TestCharListGenerator {
@Override protected List<Character> create(Character[] elements) {
return asList(elements);
}
}
public static final class CharsAsListHeadSubListGenerator extends TestCharListGenerator {
@Override protected List<Character> create(Character[] elements) {
Character[] suffix = {Character.MIN_VALUE, Character.MAX_VALUE};
Character[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class CharsAsListTailSubListGenerator extends TestCharListGenerator {
@Override protected List<Character> create(Character[] elements) {
Character[] prefix = {(char) 86, (char) 99};
Character[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class CharsAsListMiddleSubListGenerator extends TestCharListGenerator {
@Override protected List<Character> create(Character[] elements) {
Character[] prefix = {Character.MIN_VALUE, Character.MAX_VALUE};
Character[] suffix = {(char) 86, (char) 99};
Character[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Character[] concat(Character[] left, Character[] right) {
Character[] result = new Character[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestCharListGenerator
implements TestListGenerator<Character> {
@Override
public SampleElements<Character> samples() {
return new SampleChars();
}
@Override
public List<Character> create(Object... elements) {
Character[] array = new Character[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Character) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Character> create(Character[] elements);
@Override
public Character[] createArray(int length) {
return new Character[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Character> order(List<Character> insertionOrder) {
return insertionOrder;
}
}
public static class SampleChars extends SampleElements<Character> {
public SampleChars() {
super((char) 0, (char) 1, (char) 2, (char) 3, (char) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/CharArrayAsListTest.java | Java | asf20 | 4,263 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Ints#asList(int[])}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class IntArrayAsListTest extends TestCase {
private static List<Integer> asList(Integer[] values) {
int[] temp = new int[values.length];
for (int i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Ints.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class IntsAsListGenerator extends TestIntegerListGenerator {
@Override protected List<Integer> create(Integer[] elements) {
return asList(elements);
}
}
public static final class IntsAsListHeadSubListGenerator extends TestIntegerListGenerator {
@Override protected List<Integer> create(Integer[] elements) {
Integer[] suffix = {Integer.MIN_VALUE, Integer.MAX_VALUE};
Integer[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class IntsAsListTailSubListGenerator extends TestIntegerListGenerator {
@Override protected List<Integer> create(Integer[] elements) {
Integer[] prefix = {(int) 86, (int) 99};
Integer[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class IntsAsListMiddleSubListGenerator extends TestIntegerListGenerator {
@Override protected List<Integer> create(Integer[] elements) {
Integer[] prefix = {Integer.MIN_VALUE, Integer.MAX_VALUE};
Integer[] suffix = {(int) 86, (int) 99};
Integer[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Integer[] concat(Integer[] left, Integer[] right) {
Integer[] result = new Integer[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestIntegerListGenerator
implements TestListGenerator<Integer> {
@Override
public SampleElements<Integer> samples() {
return new SampleIntegers();
}
@Override
public List<Integer> create(Object... elements) {
Integer[] array = new Integer[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Integer) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Integer> create(Integer[] elements);
@Override public Integer[] createArray(int length) {
return new Integer[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Integer> order(List<Integer> insertionOrder) {
return insertionOrder;
}
}
public static class SampleIntegers extends SampleElements<Integer> {
public SampleIntegers() {
super((int) 0, (int) 1, (int) 2, (int) 3, (int) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/IntArrayAsListTest.java | Java | asf20 | 4,260 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Doubles#asList(double[])}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class DoubleArrayAsListTest extends TestCase {
private static List<Double> asList(Double[] values) {
double[] temp = new double[values.length];
for (int i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Doubles.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class DoublesAsListGenerator extends TestDoubleListGenerator {
@Override protected List<Double> create(Double[] elements) {
return asList(elements);
}
}
public static final class DoublsAsListHeadSubListGenerator extends TestDoubleListGenerator {
@Override protected List<Double> create(Double[] elements) {
Double[] suffix = {Double.MIN_VALUE, Double.MAX_VALUE};
Double[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class DoublesAsListTailSubListGenerator extends TestDoubleListGenerator {
@Override protected List<Double> create(Double[] elements) {
Double[] prefix = {(double) 86, (double) 99};
Double[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class DoublesAsListMiddleSubListGenerator extends TestDoubleListGenerator {
@Override protected List<Double> create(Double[] elements) {
Double[] prefix = {Double.MIN_VALUE, Double.MAX_VALUE};
Double[] suffix = {(double) 86, (double) 99};
Double[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Double[] concat(Double[] left, Double[] right) {
Double[] result = new Double[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestDoubleListGenerator
implements TestListGenerator<Double> {
@Override
public SampleElements<Double> samples() {
return new SampleDoubles();
}
@Override
public List<Double> create(Object... elements) {
Double[] array = new Double[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Double) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Double> create(Double[] elements);
@Override
public Double[] createArray(int length) {
return new Double[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Double> order(List<Double> insertionOrder) {
return insertionOrder;
}
}
public static class SampleDoubles extends SampleElements<Double> {
public SampleDoubles() {
super((double) 0, (double) 1, (double) 2, (double) 3, (double) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/DoubleArrayAsListTest.java | Java | asf20 | 4,199 |
/*
* Copyright (C) 2011 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* Tests for UnsignedInts
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class UnsignedIntsTest extends TestCase {
private static final long[] UNSIGNED_INTS = {
0L,
1L,
2L,
3L,
0x12345678L,
0x5a4316b8L,
0x6cf78a4bL,
0xff1a618bL,
0xfffffffdL,
0xfffffffeL,
0xffffffffL};
private static final int LEAST = (int) 0L;
private static final int GREATEST = (int) 0xffffffffL;
public void testToLong() {
for (long a : UNSIGNED_INTS) {
assertEquals(a, UnsignedInts.toLong((int) a));
}
}
public void testCompare() {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
int cmpAsLongs = Longs.compare(a, b);
int cmpAsUInt = UnsignedInts.compare((int) a, (int) b);
assertEquals(Integer.signum(cmpAsLongs), Integer.signum(cmpAsUInt));
}
}
}
public void testMax_noArgs() {
try {
UnsignedInts.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, UnsignedInts.max(LEAST));
assertEquals(GREATEST, UnsignedInts.max(GREATEST));
assertEquals((int) 0xff1a618bL, UnsignedInts.max(
(int) 8L, (int) 6L, (int) 7L,
(int) 0x12345678L, (int) 0x5a4316b8L,
(int) 0xff1a618bL, (int) 0L));
}
public void testMin_noArgs() {
try {
UnsignedInts.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, UnsignedInts.min(LEAST));
assertEquals(GREATEST, UnsignedInts.min(GREATEST));
assertEquals((int) 0L, UnsignedInts.min(
(int) 8L, (int) 6L, (int) 7L,
(int) 0x12345678L, (int) 0x5a4316b8L,
(int) 0xff1a618bL, (int) 0L));
}
public void testLexicographicalComparator() {
List<int[]> ordered = Arrays.asList(
new int[] {},
new int[] {LEAST},
new int[] {LEAST, LEAST},
new int[] {LEAST, (int) 1L},
new int[] {(int) 1L},
new int[] {(int) 1L, LEAST},
new int[] {GREATEST, (GREATEST - (int) 1L)},
new int[] {GREATEST, GREATEST},
new int[] {GREATEST, GREATEST, GREATEST}
);
Comparator<int[]> comparator = UnsignedInts.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testDivide() {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
try {
assertEquals((int) (a / b), UnsignedInts.divide((int) a, (int) b));
assertFalse(b == 0);
} catch (ArithmeticException e) {
assertEquals(0, b);
}
}
}
}
public void testRemainder() {
for (long a : UNSIGNED_INTS) {
for (long b : UNSIGNED_INTS) {
try {
assertEquals((int) (a % b), UnsignedInts.remainder((int) a, (int) b));
assertFalse(b == 0);
} catch (ArithmeticException e) {
assertEquals(0, b);
}
}
}
}
public void testParseInt() {
try {
for (long a : UNSIGNED_INTS) {
assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a)));
}
} catch (NumberFormatException e) {
fail(e.getMessage());
}
try {
UnsignedInts.parseUnsignedInt(Long.toString(1L << 32));
fail("Expected NumberFormatException");
} catch (NumberFormatException expected) {}
}
public void testParseIntWithRadix() throws NumberFormatException {
for (long a : UNSIGNED_INTS) {
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a, radix), radix));
}
}
// loops through all legal radix values.
for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) {
// tests can successfully parse a number string with this radix.
String maxAsString = Long.toString((1L << 32) - 1, radix);
assertEquals(-1, UnsignedInts.parseUnsignedInt(maxAsString, radix));
try {
// tests that we get exception whre an overflow would occur.
long overflow = 1L << 32;
String overflowAsString = Long.toString(overflow, radix);
UnsignedInts.parseUnsignedInt(overflowAsString, radix);
fail();
} catch (NumberFormatException expected) {}
}
}
public void testParseIntThrowsExceptionForInvalidRadix() {
// Valid radix values are Character.MIN_RADIX to Character.MAX_RADIX,
// inclusive.
try {
UnsignedInts.parseUnsignedInt("0", Character.MIN_RADIX - 1);
fail();
} catch (NumberFormatException expected) {}
try {
UnsignedInts.parseUnsignedInt("0", Character.MAX_RADIX + 1);
fail();
} catch (NumberFormatException expected) {}
// The radix is used as an array index, so try a negative value.
try {
UnsignedInts.parseUnsignedInt("0", -1);
fail();
} catch (NumberFormatException expected) {}
}
public void testDecodeInt() {
assertEquals(0xffffffff, UnsignedInts.decode("0xffffffff"));
assertEquals(01234567, UnsignedInts.decode("01234567")); // octal
assertEquals(0x12345678, UnsignedInts.decode("#12345678"));
assertEquals(76543210, UnsignedInts.decode("76543210"));
assertEquals(0x13579135, UnsignedInts.decode("0x13579135"));
assertEquals(0x13579135, UnsignedInts.decode("0X13579135"));
assertEquals(0, UnsignedInts.decode("0"));
}
public void testDecodeIntFails() {
try {
// One more than maximum value
UnsignedInts.decode("0xfffffffff");
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedInts.decode("-5");
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedInts.decode("-0x5");
fail();
} catch (NumberFormatException expected) {
}
try {
UnsignedInts.decode("-05");
fail();
} catch (NumberFormatException expected) {
}
}
public void testToString() {
int[] bases = {2, 5, 7, 8, 10, 16};
for (long a : UNSIGNED_INTS) {
for (int base : bases) {
assertEquals(UnsignedInts.toString((int) a, base), Long.toString(a, base));
}
}
}
public void testJoin() {
assertEquals("", join());
assertEquals("1", join(1));
assertEquals("1,2", join(1, 2));
assertEquals("4294967295,2147483648", join(-1, Integer.MIN_VALUE));
assertEquals("123", UnsignedInts.join("", 1, 2, 3));
}
private static String join(int... values) {
return UnsignedInts.join(",", values);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/UnsignedIntsTest.java | Java | asf20 | 7,495 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link Shorts}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class ShortsTest extends TestCase {
private static final short[] EMPTY = {};
private static final short[] ARRAY1 = {(short) 1};
private static final short[] ARRAY234
= {(short) 2, (short) 3, (short) 4};
private static final short LEAST = Short.MIN_VALUE;
private static final short GREATEST = Short.MAX_VALUE;
private static final short[] VALUES =
{ LEAST, (short) -1, (short) 0, (short) 1, GREATEST };
public void testHashCode() {
for (short value : VALUES) {
assertEquals(((Short) value).hashCode(), Shorts.hashCode(value));
}
}
public void testCheckedCast() {
for (short value : VALUES) {
assertEquals(value, Shorts.checkedCast((long) value));
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
assertCastFails(Long.MAX_VALUE);
assertCastFails(Long.MIN_VALUE);
}
public void testSaturatedCast() {
for (short value : VALUES) {
assertEquals(value, Shorts.saturatedCast((long) value));
}
assertEquals(GREATEST, Shorts.saturatedCast(GREATEST + 1L));
assertEquals(LEAST, Shorts.saturatedCast(LEAST - 1L));
assertEquals(GREATEST, Shorts.saturatedCast(Long.MAX_VALUE));
assertEquals(LEAST, Shorts.saturatedCast(Long.MIN_VALUE));
}
private static void assertCastFails(long value) {
try {
Shorts.checkedCast(value);
fail("Cast to short should have failed: " + value);
} catch (IllegalArgumentException ex) {
assertTrue(value + " not found in exception text: " + ex.getMessage(),
ex.getMessage().contains(String.valueOf(value)));
}
}
public void testCompare() {
for (short x : VALUES) {
for (short y : VALUES) {
// Only compare the sign of the result of compareTo().
int expected = Short.valueOf(x).compareTo(y);
int actual = Shorts.compare(x, y);
if (expected == 0) {
assertEquals(x + ", " + y, expected, actual);
} else if (expected < 0) {
assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")",
actual < 0);
} else {
assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")",
actual > 0);
}
}
}
}
public void testContains() {
assertFalse(Shorts.contains(EMPTY, (short) 1));
assertFalse(Shorts.contains(ARRAY1, (short) 2));
assertFalse(Shorts.contains(ARRAY234, (short) 1));
assertTrue(Shorts.contains(new short[] {(short) -1}, (short) -1));
assertTrue(Shorts.contains(ARRAY234, (short) 2));
assertTrue(Shorts.contains(ARRAY234, (short) 3));
assertTrue(Shorts.contains(ARRAY234, (short) 4));
}
public void testIndexOf() {
assertEquals(-1, Shorts.indexOf(EMPTY, (short) 1));
assertEquals(-1, Shorts.indexOf(ARRAY1, (short) 2));
assertEquals(-1, Shorts.indexOf(ARRAY234, (short) 1));
assertEquals(0, Shorts.indexOf(
new short[] {(short) -1}, (short) -1));
assertEquals(0, Shorts.indexOf(ARRAY234, (short) 2));
assertEquals(1, Shorts.indexOf(ARRAY234, (short) 3));
assertEquals(2, Shorts.indexOf(ARRAY234, (short) 4));
assertEquals(1, Shorts.indexOf(
new short[] { (short) 2, (short) 3, (short) 2, (short) 3 },
(short) 3));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Shorts.indexOf(EMPTY, EMPTY));
assertEquals(0, Shorts.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Shorts.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Shorts.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Shorts.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Shorts.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Shorts.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Shorts.indexOf(
ARRAY234, new short[] { (short) 2, (short) 3 }));
assertEquals(1, Shorts.indexOf(
ARRAY234, new short[] { (short) 3, (short) 4 }));
assertEquals(1, Shorts.indexOf(ARRAY234, new short[] { (short) 3 }));
assertEquals(2, Shorts.indexOf(ARRAY234, new short[] { (short) 4 }));
assertEquals(1, Shorts.indexOf(new short[] { (short) 2, (short) 3,
(short) 3, (short) 3, (short) 3 },
new short[] { (short) 3 }
));
assertEquals(2, Shorts.indexOf(
new short[] { (short) 2, (short) 3, (short) 2,
(short) 3, (short) 4, (short) 2, (short) 3},
new short[] { (short) 2, (short) 3, (short) 4}
));
assertEquals(1, Shorts.indexOf(
new short[] { (short) 2, (short) 2, (short) 3,
(short) 4, (short) 2, (short) 3, (short) 4},
new short[] { (short) 2, (short) 3, (short) 4}
));
assertEquals(-1, Shorts.indexOf(
new short[] { (short) 4, (short) 3, (short) 2},
new short[] { (short) 2, (short) 3, (short) 4}
));
}
public void testLastIndexOf() {
assertEquals(-1, Shorts.lastIndexOf(EMPTY, (short) 1));
assertEquals(-1, Shorts.lastIndexOf(ARRAY1, (short) 2));
assertEquals(-1, Shorts.lastIndexOf(ARRAY234, (short) 1));
assertEquals(0, Shorts.lastIndexOf(
new short[] {(short) -1}, (short) -1));
assertEquals(0, Shorts.lastIndexOf(ARRAY234, (short) 2));
assertEquals(1, Shorts.lastIndexOf(ARRAY234, (short) 3));
assertEquals(2, Shorts.lastIndexOf(ARRAY234, (short) 4));
assertEquals(3, Shorts.lastIndexOf(
new short[] { (short) 2, (short) 3, (short) 2, (short) 3 },
(short) 3));
}
public void testMax_noArgs() {
try {
Shorts.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, Shorts.max(LEAST));
assertEquals(GREATEST, Shorts.max(GREATEST));
assertEquals((short) 9, Shorts.max(
(short) 8, (short) 6, (short) 7,
(short) 5, (short) 3, (short) 0, (short) 9));
}
public void testMin_noArgs() {
try {
Shorts.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, Shorts.min(LEAST));
assertEquals(GREATEST, Shorts.min(GREATEST));
assertEquals((short) 0, Shorts.min(
(short) 8, (short) 6, (short) 7,
(short) 5, (short) 3, (short) 0, (short) 9));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Shorts.concat()));
assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Shorts.concat(ARRAY1)));
assertNotSame(ARRAY1, Shorts.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Shorts.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new short[] {(short) 1, (short) 1, (short) 1},
Shorts.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new short[] {(short) 1, (short) 2, (short) 3, (short) 4},
Shorts.concat(ARRAY1, ARRAY234)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Shorts.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new short[] {(short) 1, (short) 0, (short) 0},
Shorts.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Shorts.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Shorts.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testJoin() {
assertEquals("", Shorts.join(",", EMPTY));
assertEquals("1", Shorts.join(",", ARRAY1));
assertEquals("1,2", Shorts.join(",", (short) 1, (short) 2));
assertEquals("123",
Shorts.join("", (short) 1, (short) 2, (short) 3));
}
public void testLexicographicalComparator() {
List<short[]> ordered = Arrays.asList(
new short[] {},
new short[] {LEAST},
new short[] {LEAST, LEAST},
new short[] {LEAST, (short) 1},
new short[] {(short) 1},
new short[] {(short) 1, LEAST},
new short[] {GREATEST, GREATEST - (short) 1},
new short[] {GREATEST, GREATEST},
new short[] {GREATEST, GREATEST, GREATEST});
Comparator<short[]> comparator = Shorts.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Short> none = Arrays.<Short>asList();
assertTrue(Arrays.equals(EMPTY, Shorts.toArray(none)));
List<Short> one = Arrays.asList((short) 1);
assertTrue(Arrays.equals(ARRAY1, Shorts.toArray(one)));
short[] array = {(short) 0, (short) 1, (short) 3};
List<Short> three = Arrays.asList((short) 0, (short) 1, (short) 3);
assertTrue(Arrays.equals(array, Shorts.toArray(three)));
assertTrue(Arrays.equals(array, Shorts.toArray(Shorts.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Short> list = Shorts.asList(VALUES).subList(0, i);
Collection<Short> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
short[] arr = Shorts.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Short> list = Arrays.asList((short) 0, (short) 1, null);
try {
Shorts.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testToArray_withConversion() {
short[] array = {(short) 0, (short) 1, (short) 2};
List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
List<Integer> ints = Arrays.asList(0, 1, 2);
List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
assertTrue(Arrays.equals(array, Shorts.toArray(bytes)));
assertTrue(Arrays.equals(array, Shorts.toArray(shorts)));
assertTrue(Arrays.equals(array, Shorts.toArray(ints)));
assertTrue(Arrays.equals(array, Shorts.toArray(floats)));
assertTrue(Arrays.equals(array, Shorts.toArray(longs)));
assertTrue(Arrays.equals(array, Shorts.toArray(doubles)));
}
public void testAsList_isAView() {
short[] array = {(short) 0, (short) 1};
List<Short> list = Shorts.asList(array);
list.set(0, (short) 2);
assertTrue(Arrays.equals(new short[] {(short) 2, (short) 1}, array));
array[1] = (short) 3;
assertEquals(Arrays.asList((short) 2, (short) 3), list);
}
public void testAsList_toArray_roundTrip() {
short[] array = { (short) 0, (short) 1, (short) 2 };
List<Short> list = Shorts.asList(array);
short[] newArray = Shorts.toArray(list);
// Make sure it returned a copy
list.set(0, (short) 4);
assertTrue(Arrays.equals(
new short[] { (short) 0, (short) 1, (short) 2 }, newArray));
newArray[1] = (short) 5;
assertEquals((short) 1, (short) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
short[] array = { (short) 0, (short) 1, (short) 2, (short) 3 };
List<Short> list = Shorts.asList(array);
assertTrue(Arrays.equals(new short[] { (short) 1, (short) 2 },
Shorts.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new short[] {},
Shorts.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Shorts.asList(EMPTY));
}
public void testStringConverter_convert() {
Converter<String, Short> converter = Shorts.stringConverter();
assertEquals((Short) (short) 1, converter.convert("1"));
assertEquals((Short) (short) 0, converter.convert("0"));
assertEquals((Short) (short) (-1), converter.convert("-1"));
assertEquals((Short) (short) 255, converter.convert("0xff"));
assertEquals((Short) (short) 255, converter.convert("0xFF"));
assertEquals((Short) (short) (-255), converter.convert("-0xFF"));
assertEquals((Short) (short) 255, converter.convert("#0000FF"));
assertEquals((Short) (short) 438, converter.convert("0666"));
}
public void testStringConverter_convertError() {
try {
Shorts.stringConverter().convert("notanumber");
fail();
} catch (NumberFormatException expected) {
}
}
public void testStringConverter_nullConversions() {
assertNull(Shorts.stringConverter().convert(null));
assertNull(Shorts.stringConverter().reverse().convert(null));
}
public void testStringConverter_reverse() {
Converter<String, Short> converter = Shorts.stringConverter();
assertEquals("1", converter.reverse().convert((short) 1));
assertEquals("0", converter.reverse().convert((short) 0));
assertEquals("-1", converter.reverse().convert((short) -1));
assertEquals("255", converter.reverse().convert((short) 0xff));
assertEquals("255", converter.reverse().convert((short) 0xFF));
assertEquals("-255", converter.reverse().convert((short) -0xFF));
assertEquals("438", converter.reverse().convert((short) 0666));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/ShortsTest.java | Java | asf20 | 14,686 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link SignedBytes}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class SignedBytesTest extends TestCase {
private static final byte[] EMPTY = {};
private static final byte[] ARRAY1 = {(byte) 1};
private static final byte LEAST = Byte.MIN_VALUE;
private static final byte GREATEST = Byte.MAX_VALUE;
private static final byte[] VALUES =
{LEAST, -1, 0, 1, GREATEST};
public void testCheckedCast() {
for (byte value : VALUES) {
assertEquals(value, SignedBytes.checkedCast((long) value));
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
assertCastFails(Long.MAX_VALUE);
assertCastFails(Long.MIN_VALUE);
}
public void testSaturatedCast() {
for (byte value : VALUES) {
assertEquals(value, SignedBytes.saturatedCast((long) value));
}
assertEquals(GREATEST, SignedBytes.saturatedCast(GREATEST + 1L));
assertEquals(LEAST, SignedBytes.saturatedCast(LEAST - 1L));
assertEquals(GREATEST, SignedBytes.saturatedCast(Long.MAX_VALUE));
assertEquals(LEAST, SignedBytes.saturatedCast(Long.MIN_VALUE));
}
private static void assertCastFails(long value) {
try {
SignedBytes.checkedCast(value);
fail("Cast to byte should have failed: " + value);
} catch (IllegalArgumentException ex) {
assertTrue(value + " not found in exception text: " + ex.getMessage(),
ex.getMessage().contains(String.valueOf(value)));
}
}
public void testCompare() {
for (byte x : VALUES) {
for (byte y : VALUES) {
// Only compare the sign of the result of compareTo().
int expected = Byte.valueOf(x).compareTo(y);
int actual = SignedBytes.compare(x, y);
if (expected == 0) {
assertEquals(x + ", " + y, expected, actual);
} else if (expected < 0) {
assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")",
actual < 0);
} else {
assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")",
actual > 0);
}
}
}
}
public void testMax_noArgs() {
try {
SignedBytes.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, SignedBytes.max(LEAST));
assertEquals(GREATEST, SignedBytes.max(GREATEST));
assertEquals((byte) 127, SignedBytes.max(
(byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
}
public void testMin_noArgs() {
try {
SignedBytes.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, SignedBytes.min(LEAST));
assertEquals(GREATEST, SignedBytes.min(GREATEST));
assertEquals((byte) -128, SignedBytes.min(
(byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1));
}
public void testJoin() {
assertEquals("", SignedBytes.join(",", EMPTY));
assertEquals("1", SignedBytes.join(",", ARRAY1));
assertEquals("1,2", SignedBytes.join(",", (byte) 1, (byte) 2));
assertEquals("123", SignedBytes.join("", (byte) 1, (byte) 2, (byte) 3));
assertEquals("-128,-1", SignedBytes.join(",", (byte) -128, (byte) -1));
}
public void testLexicographicalComparator() {
List<byte[]> ordered = Arrays.asList(
new byte[] {},
new byte[] {LEAST},
new byte[] {LEAST, LEAST},
new byte[] {LEAST, (byte) 1},
new byte[] {(byte) 1},
new byte[] {(byte) 1, LEAST},
new byte[] {GREATEST, GREATEST - (byte) 1},
new byte[] {GREATEST, GREATEST},
new byte[] {GREATEST, GREATEST, GREATEST});
Comparator<byte[]> comparator = SignedBytes.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/SignedBytesTest.java | Java | asf20 | 4,776 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Converter;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link Ints}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
@SuppressWarnings("cast") // redundant casts are intentional and harmless
public class IntsTest extends TestCase {
private static final int[] EMPTY = {};
private static final int[] ARRAY1 = {(int) 1};
private static final int[] ARRAY234
= {(int) 2, (int) 3, (int) 4};
private static final int LEAST = Integer.MIN_VALUE;
private static final int GREATEST = Integer.MAX_VALUE;
private static final int[] VALUES =
{ LEAST, (int) -1, (int) 0, (int) 1, GREATEST };
public void testHashCode() {
for (int value : VALUES) {
assertEquals(((Integer) value).hashCode(), Ints.hashCode(value));
}
}
public void testCheckedCast() {
for (int value : VALUES) {
assertEquals(value, Ints.checkedCast((long) value));
}
assertCastFails(GREATEST + 1L);
assertCastFails(LEAST - 1L);
assertCastFails(Long.MAX_VALUE);
assertCastFails(Long.MIN_VALUE);
}
public void testSaturatedCast() {
for (int value : VALUES) {
assertEquals(value, Ints.saturatedCast((long) value));
}
assertEquals(GREATEST, Ints.saturatedCast(GREATEST + 1L));
assertEquals(LEAST, Ints.saturatedCast(LEAST - 1L));
assertEquals(GREATEST, Ints.saturatedCast(Long.MAX_VALUE));
assertEquals(LEAST, Ints.saturatedCast(Long.MIN_VALUE));
}
private static void assertCastFails(long value) {
try {
Ints.checkedCast(value);
fail("Cast to int should have failed: " + value);
} catch (IllegalArgumentException ex) {
assertTrue(value + " not found in exception text: " + ex.getMessage(),
ex.getMessage().contains(String.valueOf(value)));
}
}
public void testCompare() {
for (int x : VALUES) {
for (int y : VALUES) {
// note: spec requires only that the sign is the same
assertEquals(x + ", " + y,
Integer.valueOf(x).compareTo(y),
Ints.compare(x, y));
}
}
}
public void testContains() {
assertFalse(Ints.contains(EMPTY, (int) 1));
assertFalse(Ints.contains(ARRAY1, (int) 2));
assertFalse(Ints.contains(ARRAY234, (int) 1));
assertTrue(Ints.contains(new int[] {(int) -1}, (int) -1));
assertTrue(Ints.contains(ARRAY234, (int) 2));
assertTrue(Ints.contains(ARRAY234, (int) 3));
assertTrue(Ints.contains(ARRAY234, (int) 4));
}
public void testIndexOf() {
assertEquals(-1, Ints.indexOf(EMPTY, (int) 1));
assertEquals(-1, Ints.indexOf(ARRAY1, (int) 2));
assertEquals(-1, Ints.indexOf(ARRAY234, (int) 1));
assertEquals(0, Ints.indexOf(
new int[] {(int) -1}, (int) -1));
assertEquals(0, Ints.indexOf(ARRAY234, (int) 2));
assertEquals(1, Ints.indexOf(ARRAY234, (int) 3));
assertEquals(2, Ints.indexOf(ARRAY234, (int) 4));
assertEquals(1, Ints.indexOf(
new int[] { (int) 2, (int) 3, (int) 2, (int) 3 },
(int) 3));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Ints.indexOf(EMPTY, EMPTY));
assertEquals(0, Ints.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Ints.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Ints.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Ints.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Ints.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Ints.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Ints.indexOf(
ARRAY234, new int[] { (int) 2, (int) 3 }));
assertEquals(1, Ints.indexOf(
ARRAY234, new int[] { (int) 3, (int) 4 }));
assertEquals(1, Ints.indexOf(ARRAY234, new int[] { (int) 3 }));
assertEquals(2, Ints.indexOf(ARRAY234, new int[] { (int) 4 }));
assertEquals(1, Ints.indexOf(new int[] { (int) 2, (int) 3,
(int) 3, (int) 3, (int) 3 },
new int[] { (int) 3 }
));
assertEquals(2, Ints.indexOf(
new int[] { (int) 2, (int) 3, (int) 2,
(int) 3, (int) 4, (int) 2, (int) 3},
new int[] { (int) 2, (int) 3, (int) 4}
));
assertEquals(1, Ints.indexOf(
new int[] { (int) 2, (int) 2, (int) 3,
(int) 4, (int) 2, (int) 3, (int) 4},
new int[] { (int) 2, (int) 3, (int) 4}
));
assertEquals(-1, Ints.indexOf(
new int[] { (int) 4, (int) 3, (int) 2},
new int[] { (int) 2, (int) 3, (int) 4}
));
}
public void testLastIndexOf() {
assertEquals(-1, Ints.lastIndexOf(EMPTY, (int) 1));
assertEquals(-1, Ints.lastIndexOf(ARRAY1, (int) 2));
assertEquals(-1, Ints.lastIndexOf(ARRAY234, (int) 1));
assertEquals(0, Ints.lastIndexOf(
new int[] {(int) -1}, (int) -1));
assertEquals(0, Ints.lastIndexOf(ARRAY234, (int) 2));
assertEquals(1, Ints.lastIndexOf(ARRAY234, (int) 3));
assertEquals(2, Ints.lastIndexOf(ARRAY234, (int) 4));
assertEquals(3, Ints.lastIndexOf(
new int[] { (int) 2, (int) 3, (int) 2, (int) 3 },
(int) 3));
}
public void testMax_noArgs() {
try {
Ints.max();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMax() {
assertEquals(LEAST, Ints.max(LEAST));
assertEquals(GREATEST, Ints.max(GREATEST));
assertEquals((int) 9, Ints.max(
(int) 8, (int) 6, (int) 7,
(int) 5, (int) 3, (int) 0, (int) 9));
}
public void testMin_noArgs() {
try {
Ints.min();
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMin() {
assertEquals(LEAST, Ints.min(LEAST));
assertEquals(GREATEST, Ints.min(GREATEST));
assertEquals((int) 0, Ints.min(
(int) 8, (int) 6, (int) 7,
(int) 5, (int) 3, (int) 0, (int) 9));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Ints.concat()));
assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Ints.concat(ARRAY1)));
assertNotSame(ARRAY1, Ints.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Ints.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new int[] {(int) 1, (int) 1, (int) 1},
Ints.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new int[] {(int) 1, (int) 2, (int) 3, (int) 4},
Ints.concat(ARRAY1, ARRAY234)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Ints.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new int[] {(int) 1, (int) 0, (int) 0},
Ints.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Ints.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Ints.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testJoin() {
assertEquals("", Ints.join(",", EMPTY));
assertEquals("1", Ints.join(",", ARRAY1));
assertEquals("1,2", Ints.join(",", (int) 1, (int) 2));
assertEquals("123",
Ints.join("", (int) 1, (int) 2, (int) 3));
}
public void testLexicographicalComparator() {
List<int[]> ordered = Arrays.asList(
new int[] {},
new int[] {LEAST},
new int[] {LEAST, LEAST},
new int[] {LEAST, (int) 1},
new int[] {(int) 1},
new int[] {(int) 1, LEAST},
new int[] {GREATEST, GREATEST - (int) 1},
new int[] {GREATEST, GREATEST},
new int[] {GREATEST, GREATEST, GREATEST});
Comparator<int[]> comparator = Ints.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Integer> none = Arrays.<Integer>asList();
assertTrue(Arrays.equals(EMPTY, Ints.toArray(none)));
List<Integer> one = Arrays.asList((int) 1);
assertTrue(Arrays.equals(ARRAY1, Ints.toArray(one)));
int[] array = {(int) 0, (int) 1, (int) 0xdeadbeef};
List<Integer> three = Arrays.asList((int) 0, (int) 1, (int) 0xdeadbeef);
assertTrue(Arrays.equals(array, Ints.toArray(three)));
assertTrue(Arrays.equals(array, Ints.toArray(Ints.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Integer> list = Ints.asList(VALUES).subList(0, i);
Collection<Integer> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
int[] arr = Ints.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Integer> list = Arrays.asList((int) 0, (int) 1, null);
try {
Ints.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testToArray_withConversion() {
int[] array = {0, 1, 2};
List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
List<Integer> ints = Arrays.asList(0, 1, 2);
List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
assertTrue(Arrays.equals(array, Ints.toArray(bytes)));
assertTrue(Arrays.equals(array, Ints.toArray(shorts)));
assertTrue(Arrays.equals(array, Ints.toArray(ints)));
assertTrue(Arrays.equals(array, Ints.toArray(floats)));
assertTrue(Arrays.equals(array, Ints.toArray(longs)));
assertTrue(Arrays.equals(array, Ints.toArray(doubles)));
}
public void testAsList_isAView() {
int[] array = {(int) 0, (int) 1};
List<Integer> list = Ints.asList(array);
list.set(0, (int) 2);
assertTrue(Arrays.equals(new int[] {(int) 2, (int) 1}, array));
array[1] = (int) 3;
assertEquals(Arrays.asList((int) 2, (int) 3), list);
}
public void testAsList_toArray_roundTrip() {
int[] array = { (int) 0, (int) 1, (int) 2 };
List<Integer> list = Ints.asList(array);
int[] newArray = Ints.toArray(list);
// Make sure it returned a copy
list.set(0, (int) 4);
assertTrue(Arrays.equals(
new int[] { (int) 0, (int) 1, (int) 2 }, newArray));
newArray[1] = (int) 5;
assertEquals((int) 1, (int) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
int[] array = { (int) 0, (int) 1, (int) 2, (int) 3 };
List<Integer> list = Ints.asList(array);
assertTrue(Arrays.equals(new int[] { (int) 1, (int) 2 },
Ints.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new int[] {},
Ints.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Ints.asList(EMPTY));
}
public void testStringConverter_convert() {
Converter<String, Integer> converter = Ints.stringConverter();
assertEquals((Integer) 1, converter.convert("1"));
assertEquals((Integer) 0, converter.convert("0"));
assertEquals((Integer) (-1), converter.convert("-1"));
assertEquals((Integer) 255, converter.convert("0xff"));
assertEquals((Integer) 255, converter.convert("0xFF"));
assertEquals((Integer) (-255), converter.convert("-0xFF"));
assertEquals((Integer) 255, converter.convert("#0000FF"));
assertEquals((Integer) 438, converter.convert("0666"));
}
public void testStringConverter_convertError() {
try {
Ints.stringConverter().convert("notanumber");
fail();
} catch (NumberFormatException expected) {
}
}
public void testStringConverter_nullConversions() {
assertNull(Ints.stringConverter().convert(null));
assertNull(Ints.stringConverter().reverse().convert(null));
}
public void testStringConverter_reverse() {
Converter<String, Integer> converter = Ints.stringConverter();
assertEquals("1", converter.reverse().convert(1));
assertEquals("0", converter.reverse().convert(0));
assertEquals("-1", converter.reverse().convert(-1));
assertEquals("255", converter.reverse().convert(0xff));
assertEquals("255", converter.reverse().convert(0xFF));
assertEquals("-255", converter.reverse().convert(-0xFF));
assertEquals("438", converter.reverse().convert(0666));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/IntsTest.java | Java | asf20 | 13,652 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Bytes#asList(byte[])}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class ByteArrayAsListTest extends TestCase {
private static List<Byte> asList(Byte[] values) {
byte[] temp = new byte[values.length];
for (int i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Bytes.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class BytesAsListGenerator extends TestByteListGenerator {
@Override protected List<Byte> create(Byte[] elements) {
return asList(elements);
}
}
public static final class BytesAsListHeadSubListGenerator extends TestByteListGenerator {
@Override protected List<Byte> create(Byte[] elements) {
Byte[] suffix = {Byte.MIN_VALUE, Byte.MAX_VALUE};
Byte[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class BytesAsListTailSubListGenerator extends TestByteListGenerator {
@Override protected List<Byte> create(Byte[] elements) {
Byte[] prefix = {(byte) 86, (byte) 99};
Byte[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class BytesAsListMiddleSubListGenerator extends TestByteListGenerator {
@Override protected List<Byte> create(Byte[] elements) {
Byte[] prefix = {Byte.MIN_VALUE, Byte.MAX_VALUE};
Byte[] suffix = {(byte) 86, (byte) 99};
Byte[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Byte[] concat(Byte[] left, Byte[] right) {
Byte[] result = new Byte[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestByteListGenerator
implements TestListGenerator<Byte> {
@Override
public SampleElements<Byte> samples() {
return new SampleBytes();
}
@Override
public List<Byte> create(Object... elements) {
Byte[] array = new Byte[elements.length];
int i = 0;
for (Object e : elements) {
array[i++] = (Byte) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Byte> create(Byte[] elements);
@Override
public Byte[] createArray(int length) {
return new Byte[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Byte> order(List<Byte> insertionOrder) {
return insertionOrder;
}
}
public static class SampleBytes extends SampleElements<Byte> {
public SampleBytes() {
super((byte) 0, (byte) 1, (byte) 2, (byte) 3, (byte) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/ByteArrayAsListTest.java | Java | asf20 | 4,068 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Unit test for {@link Booleans}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class BooleansTest extends TestCase {
private static final boolean[] EMPTY = {};
private static final boolean[] ARRAY_FALSE = {false};
private static final boolean[] ARRAY_TRUE = {true};
private static final boolean[] ARRAY_FALSE_FALSE = {false, false};
private static final boolean[] ARRAY_FALSE_TRUE = {false, true};
private static final boolean[] VALUES = {false, true};
public void testHashCode() {
assertEquals(Boolean.TRUE.hashCode(), Booleans.hashCode(true));
assertEquals(Boolean.FALSE.hashCode(), Booleans.hashCode(false));
}
public void testCompare() {
for (boolean x : VALUES) {
for (boolean y : VALUES) {
// note: spec requires only that the sign is the same
assertEquals(x + ", " + y,
Boolean.valueOf(x).compareTo(y),
Booleans.compare(x, y));
}
}
}
public void testContains() {
assertFalse(Booleans.contains(EMPTY, false));
assertFalse(Booleans.contains(ARRAY_FALSE, true));
assertTrue(Booleans.contains(ARRAY_FALSE, false));
assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, false));
assertTrue(Booleans.contains(ARRAY_FALSE_TRUE, true));
}
public void testIndexOf() {
assertEquals(-1, Booleans.indexOf(EMPTY, ARRAY_FALSE));
assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE_TRUE));
assertEquals(0, Booleans.indexOf(ARRAY_FALSE_FALSE, ARRAY_FALSE));
assertEquals(0, Booleans.indexOf(ARRAY_FALSE, ARRAY_FALSE));
assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_FALSE));
assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, ARRAY_TRUE));
assertEquals(0, Booleans.indexOf(ARRAY_TRUE, new boolean[0]));
}
public void testIndexOf_arrays() {
assertEquals(-1, Booleans.indexOf(EMPTY, false));
assertEquals(-1, Booleans.indexOf(ARRAY_FALSE, true));
assertEquals(-1, Booleans.indexOf(ARRAY_FALSE_FALSE, true));
assertEquals(0, Booleans.indexOf(ARRAY_FALSE, false));
assertEquals(0, Booleans.indexOf(ARRAY_FALSE_TRUE, false));
assertEquals(1, Booleans.indexOf(ARRAY_FALSE_TRUE, true));
assertEquals(2, Booleans.indexOf(new boolean[] {false, false, true}, true));
}
public void testLastIndexOf() {
assertEquals(-1, Booleans.lastIndexOf(EMPTY, false));
assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE, true));
assertEquals(-1, Booleans.lastIndexOf(ARRAY_FALSE_FALSE, true));
assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE, false));
assertEquals(0, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, false));
assertEquals(1, Booleans.lastIndexOf(ARRAY_FALSE_TRUE, true));
assertEquals(2, Booleans.lastIndexOf(new boolean[] {false, true, true}, true));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Booleans.concat()));
assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Booleans.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE)));
assertNotSame(ARRAY_FALSE, Booleans.concat(ARRAY_FALSE));
assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.concat(EMPTY, ARRAY_FALSE, EMPTY)));
assertTrue(Arrays.equals(
new boolean[] {false, false, false},
Booleans.concat(ARRAY_FALSE, ARRAY_FALSE, ARRAY_FALSE)));
assertTrue(Arrays.equals(
new boolean[] {false, false, true},
Booleans.concat(ARRAY_FALSE, ARRAY_FALSE_TRUE)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Booleans.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 0, 1));
assertSame(ARRAY_FALSE, Booleans.ensureCapacity(ARRAY_FALSE, 1, 1));
assertTrue(Arrays.equals(
new boolean[] {true, false, false},
Booleans.ensureCapacity(new boolean[] {true}, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Booleans.ensureCapacity(ARRAY_FALSE, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Booleans.ensureCapacity(ARRAY_FALSE, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testJoin() {
assertEquals("", Booleans.join(",", EMPTY));
assertEquals("false", Booleans.join(",", ARRAY_FALSE));
assertEquals("false,true", Booleans.join(",", false, true));
assertEquals("falsetruefalse",
Booleans.join("", false, true, false));
}
public void testLexicographicalComparator() {
List<boolean[]> ordered = Arrays.asList(
new boolean[] {},
new boolean[] {false},
new boolean[] {false, false},
new boolean[] {false, true},
new boolean[] {true},
new boolean[] {true, false},
new boolean[] {true, true},
new boolean[] {true, true, true});
Comparator<boolean[]> comparator = Booleans.lexicographicalComparator();
Helpers.testComparator(comparator, ordered);
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Boolean> none = Arrays.<Boolean>asList();
assertTrue(Arrays.equals(EMPTY, Booleans.toArray(none)));
List<Boolean> one = Arrays.asList(false);
assertTrue(Arrays.equals(ARRAY_FALSE, Booleans.toArray(one)));
boolean[] array = {false, false, true};
List<Boolean> three = Arrays.asList(false, false, true);
assertTrue(Arrays.equals(array, Booleans.toArray(three)));
assertTrue(Arrays.equals(array, Booleans.toArray(Booleans.asList(array))));
}
public void testToArray_threadSafe() {
// Only for booleans, we lengthen VALUES
boolean[] VALUES = BooleansTest.VALUES;
VALUES = Booleans.concat(VALUES, VALUES);
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Boolean> list = Booleans.asList(VALUES).subList(0, i);
Collection<Boolean> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
boolean[] arr = Booleans.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Boolean> list = Arrays.asList(false, true, null);
try {
Booleans.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testAsListIsEmpty() {
assertTrue(Booleans.asList(EMPTY).isEmpty());
assertFalse(Booleans.asList(ARRAY_FALSE).isEmpty());
}
public void testAsListSize() {
assertEquals(0, Booleans.asList(EMPTY).size());
assertEquals(1, Booleans.asList(ARRAY_FALSE).size());
assertEquals(2, Booleans.asList(ARRAY_FALSE_TRUE).size());
}
public void testAsListIndexOf() {
assertEquals(-1, Booleans.asList(EMPTY).indexOf("wrong type"));
assertEquals(-1, Booleans.asList(EMPTY).indexOf(true));
assertEquals(-1, Booleans.asList(ARRAY_FALSE).indexOf(true));
assertEquals(0, Booleans.asList(ARRAY_FALSE).indexOf(false));
assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).indexOf(true));
}
public void testAsListLastIndexOf() {
assertEquals(-1, Booleans.asList(EMPTY).indexOf("wrong type"));
assertEquals(-1, Booleans.asList(EMPTY).indexOf(true));
assertEquals(-1, Booleans.asList(ARRAY_FALSE).lastIndexOf(true));
assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true));
assertEquals(1, Booleans.asList(ARRAY_FALSE_FALSE).lastIndexOf(false));
}
public void testAsListContains() {
assertFalse(Booleans.asList(EMPTY).contains("wrong type"));
assertFalse(Booleans.asList(EMPTY).contains(true));
assertFalse(Booleans.asList(ARRAY_FALSE).contains(true));
assertTrue(Booleans.asList(ARRAY_TRUE).contains(true));
assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(false));
assertTrue(Booleans.asList(ARRAY_FALSE_TRUE).contains(true));
}
public void testAsListEquals() {
assertEquals(Booleans.asList(EMPTY), Collections.emptyList());
assertEquals(Booleans.asList(ARRAY_FALSE), Booleans.asList(ARRAY_FALSE));
assertFalse(Booleans.asList(ARRAY_FALSE).equals(ARRAY_FALSE));
assertFalse(Booleans.asList(ARRAY_FALSE).equals(null));
assertFalse(Booleans.asList(ARRAY_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)));
assertFalse(Booleans.asList(ARRAY_FALSE_FALSE).equals(Booleans.asList(ARRAY_FALSE_TRUE)));
assertEquals(1, Booleans.asList(ARRAY_FALSE_TRUE).lastIndexOf(true));
List<Boolean> reference = Booleans.asList(ARRAY_FALSE);
assertEquals(Booleans.asList(ARRAY_FALSE), reference);
assertEquals(reference, reference);
}
public void testAsListHashcode() {
assertEquals(1, Booleans.asList(EMPTY).hashCode());
assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), Booleans.asList(ARRAY_FALSE).hashCode());
List<Boolean> reference = Booleans.asList(ARRAY_FALSE);
assertEquals(Booleans.asList(ARRAY_FALSE).hashCode(), reference.hashCode());
}
public void testAsListToString() {
assertEquals("[false]", Booleans.asList(ARRAY_FALSE).toString());
assertEquals("[false, true]", Booleans.asList(ARRAY_FALSE_TRUE).toString());
}
public void testAsListSet() {
List<Boolean> list = Booleans.asList(ARRAY_FALSE);
assertFalse(list.set(0, true));
assertTrue(list.set(0, false));
try {
list.set(0, null);
fail();
} catch (NullPointerException expected) {
}
try {
list.set(1, true);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testCountTrue() {
assertEquals(0, Booleans.countTrue());
assertEquals(0, Booleans.countTrue(false));
assertEquals(1, Booleans.countTrue(true));
assertEquals(3, Booleans.countTrue(false, true, false, true, false, true));
assertEquals(1, Booleans.countTrue(false, false, true, false, false));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/BooleansTest.java | Java | asf20 | 10,972 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.SampleElements;
import com.google.common.collect.testing.TestListGenerator;
import junit.framework.TestCase;
import java.util.List;
/**
* Test suite covering {@link Shorts#asList(short[])}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class ShortArrayAsListTest extends TestCase {
private static List<Short> asList(Short[] values) {
short[] temp = new short[values.length];
for (short i = 0; i < values.length; i++) {
temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize).
}
return Shorts.asList(temp);
}
// Test generators. To let the GWT test suite generator access them, they need to be
// public named classes with a public default constructor.
public static final class ShortsAsListGenerator extends TestShortListGenerator {
@Override protected List<Short> create(Short[] elements) {
return asList(elements);
}
}
public static final class ShortsAsListHeadSubListGenerator extends TestShortListGenerator {
@Override protected List<Short> create(Short[] elements) {
Short[] suffix = {Short.MIN_VALUE, Short.MAX_VALUE};
Short[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final class ShortsAsListTailSubListGenerator extends TestShortListGenerator {
@Override protected List<Short> create(Short[] elements) {
Short[] prefix = {(short) 86, (short) 99};
Short[] all = concat(prefix, elements);
return asList(all).subList(2, elements.length + 2);
}
}
public static final class ShortsAsListMiddleSubListGenerator extends TestShortListGenerator {
@Override protected List<Short> create(Short[] elements) {
Short[] prefix = {Short.MIN_VALUE, Short.MAX_VALUE};
Short[] suffix = {(short) 86, (short) 99};
Short[] all = concat(concat(prefix, elements), suffix);
return asList(all).subList(2, elements.length + 2);
}
}
private static Short[] concat(Short[] left, Short[] right) {
Short[] result = new Short[left.length + right.length];
System.arraycopy(left, 0, result, 0, left.length);
System.arraycopy(right, 0, result, left.length, right.length);
return result;
}
public static abstract class TestShortListGenerator
implements TestListGenerator<Short> {
@Override
public SampleElements<Short> samples() {
return new SampleShorts();
}
@Override
public List<Short> create(Object... elements) {
Short[] array = new Short[elements.length];
short i = 0;
for (Object e : elements) {
array[i++] = (Short) e;
}
return create(array);
}
/**
* Creates a new collection containing the given elements; implement this
* method instead of {@link #create(Object...)}.
*/
protected abstract List<Short> create(Short[] elements);
@Override
public Short[] createArray(int length) {
return new Short[length];
}
/** Returns the original element list, unchanged. */
@Override
public List<Short> order(List<Short> insertionOrder) {
return insertionOrder;
}
}
public static class SampleShorts extends SampleElements<Short> {
public SampleShorts() {
super((short) 0, (short) 1, (short) 2, (short) 3, (short) 4);
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/ShortArrayAsListTest.java | Java | asf20 | 4,138 |
/*
* Copyright (C) 2008 The Guava 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.common.primitives;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Unit test for {@link Bytes}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class BytesTest extends TestCase {
private static final byte[] EMPTY = {};
private static final byte[] ARRAY1 = {(byte) 1};
private static final byte[] ARRAY234
= {(byte) 2, (byte) 3, (byte) 4};
private static final byte[] VALUES =
{ Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE };
public void testHashCode() {
for (byte value : VALUES) {
assertEquals(((Byte) value).hashCode(), Bytes.hashCode(value));
}
}
public void testContains() {
assertFalse(Bytes.contains(EMPTY, (byte) 1));
assertFalse(Bytes.contains(ARRAY1, (byte) 2));
assertFalse(Bytes.contains(ARRAY234, (byte) 1));
assertTrue(Bytes.contains(new byte[] {(byte) -1}, (byte) -1));
assertTrue(Bytes.contains(ARRAY234, (byte) 2));
assertTrue(Bytes.contains(ARRAY234, (byte) 3));
assertTrue(Bytes.contains(ARRAY234, (byte) 4));
}
public void testIndexOf() {
assertEquals(-1, Bytes.indexOf(EMPTY, (byte) 1));
assertEquals(-1, Bytes.indexOf(ARRAY1, (byte) 2));
assertEquals(-1, Bytes.indexOf(ARRAY234, (byte) 1));
assertEquals(0, Bytes.indexOf(
new byte[] {(byte) -1}, (byte) -1));
assertEquals(0, Bytes.indexOf(ARRAY234, (byte) 2));
assertEquals(1, Bytes.indexOf(ARRAY234, (byte) 3));
assertEquals(2, Bytes.indexOf(ARRAY234, (byte) 4));
assertEquals(1, Bytes.indexOf(
new byte[] { (byte) 2, (byte) 3, (byte) 2, (byte) 3 },
(byte) 3));
}
public void testIndexOf_arrayTarget() {
assertEquals(0, Bytes.indexOf(EMPTY, EMPTY));
assertEquals(0, Bytes.indexOf(ARRAY234, EMPTY));
assertEquals(-1, Bytes.indexOf(EMPTY, ARRAY234));
assertEquals(-1, Bytes.indexOf(ARRAY234, ARRAY1));
assertEquals(-1, Bytes.indexOf(ARRAY1, ARRAY234));
assertEquals(0, Bytes.indexOf(ARRAY1, ARRAY1));
assertEquals(0, Bytes.indexOf(ARRAY234, ARRAY234));
assertEquals(0, Bytes.indexOf(
ARRAY234, new byte[] { (byte) 2, (byte) 3 }));
assertEquals(1, Bytes.indexOf(
ARRAY234, new byte[] { (byte) 3, (byte) 4 }));
assertEquals(1, Bytes.indexOf(ARRAY234, new byte[] { (byte) 3 }));
assertEquals(2, Bytes.indexOf(ARRAY234, new byte[] { (byte) 4 }));
assertEquals(1, Bytes.indexOf(new byte[] { (byte) 2, (byte) 3,
(byte) 3, (byte) 3, (byte) 3 },
new byte[] { (byte) 3 }
));
assertEquals(2, Bytes.indexOf(
new byte[] { (byte) 2, (byte) 3, (byte) 2,
(byte) 3, (byte) 4, (byte) 2, (byte) 3},
new byte[] { (byte) 2, (byte) 3, (byte) 4}
));
assertEquals(1, Bytes.indexOf(
new byte[] { (byte) 2, (byte) 2, (byte) 3,
(byte) 4, (byte) 2, (byte) 3, (byte) 4},
new byte[] { (byte) 2, (byte) 3, (byte) 4}
));
assertEquals(-1, Bytes.indexOf(
new byte[] { (byte) 4, (byte) 3, (byte) 2},
new byte[] { (byte) 2, (byte) 3, (byte) 4}
));
}
public void testLastIndexOf() {
assertEquals(-1, Bytes.lastIndexOf(EMPTY, (byte) 1));
assertEquals(-1, Bytes.lastIndexOf(ARRAY1, (byte) 2));
assertEquals(-1, Bytes.lastIndexOf(ARRAY234, (byte) 1));
assertEquals(0, Bytes.lastIndexOf(
new byte[] {(byte) -1}, (byte) -1));
assertEquals(0, Bytes.lastIndexOf(ARRAY234, (byte) 2));
assertEquals(1, Bytes.lastIndexOf(ARRAY234, (byte) 3));
assertEquals(2, Bytes.lastIndexOf(ARRAY234, (byte) 4));
assertEquals(3, Bytes.lastIndexOf(
new byte[] { (byte) 2, (byte) 3, (byte) 2, (byte) 3 },
(byte) 3));
}
public void testConcat() {
assertTrue(Arrays.equals(EMPTY, Bytes.concat()));
assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY)));
assertTrue(Arrays.equals(EMPTY, Bytes.concat(EMPTY, EMPTY, EMPTY)));
assertTrue(Arrays.equals(ARRAY1, Bytes.concat(ARRAY1)));
assertNotSame(ARRAY1, Bytes.concat(ARRAY1));
assertTrue(Arrays.equals(ARRAY1, Bytes.concat(EMPTY, ARRAY1, EMPTY)));
assertTrue(Arrays.equals(
new byte[] {(byte) 1, (byte) 1, (byte) 1},
Bytes.concat(ARRAY1, ARRAY1, ARRAY1)));
assertTrue(Arrays.equals(
new byte[] {(byte) 1, (byte) 2, (byte) 3, (byte) 4},
Bytes.concat(ARRAY1, ARRAY234)));
}
public void testEnsureCapacity() {
assertSame(EMPTY, Bytes.ensureCapacity(EMPTY, 0, 1));
assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 0, 1));
assertSame(ARRAY1, Bytes.ensureCapacity(ARRAY1, 1, 1));
assertTrue(Arrays.equals(
new byte[] {(byte) 1, (byte) 0, (byte) 0},
Bytes.ensureCapacity(ARRAY1, 2, 1)));
}
public void testEnsureCapacity_fail() {
try {
Bytes.ensureCapacity(ARRAY1, -1, 1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// notice that this should even fail when no growth was needed
Bytes.ensureCapacity(ARRAY1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testToArray() {
// need explicit type parameter to avoid javac warning!?
List<Byte> none = Arrays.<Byte>asList();
assertTrue(Arrays.equals(EMPTY, Bytes.toArray(none)));
List<Byte> one = Arrays.asList((byte) 1);
assertTrue(Arrays.equals(ARRAY1, Bytes.toArray(one)));
byte[] array = {(byte) 0, (byte) 1, (byte) 0x55};
List<Byte> three = Arrays.asList((byte) 0, (byte) 1, (byte) 0x55);
assertTrue(Arrays.equals(array, Bytes.toArray(three)));
assertTrue(Arrays.equals(array, Bytes.toArray(Bytes.asList(array))));
}
public void testToArray_threadSafe() {
for (int delta : new int[] { +1, 0, -1 }) {
for (int i = 0; i < VALUES.length; i++) {
List<Byte> list = Bytes.asList(VALUES).subList(0, i);
Collection<Byte> misleadingSize =
Helpers.misleadingSizeCollection(delta);
misleadingSize.addAll(list);
byte[] arr = Bytes.toArray(misleadingSize);
assertEquals(i, arr.length);
for (int j = 0; j < i; j++) {
assertEquals(VALUES[j], arr[j]);
}
}
}
}
public void testToArray_withNull() {
List<Byte> list = Arrays.asList((byte) 0, (byte) 1, null);
try {
Bytes.toArray(list);
fail();
} catch (NullPointerException expected) {
}
}
public void testToArray_withConversion() {
byte[] array = {(byte) 0, (byte) 1, (byte) 2};
List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2);
List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2);
List<Integer> ints = Arrays.asList(0, 1, 2);
List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2);
List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2);
List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2);
assertTrue(Arrays.equals(array, Bytes.toArray(bytes)));
assertTrue(Arrays.equals(array, Bytes.toArray(shorts)));
assertTrue(Arrays.equals(array, Bytes.toArray(ints)));
assertTrue(Arrays.equals(array, Bytes.toArray(floats)));
assertTrue(Arrays.equals(array, Bytes.toArray(longs)));
assertTrue(Arrays.equals(array, Bytes.toArray(doubles)));
}
public void testAsList_isAView() {
byte[] array = {(byte) 0, (byte) 1};
List<Byte> list = Bytes.asList(array);
list.set(0, (byte) 2);
assertTrue(Arrays.equals(new byte[] {(byte) 2, (byte) 1}, array));
array[1] = (byte) 3;
assertEquals(Arrays.asList((byte) 2, (byte) 3), list);
}
public void testAsList_toArray_roundTrip() {
byte[] array = { (byte) 0, (byte) 1, (byte) 2 };
List<Byte> list = Bytes.asList(array);
byte[] newArray = Bytes.toArray(list);
// Make sure it returned a copy
list.set(0, (byte) 4);
assertTrue(Arrays.equals(
new byte[] { (byte) 0, (byte) 1, (byte) 2 }, newArray));
newArray[1] = (byte) 5;
assertEquals((byte) 1, (byte) list.get(1));
}
// This test stems from a real bug found by andrewk
public void testAsList_subList_toArray_roundTrip() {
byte[] array = { (byte) 0, (byte) 1, (byte) 2, (byte) 3 };
List<Byte> list = Bytes.asList(array);
assertTrue(Arrays.equals(new byte[] { (byte) 1, (byte) 2 },
Bytes.toArray(list.subList(1, 3))));
assertTrue(Arrays.equals(new byte[] {},
Bytes.toArray(list.subList(2, 2))));
}
public void testAsListEmpty() {
assertSame(Collections.emptyList(), Bytes.asList(EMPTY));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/primitives/super/com/google/common/primitives/BytesTest.java | Java | asf20 | 9,272 |
/*
* Copyright (C) 2008 The Guava 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.common.testing;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
/**
* Unit test for {@link FakeTicker}.
*
* @author Jige Yu
*/
@GwtCompatible(emulated = true)
public class FakeTickerTest extends TestCase {
public void testAdvance() {
FakeTicker ticker = new FakeTicker();
assertEquals(0, ticker.read());
assertSame(ticker, ticker.advance(10));
assertEquals(10, ticker.read());
ticker.advance(1, TimeUnit.MILLISECONDS);
assertEquals(1000010L, ticker.read());
}
public void testAutoIncrementStep_returnsSameInstance() {
FakeTicker ticker = new FakeTicker();
assertSame(ticker, ticker.setAutoIncrementStep(10, TimeUnit.NANOSECONDS));
}
public void testAutoIncrementStep_nanos() {
FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS);
assertEquals(0, ticker.read());
assertEquals(10, ticker.read());
assertEquals(20, ticker.read());
}
public void testAutoIncrementStep_millis() {
FakeTicker ticker = new FakeTicker().setAutoIncrementStep(1, TimeUnit.MILLISECONDS);
assertEquals(0, ticker.read());
assertEquals(1000000, ticker.read());
assertEquals(2000000, ticker.read());
}
public void testAutoIncrementStep_seconds() {
FakeTicker ticker = new FakeTicker().setAutoIncrementStep(3, TimeUnit.SECONDS);
assertEquals(0, ticker.read());
assertEquals(3000000000L, ticker.read());
assertEquals(6000000000L, ticker.read());
}
public void testAutoIncrementStep_resetToZero() {
FakeTicker ticker = new FakeTicker().setAutoIncrementStep(10, TimeUnit.NANOSECONDS);
assertEquals(0, ticker.read());
assertEquals(10, ticker.read());
assertEquals(20, ticker.read());
for (TimeUnit timeUnit : EnumSet.allOf(TimeUnit.class)) {
ticker.setAutoIncrementStep(0, timeUnit);
assertEquals(
"Expected no auto-increment when setting autoIncrementStep to 0 " + timeUnit,
30, ticker.read());
}
}
public void testAutoIncrement_negative() {
FakeTicker ticker = new FakeTicker();
try {
ticker.setAutoIncrementStep(-1, TimeUnit.NANOSECONDS);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/testing/super/com/google/common/testing/FakeTickerTest.java | Java | asf20 | 2,963 |
/*
* Copyright (C) 2011 The Guava 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.common.testing;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Methods factored out so that they can be emulated differently in GWT.
*
* @author Chris Povirk
*/
final class Platform {
/**
* Serializes and deserializes the specified object (a no-op under GWT).
*/
@SuppressWarnings("unchecked")
static <T> T reserialize(T object) {
return checkNotNull(object);
}
private Platform() {}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/testing/super/com/google/common/testing/Platform.java | Java | asf20 | 1,058 |
/*
* Copyright (C) 2006 The Guava 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.common.base;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.LOWER_HYPHEN;
import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
/**
* Unit test for {@link CaseFormat}.
*
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
public class CaseFormatTest extends TestCase {
public void testIdentity() {
for (CaseFormat from : CaseFormat.values()) {
assertSame(from + " to " + from, "foo", from.to(from, "foo"));
for (CaseFormat to : CaseFormat.values()) {
assertEquals(from + " to " + to, "", from.to(to, ""));
assertEquals(from + " to " + to, " ", from.to(to, " "));
}
}
}
public void testLowerHyphenToLowerHyphen() {
assertEquals("foo", LOWER_HYPHEN.to(LOWER_HYPHEN, "foo"));
assertEquals("foo-bar", LOWER_HYPHEN.to(LOWER_HYPHEN, "foo-bar"));
}
public void testLowerHyphenToLowerUnderscore() {
assertEquals("foo", LOWER_HYPHEN.to(LOWER_UNDERSCORE, "foo"));
assertEquals("foo_bar", LOWER_HYPHEN.to(LOWER_UNDERSCORE, "foo-bar"));
}
public void testLowerHyphenToLowerCamel() {
assertEquals("foo", LOWER_HYPHEN.to(LOWER_CAMEL, "foo"));
assertEquals("fooBar", LOWER_HYPHEN.to(LOWER_CAMEL, "foo-bar"));
}
public void testLowerHyphenToUpperCamel() {
assertEquals("Foo", LOWER_HYPHEN.to(UPPER_CAMEL, "foo"));
assertEquals("FooBar", LOWER_HYPHEN.to(UPPER_CAMEL, "foo-bar"));
}
public void testLowerHyphenToUpperUnderscore() {
assertEquals("FOO", LOWER_HYPHEN.to(UPPER_UNDERSCORE, "foo"));
assertEquals("FOO_BAR", LOWER_HYPHEN.to(UPPER_UNDERSCORE, "foo-bar"));
}
public void testLowerUnderscoreToLowerHyphen() {
assertEquals("foo", LOWER_UNDERSCORE.to(LOWER_HYPHEN, "foo"));
assertEquals("foo-bar", LOWER_UNDERSCORE.to(LOWER_HYPHEN, "foo_bar"));
}
public void testLowerUnderscoreToLowerUnderscore() {
assertEquals("foo", LOWER_UNDERSCORE.to(LOWER_UNDERSCORE, "foo"));
assertEquals("foo_bar", LOWER_UNDERSCORE.to(LOWER_UNDERSCORE, "foo_bar"));
}
public void testLowerUnderscoreToLowerCamel() {
assertEquals("foo", LOWER_UNDERSCORE.to(LOWER_CAMEL, "foo"));
assertEquals("fooBar", LOWER_UNDERSCORE.to(LOWER_CAMEL, "foo_bar"));
}
public void testLowerUnderscoreToUpperCamel() {
assertEquals("Foo", LOWER_UNDERSCORE.to(UPPER_CAMEL, "foo"));
assertEquals("FooBar", LOWER_UNDERSCORE.to(UPPER_CAMEL, "foo_bar"));
}
public void testLowerUnderscoreToUpperUnderscore() {
assertEquals("FOO", LOWER_UNDERSCORE.to(UPPER_UNDERSCORE, "foo"));
assertEquals("FOO_BAR", LOWER_UNDERSCORE.to(UPPER_UNDERSCORE, "foo_bar"));
}
public void testLowerCamelToLowerHyphen() {
assertEquals("foo", LOWER_CAMEL.to(LOWER_HYPHEN, "foo"));
assertEquals("foo-bar", LOWER_CAMEL.to(LOWER_HYPHEN, "fooBar"));
assertEquals("h-t-t-p", LOWER_CAMEL.to(LOWER_HYPHEN, "HTTP"));
}
public void testLowerCamelToLowerUnderscore() {
assertEquals("foo", LOWER_CAMEL.to(LOWER_UNDERSCORE, "foo"));
assertEquals("foo_bar", LOWER_CAMEL.to(LOWER_UNDERSCORE, "fooBar"));
assertEquals("h_t_t_p", LOWER_CAMEL.to(LOWER_UNDERSCORE, "hTTP"));
}
public void testLowerCamelToLowerCamel() {
assertEquals("foo", LOWER_CAMEL.to(LOWER_CAMEL, "foo"));
assertEquals("fooBar", LOWER_CAMEL.to(LOWER_CAMEL, "fooBar"));
}
public void testLowerCamelToUpperCamel() {
assertEquals("Foo", LOWER_CAMEL.to(UPPER_CAMEL, "foo"));
assertEquals("FooBar", LOWER_CAMEL.to(UPPER_CAMEL, "fooBar"));
assertEquals("HTTP", LOWER_CAMEL.to(UPPER_CAMEL, "hTTP"));
}
public void testLowerCamelToUpperUnderscore() {
assertEquals("FOO", LOWER_CAMEL.to(UPPER_UNDERSCORE, "foo"));
assertEquals("FOO_BAR", LOWER_CAMEL.to(UPPER_UNDERSCORE, "fooBar"));
}
public void testUpperCamelToLowerHyphen() {
assertEquals("foo", UPPER_CAMEL.to(LOWER_HYPHEN, "Foo"));
assertEquals("foo-bar", UPPER_CAMEL.to(LOWER_HYPHEN, "FooBar"));
}
public void testUpperCamelToLowerUnderscore() {
assertEquals("foo", UPPER_CAMEL.to(LOWER_UNDERSCORE, "Foo"));
assertEquals("foo_bar", UPPER_CAMEL.to(LOWER_UNDERSCORE, "FooBar"));
}
public void testUpperCamelToLowerCamel() {
assertEquals("foo", UPPER_CAMEL.to(LOWER_CAMEL, "Foo"));
assertEquals("fooBar", UPPER_CAMEL.to(LOWER_CAMEL, "FooBar"));
assertEquals("hTTP", UPPER_CAMEL.to(LOWER_CAMEL, "HTTP"));
}
public void testUpperCamelToUpperCamel() {
assertEquals("Foo", UPPER_CAMEL.to(UPPER_CAMEL, "Foo"));
assertEquals("FooBar", UPPER_CAMEL.to(UPPER_CAMEL, "FooBar"));
}
public void testUpperCamelToUpperUnderscore() {
assertEquals("FOO", UPPER_CAMEL.to(UPPER_UNDERSCORE, "Foo"));
assertEquals("FOO_BAR", UPPER_CAMEL.to(UPPER_UNDERSCORE, "FooBar"));
assertEquals("H_T_T_P", UPPER_CAMEL.to(UPPER_UNDERSCORE, "HTTP"));
assertEquals("H__T__T__P", UPPER_CAMEL.to(UPPER_UNDERSCORE, "H_T_T_P"));
}
public void testUpperUnderscoreToLowerHyphen() {
assertEquals("foo", UPPER_UNDERSCORE.to(LOWER_HYPHEN, "FOO"));
assertEquals("foo-bar", UPPER_UNDERSCORE.to(LOWER_HYPHEN, "FOO_BAR"));
}
public void testUpperUnderscoreToLowerUnderscore() {
assertEquals("foo", UPPER_UNDERSCORE.to(LOWER_UNDERSCORE, "FOO"));
assertEquals("foo_bar", UPPER_UNDERSCORE.to(LOWER_UNDERSCORE, "FOO_BAR"));
}
public void testUpperUnderscoreToLowerCamel() {
assertEquals("foo", UPPER_UNDERSCORE.to(LOWER_CAMEL, "FOO"));
assertEquals("fooBar", UPPER_UNDERSCORE.to(LOWER_CAMEL, "FOO_BAR"));
}
public void testUpperUnderscoreToUpperCamel() {
assertEquals("Foo", UPPER_UNDERSCORE.to(UPPER_CAMEL, "FOO"));
assertEquals("FooBar", UPPER_UNDERSCORE.to(UPPER_CAMEL, "FOO_BAR"));
assertEquals("HTTP", UPPER_UNDERSCORE.to(UPPER_CAMEL, "H_T_T_P"));
}
public void testUpperUnderscoreToUpperUnderscore() {
assertEquals("FOO", UPPER_UNDERSCORE.to(UPPER_UNDERSCORE, "FOO"));
assertEquals("FOO_BAR", UPPER_UNDERSCORE.to(UPPER_UNDERSCORE, "FOO_BAR"));
}
public void testConverterToForward() {
assertEquals("FooBar", UPPER_UNDERSCORE.converterTo(UPPER_CAMEL).convert("FOO_BAR"));
assertEquals("fooBar", UPPER_UNDERSCORE.converterTo(LOWER_CAMEL).convert("FOO_BAR"));
assertEquals("FOO_BAR", UPPER_CAMEL.converterTo(UPPER_UNDERSCORE).convert("FooBar"));
assertEquals("FOO_BAR", LOWER_CAMEL.converterTo(UPPER_UNDERSCORE).convert("fooBar"));
}
public void testConverterToBackward() {
assertEquals("FOO_BAR", UPPER_UNDERSCORE.converterTo(UPPER_CAMEL).reverse().convert("FooBar"));
assertEquals("FOO_BAR", UPPER_UNDERSCORE.converterTo(LOWER_CAMEL).reverse().convert("fooBar"));
assertEquals("FooBar", UPPER_CAMEL.converterTo(UPPER_UNDERSCORE).reverse().convert("FOO_BAR"));
assertEquals("fooBar", LOWER_CAMEL.converterTo(UPPER_UNDERSCORE).reverse().convert("FOO_BAR"));
}
public void testConverter_nullConversions() {
for (CaseFormat outer : CaseFormat.values()) {
for (CaseFormat inner : CaseFormat.values()) {
assertNull(outer.converterTo(inner).convert(null));
assertNull(outer.converterTo(inner).reverse().convert(null));
}
}
}
public void testConverter_toString() {
assertEquals(
"LOWER_HYPHEN.converterTo(UPPER_CAMEL)",
LOWER_HYPHEN.converterTo(UPPER_CAMEL).toString());
}
public void testConverter_serialization() {
for (CaseFormat outer : CaseFormat.values()) {
for (CaseFormat inner : CaseFormat.values()) {
SerializableTester.reserializeAndAssert(outer.converterTo(inner));
}
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/CaseFormatTest.java | Java | asf20 | 8,456 |
/*
* Copyright (C) 2008 The Guava 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.common.base;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.testing.FakeTicker;
import junit.framework.TestCase;
/**
* Unit test for {@link Stopwatch}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class StopwatchTest extends TestCase {
private final FakeTicker ticker = new FakeTicker();
private final Stopwatch stopwatch = new Stopwatch(ticker);
public void testCreateStarted() {
Stopwatch startedStopwatch = Stopwatch.createStarted();
assertTrue(startedStopwatch.isRunning());
}
public void testCreateUnstarted() {
Stopwatch unstartedStopwatch = Stopwatch.createUnstarted();
assertFalse(unstartedStopwatch.isRunning());
assertEquals(0, unstartedStopwatch.elapsed(NANOSECONDS));
}
public void testInitialState() {
assertFalse(stopwatch.isRunning());
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
}
public void testStart() {
assertSame(stopwatch, stopwatch.start());
assertTrue(stopwatch.isRunning());
}
public void testStart_whileRunning() {
stopwatch.start();
try {
stopwatch.start();
fail();
} catch (IllegalStateException expected) {
}
assertTrue(stopwatch.isRunning());
}
public void testStop() {
stopwatch.start();
assertSame(stopwatch, stopwatch.stop());
assertFalse(stopwatch.isRunning());
}
public void testStop_new() {
try {
stopwatch.stop();
fail();
} catch (IllegalStateException expected) {
}
assertFalse(stopwatch.isRunning());
}
public void testStop_alreadyStopped() {
stopwatch.start();
stopwatch.stop();
try {
stopwatch.stop();
fail();
} catch (IllegalStateException expected) {
}
assertFalse(stopwatch.isRunning());
}
public void testReset_new() {
ticker.advance(1);
stopwatch.reset();
assertFalse(stopwatch.isRunning());
ticker.advance(2);
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
stopwatch.start();
ticker.advance(3);
assertEquals(3, stopwatch.elapsed(NANOSECONDS));
}
public void testReset_whileRunning() {
ticker.advance(1);
stopwatch.start();
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
ticker.advance(2);
assertEquals(2, stopwatch.elapsed(NANOSECONDS));
stopwatch.reset();
assertFalse(stopwatch.isRunning());
ticker.advance(3);
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
}
public void testElapsed_whileRunning() {
ticker.advance(78);
stopwatch.start();
assertEquals(0, stopwatch.elapsed(NANOSECONDS));
ticker.advance(345);
assertEquals(345, stopwatch.elapsed(NANOSECONDS));
}
public void testElapsed_notRunning() {
ticker.advance(1);
stopwatch.start();
ticker.advance(4);
stopwatch.stop();
ticker.advance(9);
assertEquals(4, stopwatch.elapsed(NANOSECONDS));
}
public void testElapsed_multipleSegments() {
stopwatch.start();
ticker.advance(9);
stopwatch.stop();
ticker.advance(16);
stopwatch.start();
assertEquals(9, stopwatch.elapsed(NANOSECONDS));
ticker.advance(25);
assertEquals(34, stopwatch.elapsed(NANOSECONDS));
stopwatch.stop();
ticker.advance(36);
assertEquals(34, stopwatch.elapsed(NANOSECONDS));
}
public void testElapsed_micros() {
stopwatch.start();
ticker.advance(999);
assertEquals(0, stopwatch.elapsed(MICROSECONDS));
ticker.advance(1);
assertEquals(1, stopwatch.elapsed(MICROSECONDS));
}
public void testElapsed_millis() {
stopwatch.start();
ticker.advance(999999);
assertEquals(0, stopwatch.elapsed(MILLISECONDS));
ticker.advance(1);
assertEquals(1, stopwatch.elapsed(MILLISECONDS));
}
public void testElapsedMillis() {
stopwatch.start();
ticker.advance(999999);
assertEquals(0, stopwatch.elapsed(MILLISECONDS));
ticker.advance(1);
assertEquals(1, stopwatch.elapsed(MILLISECONDS));
}
public void testElapsedMillis_whileRunning() {
ticker.advance(78000000);
stopwatch.start();
assertEquals(0, stopwatch.elapsed(MILLISECONDS));
ticker.advance(345000000);
assertEquals(345, stopwatch.elapsed(MILLISECONDS));
}
public void testElapsedMillis_notRunning() {
ticker.advance(1000000);
stopwatch.start();
ticker.advance(4000000);
stopwatch.stop();
ticker.advance(9000000);
assertEquals(4, stopwatch.elapsed(MILLISECONDS));
}
public void testElapsedMillis_multipleSegments() {
stopwatch.start();
ticker.advance(9000000);
stopwatch.stop();
ticker.advance(16000000);
stopwatch.start();
assertEquals(9, stopwatch.elapsed(MILLISECONDS));
ticker.advance(25000000);
assertEquals(34, stopwatch.elapsed(MILLISECONDS));
stopwatch.stop();
ticker.advance(36000000);
assertEquals(34, stopwatch.elapsed(MILLISECONDS));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/StopwatchTest.java | Java | asf20 | 5,681 |
/*
* Copyright (C) 2005 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.testing.EqualsTester;
import junit.framework.TestCase;
import java.io.Serializable;
import java.util.Map;
/**
* Tests for {@link Functions}.
*
* @author Mike Bostock
* @author Vlad Patryshev
*/
@GwtCompatible(emulated = true)
public class FunctionsTest extends TestCase {
public void testIdentity_same() {
Function<String, String> identity = Functions.identity();
assertNull(identity.apply(null));
assertSame("foo", identity.apply("foo"));
}
public void testIdentity_notSame() {
Function<Long, Long> identity = Functions.identity();
assertNotSame(new Long(135135L), identity.apply(new Long(135135L)));
}
public void testToStringFunction_apply() {
assertEquals("3", Functions.toStringFunction().apply(3));
assertEquals("hiya", Functions.toStringFunction().apply("hiya"));
assertEquals("I'm a string",
Functions.toStringFunction().apply(
new Object() {
@Override public String toString() {
return "I'm a string";
}
}));
try {
Functions.toStringFunction().apply(null);
fail("expected NullPointerException");
} catch (NullPointerException e) {
// expected
}
}
public void testForMapWithoutDefault() {
Map<String, Integer> map = Maps.newHashMap();
map.put("One", 1);
map.put("Three", 3);
map.put("Null", null);
Function<String, Integer> function = Functions.forMap(map);
assertEquals(1, function.apply("One").intValue());
assertEquals(3, function.apply("Three").intValue());
assertNull(function.apply("Null"));
try {
function.apply("Two");
fail();
} catch (IllegalArgumentException expected) {
}
new EqualsTester()
.addEqualityGroup(function, Functions.forMap(map))
.addEqualityGroup(Functions.forMap(map, 42))
.testEquals();
}
public void testForMapWithDefault() {
Map<String, Integer> map = Maps.newHashMap();
map.put("One", 1);
map.put("Three", 3);
map.put("Null", null);
Function<String, Integer> function = Functions.forMap(map, 42);
assertEquals(1, function.apply("One").intValue());
assertEquals(42, function.apply("Two").intValue());
assertEquals(3, function.apply("Three").intValue());
assertNull(function.apply("Null"));
new EqualsTester()
.addEqualityGroup(function, Functions.forMap(map, 42))
.addEqualityGroup(Functions.forMap(map))
.addEqualityGroup(Functions.forMap(map, null))
.addEqualityGroup(Functions.forMap(map, 43))
.testEquals();
}
public void testForMapWithDefault_null() {
ImmutableMap<String, Integer> map = ImmutableMap.of("One", 1);
Function<String, Integer> function = Functions.forMap(map, null);
assertEquals((Integer) 1, function.apply("One"));
assertNull(function.apply("Two"));
// check basic sanity of equals and hashCode
new EqualsTester()
.addEqualityGroup(function)
.addEqualityGroup(Functions.forMap(map, 1))
.testEquals();
}
public void testForMapWildCardWithDefault() {
Map<String, Integer> map = Maps.newHashMap();
map.put("One", 1);
map.put("Three", 3);
Number number = Double.valueOf(42);
Function<String, Number> function = Functions.forMap(map, number);
assertEquals(1, function.apply("One").intValue());
assertEquals(number, function.apply("Two"));
assertEquals(3L, function.apply("Three").longValue());
}
public void testComposition() {
Map<String, Integer> mJapaneseToInteger = Maps.newHashMap();
mJapaneseToInteger.put("Ichi", 1);
mJapaneseToInteger.put("Ni", 2);
mJapaneseToInteger.put("San", 3);
Function<String, Integer> japaneseToInteger =
Functions.forMap(mJapaneseToInteger);
Map<Integer, String> mIntegerToSpanish = Maps.newHashMap();
mIntegerToSpanish.put(1, "Uno");
mIntegerToSpanish.put(3, "Tres");
mIntegerToSpanish.put(4, "Cuatro");
Function<Integer, String> integerToSpanish =
Functions.forMap(mIntegerToSpanish);
Function<String, String> japaneseToSpanish =
Functions.compose(integerToSpanish, japaneseToInteger);
assertEquals("Uno", japaneseToSpanish.apply("Ichi"));
try {
japaneseToSpanish.apply("Ni");
fail();
} catch (IllegalArgumentException e) {
}
assertEquals("Tres", japaneseToSpanish.apply("San"));
try {
japaneseToSpanish.apply("Shi");
fail();
} catch (IllegalArgumentException e) {
}
new EqualsTester()
.addEqualityGroup(
japaneseToSpanish,
Functions.compose(integerToSpanish, japaneseToInteger))
.addEqualityGroup(japaneseToInteger)
.addEqualityGroup(integerToSpanish)
.addEqualityGroup(
Functions.compose(japaneseToInteger, integerToSpanish))
.testEquals();
}
public void testCompositionWildcard() {
Map<String, Integer> mapJapaneseToInteger = Maps.newHashMap();
Function<String, Integer> japaneseToInteger =
Functions.forMap(mapJapaneseToInteger);
Function<Object, String> numberToSpanish = Functions.constant("Yo no se");
Function<String, String> japaneseToSpanish =
Functions.compose(numberToSpanish, japaneseToInteger);
}
private static class HashCodeFunction implements Function<Object, Integer> {
@Override
public Integer apply(Object o) {
return (o == null) ? 0 : o.hashCode();
}
}
public void testComposeOfFunctionsIsAssociative() {
Map<Float, String> m = ImmutableMap.of(
4.0f, "A", 3.0f, "B", 2.0f, "C", 1.0f, "D");
Function<? super Integer, Boolean> h = Functions.constant(Boolean.TRUE);
Function<? super String, Integer> g = new HashCodeFunction();
Function<Float, String> f = Functions.forMap(m, "F");
Function<Float, Boolean> c1 = Functions.compose(Functions.compose(h, g), f);
Function<Float, Boolean> c2 = Functions.compose(h, Functions.compose(g, f));
// Might be nice (eventually) to have:
// assertEquals(c1, c2);
// But for now, settle for this:
assertEquals(c1.hashCode(), c2.hashCode());
assertEquals(c1.apply(1.0f), c2.apply(1.0f));
assertEquals(c1.apply(5.0f), c2.apply(5.0f));
}
public void testComposeOfPredicateAndFunctionIsAssociative() {
Map<Float, String> m = ImmutableMap.of(
4.0f, "A", 3.0f, "B", 2.0f, "C", 1.0f, "D");
Predicate<? super Integer> h = Predicates.equalTo(42);
Function<? super String, Integer> g = new HashCodeFunction();
Function<Float, String> f = Functions.forMap(m, "F");
Predicate<Float> p1 = Predicates.compose(Predicates.compose(h, g), f);
Predicate<Float> p2 = Predicates.compose(h, Functions.compose(g, f));
// Might be nice (eventually) to have:
// assertEquals(p1, p2);
// But for now, settle for this:
assertEquals(p1.hashCode(), p2.hashCode());
assertEquals(p1.apply(1.0f), p2.apply(1.0f));
assertEquals(p1.apply(5.0f), p2.apply(5.0f));
}
public void testForPredicate() {
Function<Object, Boolean> alwaysTrue =
Functions.forPredicate(Predicates.alwaysTrue());
Function<Object, Boolean> alwaysFalse =
Functions.forPredicate(Predicates.alwaysFalse());
assertTrue(alwaysTrue.apply(0));
assertFalse(alwaysFalse.apply(0));
new EqualsTester()
.addEqualityGroup(
alwaysTrue, Functions.forPredicate(Predicates.alwaysTrue()))
.addEqualityGroup(alwaysFalse)
.addEqualityGroup(Functions.identity())
.testEquals();
}
public void testConstant() {
Function<Object, Object> f = Functions.<Object>constant("correct");
assertEquals("correct", f.apply(new Object()));
assertEquals("correct", f.apply(null));
Function<Object, String> g = Functions.constant(null);
assertEquals(null, g.apply(2));
assertEquals(null, g.apply(null));
new EqualsTester()
.addEqualityGroup(f, Functions.constant("correct"))
.addEqualityGroup(Functions.constant("incorrect"))
.addEqualityGroup(Functions.toStringFunction())
.addEqualityGroup(g)
.testEquals();
new EqualsTester()
.addEqualityGroup(g, Functions.constant(null))
.addEqualityGroup(Functions.constant("incorrect"))
.addEqualityGroup(Functions.toStringFunction())
.addEqualityGroup(f)
.testEquals();
}
private static class CountingSupplier
implements Supplier<Integer>, Serializable {
private static final long serialVersionUID = 0;
private int value;
@Override
public Integer get() {
return ++value;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof CountingSupplier) {
return this.value == ((CountingSupplier) obj).value;
}
return false;
}
@Override
public int hashCode() {
return value;
}
}
public void testForSupplier() {
Supplier<Integer> supplier = new CountingSupplier();
Function<Object, Integer> function = Functions.forSupplier(supplier);
assertEquals(1, (int) function.apply(null));
assertEquals(2, (int) function.apply("foo"));
new EqualsTester()
.addEqualityGroup(function, Functions.forSupplier(supplier))
.addEqualityGroup(Functions.forSupplier(new CountingSupplier()))
.addEqualityGroup(Functions.forSupplier(Suppliers.ofInstance(12)))
.addEqualityGroup(Functions.toStringFunction())
.testEquals();
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/FunctionsTest.java | Java | asf20 | 10,305 |
/*
* Copyright (C) 2007 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Lists;
import com.google.common.testing.EqualsTester;
import junit.framework.TestCase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Tests com.google.common.base.Suppliers.
*
* @author Laurence Gonsalves
* @author Harry Heymann
*/
@GwtCompatible(emulated = true)
public class SuppliersTest extends TestCase {
public void testCompose() {
Supplier<Integer> fiveSupplier = new Supplier<Integer>() {
@Override
public Integer get() {
return 5;
}
};
Function<Number, Integer> intValueFunction =
new Function<Number, Integer>() {
@Override
public Integer apply(Number x) {
return x.intValue();
}
};
Supplier<Integer> squareSupplier = Suppliers.compose(intValueFunction,
fiveSupplier);
assertEquals(Integer.valueOf(5), squareSupplier.get());
}
public void testComposeWithLists() {
Supplier<ArrayList<Integer>> listSupplier
= new Supplier<ArrayList<Integer>>() {
@Override
public ArrayList<Integer> get() {
return Lists.newArrayList(0);
}
};
Function<List<Integer>, List<Integer>> addElementFunction =
new Function<List<Integer>, List<Integer>>() {
@Override
public List<Integer> apply(List<Integer> list) {
ArrayList<Integer> result = Lists.newArrayList(list);
result.add(1);
return result;
}
};
Supplier<List<Integer>> addSupplier = Suppliers.compose(addElementFunction,
listSupplier);
List<Integer> result = addSupplier.get();
assertEquals(Integer.valueOf(0), result.get(0));
assertEquals(Integer.valueOf(1), result.get(1));
}
static class CountingSupplier implements Supplier<Integer>, Serializable {
private static final long serialVersionUID = 0L;
transient int calls = 0;
@Override
public Integer get() {
calls++;
return calls * 10;
}
}
public void testMemoize() {
CountingSupplier countingSupplier = new CountingSupplier();
Supplier<Integer> memoizedSupplier = Suppliers.memoize(countingSupplier);
checkMemoize(countingSupplier, memoizedSupplier);
}
public void testMemoize_redudantly() {
CountingSupplier countingSupplier = new CountingSupplier();
Supplier<Integer> memoizedSupplier = Suppliers.memoize(countingSupplier);
assertSame(memoizedSupplier, Suppliers.memoize(memoizedSupplier));
}
private void checkMemoize(
CountingSupplier countingSupplier, Supplier<Integer> memoizedSupplier) {
// the underlying supplier hasn't executed yet
assertEquals(0, countingSupplier.calls);
assertEquals(10, (int) memoizedSupplier.get());
// now it has
assertEquals(1, countingSupplier.calls);
assertEquals(10, (int) memoizedSupplier.get());
// it still should only have executed once due to memoization
assertEquals(1, countingSupplier.calls);
}
public void testMemoizeExceptionThrown() {
Supplier<Integer> exceptingSupplier = new Supplier<Integer>() {
@Override
public Integer get() {
throw new NullPointerException();
}
};
Supplier<Integer> memoizedSupplier = Suppliers.memoize(exceptingSupplier);
// call get() twice to make sure that memoization doesn't interfere
// with throwing the exception
for (int i = 0; i < 2; i++) {
try {
memoizedSupplier.get();
fail("failed to throw NullPointerException");
} catch (NullPointerException e) {
// this is what should happen
}
}
}
public void testOfInstanceSuppliesSameInstance() {
Object toBeSupplied = new Object();
Supplier<Object> objectSupplier = Suppliers.ofInstance(toBeSupplied);
assertSame(toBeSupplied,objectSupplier.get());
assertSame(toBeSupplied,objectSupplier.get()); // idempotent
}
public void testOfInstanceSuppliesNull() {
Supplier<Integer> nullSupplier = Suppliers.ofInstance(null);
assertNull(nullSupplier.get());
}
public void testSupplierFunction() {
Supplier<Integer> supplier = Suppliers.ofInstance(14);
Function<Supplier<Integer>, Integer> supplierFunction =
Suppliers.supplierFunction();
assertEquals(14, (int) supplierFunction.apply(supplier));
}
public void testOfInstance_equals() {
new EqualsTester()
.addEqualityGroup(
Suppliers.ofInstance("foo"), Suppliers.ofInstance("foo"))
.addEqualityGroup(Suppliers.ofInstance("bar"))
.testEquals();
}
public void testCompose_equals() {
new EqualsTester()
.addEqualityGroup(
Suppliers.compose(Functions.constant(1), Suppliers.ofInstance("foo")),
Suppliers.compose(Functions.constant(1), Suppliers.ofInstance("foo")))
.addEqualityGroup(
Suppliers.compose(Functions.constant(2), Suppliers.ofInstance("foo")))
.addEqualityGroup(
Suppliers.compose(Functions.constant(1), Suppliers.ofInstance("bar")))
.testEquals();
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/SuppliersTest.java | Java | asf20 | 5,783 |
/*
* Copyright (C) 2007 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.nio.charset.Charset;
/**
* Unit test for {@link Charsets}.
*
* @author Mike Bostock
*/
@GwtCompatible(emulated = true)
public class CharsetsTest extends TestCase {
public void testUtf8() {
assertEquals(Charset.forName("UTF-8"), Charsets.UTF_8);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/CharsetsTest.java | Java | asf20 | 998 |
/*
* Copyright (C) 2013 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
/**
* Unit tests for {@link Utf8}.
*
* @author Jon Perlow
* @author Martin Buchholz
* @author Clément Roux
*/
@GwtCompatible(emulated = true)
public class Utf8Test extends TestCase {
public void testEncodedLength_validStrings() {
assertEquals(0, Utf8.encodedLength(""));
assertEquals(11, Utf8.encodedLength("Hello world"));
assertEquals(8, Utf8.encodedLength("Résumé"));
assertEquals(461, Utf8.encodedLength("威廉·莎士比亞(William Shakespeare,"
+ "1564年4月26號—1616年4月23號[1])係隻英國嗰演員、劇作家同詩人,"
+ "有時間佢簡稱莎翁;中國清末民初哈拕翻譯做舌克斯毕、沙斯皮耳、筛斯比耳、"
+ "莎基斯庇尔、索士比尔、夏克思芘尔、希哀苦皮阿、叶斯壁、沙克皮尔、"
+ "狹斯丕爾。[2]莎士比亞編寫過好多作品,佢嗰劇作響西洋文學好有影響,"
+ "哈都拕人翻譯做好多話。"));
// A surrogate pair
assertEquals(4, Utf8.encodedLength(
newString(Character.MIN_HIGH_SURROGATE, Character.MIN_LOW_SURROGATE)));
}
public void testEncodedLength_invalidStrings() {
testEncodedLengthFails(newString(Character.MIN_HIGH_SURROGATE), 0);
testEncodedLengthFails("foobar" + newString(Character.MIN_HIGH_SURROGATE), 6);
testEncodedLengthFails(newString(Character.MIN_LOW_SURROGATE), 0);
testEncodedLengthFails("foobar" + newString(Character.MIN_LOW_SURROGATE), 6);
testEncodedLengthFails(
newString(
Character.MIN_HIGH_SURROGATE,
Character.MIN_HIGH_SURROGATE), 0);
}
private static void testEncodedLengthFails(String invalidString,
int invalidCodePointIndex) {
try {
Utf8.encodedLength(invalidString);
fail();
} catch (IllegalArgumentException expected) {
assertEquals("Unpaired surrogate at index " + invalidCodePointIndex,
expected.getMessage());
}
}
// 128 - [chars 0x0000 to 0x007f]
private static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS =
0x007f - 0x0000 + 1;
// 128
private static final long EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT =
ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 1920 [chars 0x0080 to 0x07FF]
private static final long TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS =
0x07FF - 0x0080 + 1;
// 18,304
private static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT =
// Both bytes are one byte characters
(long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) +
// The possible number of two byte characters
TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 2048
private static final long THREE_BYTE_SURROGATES = 2 * 1024;
// 61,440 [chars 0x0800 to 0xFFFF, minus surrogates]
private static final long THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS =
0xFFFF - 0x0800 + 1 - THREE_BYTE_SURROGATES;
// 2,650,112
private static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT =
// All one byte characters
(long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) +
// One two byte character and a one byte character
2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS *
ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
// Three byte characters
THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS;
// 1,048,576 [chars 0x10000L to 0x10FFFF]
private static final long FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS =
0x10FFFF - 0x10000L + 1;
// 289,571,839
private static final long EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT =
// All one byte characters
(long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 4) +
// One and three byte characters
2 * THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS *
ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
// Two two byte characters
TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS +
// Permutations of one and two byte characters
3 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS *
ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS *
ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS +
// Four byte characters
FOUR_BYTE_ROUNDTRIPPABLE_CHARACTERS;
/**
* Tests that round tripping of a sample of four byte permutations work.
* All permutations are prohibitively expensive to test for automated runs.
* This method tests specific four-byte cases.
*/
public void testIsWellFormed_4BytesSamples() {
// Valid 4 byte.
assertWellFormed(0xF0, 0xA4, 0xAD, 0xA2);
// Bad trailing bytes
assertNotWellFormed(0xF0, 0xA4, 0xAD, 0x7F);
assertNotWellFormed(0xF0, 0xA4, 0xAD, 0xC0);
// Special cases for byte2
assertNotWellFormed(0xF0, 0x8F, 0xAD, 0xA2);
assertNotWellFormed(0xF4, 0x90, 0xAD, 0xA2);
}
/** Tests some hard-coded test cases. */
public void testSomeSequences() {
// Empty
assertWellFormed();
// One-byte characters, including control characters
assertWellFormed(0x00, 0x61, 0x62, 0x63, 0x7F); // "\u0000abc\u007f"
// Two-byte characters
assertWellFormed(0xC2, 0xA2, 0xC2, 0xA2); // "\u00a2\u00a2"
// Three-byte characters
assertWellFormed(0xc8, 0x8a, 0x63, 0xc8, 0x8a, 0x63); // "\u020ac\u020ac"
// Four-byte characters
// "\u024B62\u024B62"
assertWellFormed(0xc9, 0x8b, 0x36, 0x32, 0xc9, 0x8b, 0x36, 0x32);
// Mixed string
// "a\u020ac\u00a2b\\u024B62u020acc\u00a2de\u024B62"
assertWellFormed(0x61, 0xc8, 0x8a, 0x63, 0xc2, 0xa2, 0x62, 0x5c, 0x75, 0x30,
0x32, 0x34, 0x42, 0x36, 0x32, 0x75, 0x30, 0x32, 0x30, 0x61, 0x63, 0x63,
0xc2, 0xa2, 0x64, 0x65, 0xc9, 0x8b, 0x36, 0x32);
// Not a valid string
assertNotWellFormed(-1, 0, -1, 0);
}
public void testShardsHaveExpectedRoundTrippables() {
// A sanity check.
long actual = 0;
for (long expected : generateFourByteShardsExpectedRunnables()) {
actual += expected;
}
assertEquals(EXPECTED_FOUR_BYTE_ROUNDTRIPPABLE_COUNT, actual);
}
private String newString(char... chars) {
return new String(chars);
}
private byte[] toByteArray(int... bytes) {
byte[] realBytes = new byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
realBytes[i] = (byte) bytes[i];
}
return realBytes;
}
private void assertWellFormed(int... bytes) {
assertTrue(Utf8.isWellFormed(toByteArray(bytes)));
}
private void assertNotWellFormed(int... bytes) {
assertFalse(Utf8.isWellFormed(toByteArray(bytes)));
}
private static long[] generateFourByteShardsExpectedRunnables() {
long[] expected = new long[128];
// 0-63 are all 5300224
for (int i = 0; i <= 63; i++) {
expected[i] = 5300224;
}
// 97-111 are all 2342912
for (int i = 97; i <= 111; i++) {
expected[i] = 2342912;
}
// 113-117 are all 1048576
for (int i = 113; i <= 117; i++) {
expected[i] = 1048576;
}
// One offs
expected[112] = 786432;
expected[118] = 786432;
expected[119] = 1048576;
expected[120] = 458752;
expected[121] = 524288;
expected[122] = 65536;
// Anything not assigned was the default 0.
return expected;
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/Utf8Test.java | Java | asf20 | 7,819 |
/*
* Copyright (C) 2009 The Guava 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.common.base;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import junit.framework.TestCase;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Julien Silland
*/
@GwtCompatible(emulated = true)
public class SplitterTest extends TestCase {
private static final Splitter COMMA_SPLITTER = Splitter.on(',');
public void testSplitNullString() {
try {
COMMA_SPLITTER.split(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testCharacterSimpleSplit() {
String simple = "a,b,c";
Iterable<String> letters = COMMA_SPLITTER.split(simple);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c");
}
/**
* All of the infrastructure of split and splitToString is identical, so we
* do one test of splitToString. All other cases should be covered by testing
* of split.
*
* <p>TODO(user): It would be good to make all the relevant tests run on
* both split and splitToString automatically.
*/
public void testCharacterSimpleSplitToList() {
String simple = "a,b,c";
List<String> letters = COMMA_SPLITTER.splitToList(simple);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c");
}
public void testToString() {
assertEquals("[]", Splitter.on(',').split("").toString());
assertEquals("[a, b, c]", Splitter.on(',').split("a,b,c").toString());
assertEquals("[yam, bam, jam, ham]", Splitter.on(", ").split("yam, bam, jam, ham").toString());
}
public void testCharacterSimpleSplitWithNoDelimiter() {
String simple = "a,b,c";
Iterable<String> letters = Splitter.on('.').split(simple);
ASSERT.that(letters).iteratesOverSequence("a,b,c");
}
public void testCharacterSplitWithDoubleDelimiter() {
String doubled = "a,,b,c";
Iterable<String> letters = COMMA_SPLITTER.split(doubled);
ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c");
}
public void testCharacterSplitWithDoubleDelimiterAndSpace() {
String doubled = "a,, b,c";
Iterable<String> letters = COMMA_SPLITTER.split(doubled);
ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c");
}
public void testCharacterSplitWithTrailingDelimiter() {
String trailing = "a,b,c,";
Iterable<String> letters = COMMA_SPLITTER.split(trailing);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "");
}
public void testCharacterSplitWithLeadingDelimiter() {
String leading = ",a,b,c";
Iterable<String> letters = COMMA_SPLITTER.split(leading);
ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c");
}
public void testCharacterSplitWithMulitpleLetters() {
Iterable<String> testCharacteringMotto = Splitter.on('-').split(
"Testing-rocks-Debugging-sucks");
ASSERT.that(testCharacteringMotto).iteratesOverSequence(
"Testing", "rocks", "Debugging", "sucks");
}
public void testCharacterSplitWithMatcherDelimiter() {
Iterable<String> testCharacteringMotto = Splitter
.on(CharMatcher.WHITESPACE)
.split("Testing\nrocks\tDebugging sucks");
ASSERT.that(testCharacteringMotto).iteratesOverSequence(
"Testing", "rocks", "Debugging", "sucks");
}
public void testCharacterSplitWithDoubleDelimiterOmitEmptyStrings() {
String doubled = "a..b.c";
Iterable<String> letters = Splitter.on('.')
.omitEmptyStrings().split(doubled);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c");
}
public void testCharacterSplitEmptyToken() {
String emptyToken = "a. .c";
Iterable<String> letters = Splitter.on('.').trimResults()
.split(emptyToken);
ASSERT.that(letters).iteratesOverSequence("a", "", "c");
}
public void testCharacterSplitEmptyTokenOmitEmptyStrings() {
String emptyToken = "a. .c";
Iterable<String> letters = Splitter.on('.')
.omitEmptyStrings().trimResults().split(emptyToken);
ASSERT.that(letters).iteratesOverSequence("a", "c");
}
public void testCharacterSplitOnEmptyString() {
Iterable<String> nothing = Splitter.on('.').split("");
ASSERT.that(nothing).iteratesOverSequence("");
}
public void testCharacterSplitOnEmptyStringOmitEmptyStrings() {
ASSERT.that(Splitter.on('.').omitEmptyStrings().split("")).isEmpty();
}
public void testCharacterSplitOnOnlyDelimiter() {
Iterable<String> blankblank = Splitter.on('.').split(".");
ASSERT.that(blankblank).iteratesOverSequence("", "");
}
public void testCharacterSplitOnOnlyDelimitersOmitEmptyStrings() {
Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("...");
ASSERT.that(empty);
}
public void testCharacterSplitWithTrim() {
String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, "
+ "ofar(Jemaine), aff(Tito)";
Iterable<String> family = COMMA_SPLITTER
.trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE))
.split(jacksons);
ASSERT.that(family).iteratesOverSequence(
"(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)");
}
public void testStringSimpleSplit() {
String simple = "a,b,c";
Iterable<String> letters = Splitter.on(',').split(simple);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c");
}
public void testStringSimpleSplitWithNoDelimiter() {
String simple = "a,b,c";
Iterable<String> letters = Splitter.on('.').split(simple);
ASSERT.that(letters).iteratesOverSequence("a,b,c");
}
public void testStringSplitWithDoubleDelimiter() {
String doubled = "a,,b,c";
Iterable<String> letters = Splitter.on(',').split(doubled);
ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c");
}
public void testStringSplitWithDoubleDelimiterAndSpace() {
String doubled = "a,, b,c";
Iterable<String> letters = Splitter.on(',').split(doubled);
ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c");
}
public void testStringSplitWithTrailingDelimiter() {
String trailing = "a,b,c,";
Iterable<String> letters = Splitter.on(',').split(trailing);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "");
}
public void testStringSplitWithLeadingDelimiter() {
String leading = ",a,b,c";
Iterable<String> letters = Splitter.on(',').split(leading);
ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c");
}
public void testStringSplitWithMultipleLetters() {
Iterable<String> testStringingMotto = Splitter.on('-').split(
"Testing-rocks-Debugging-sucks");
ASSERT.that(testStringingMotto).iteratesOverSequence(
"Testing", "rocks", "Debugging", "sucks");
}
public void testStringSplitWithDoubleDelimiterOmitEmptyStrings() {
String doubled = "a..b.c";
Iterable<String> letters = Splitter.on('.')
.omitEmptyStrings().split(doubled);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c");
}
public void testStringSplitEmptyToken() {
String emptyToken = "a. .c";
Iterable<String> letters = Splitter.on('.').trimResults()
.split(emptyToken);
ASSERT.that(letters).iteratesOverSequence("a", "", "c");
}
public void testStringSplitEmptyTokenOmitEmptyStrings() {
String emptyToken = "a. .c";
Iterable<String> letters = Splitter.on('.')
.omitEmptyStrings().trimResults().split(emptyToken);
ASSERT.that(letters).iteratesOverSequence("a", "c");
}
public void testStringSplitWithLongDelimiter() {
String longDelimiter = "a, b, c";
Iterable<String> letters = Splitter.on(", ").split(longDelimiter);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c");
}
public void testStringSplitWithLongLeadingDelimiter() {
String longDelimiter = ", a, b, c";
Iterable<String> letters = Splitter.on(", ").split(longDelimiter);
ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c");
}
public void testStringSplitWithLongTrailingDelimiter() {
String longDelimiter = "a, b, c, ";
Iterable<String> letters = Splitter.on(", ").split(longDelimiter);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "");
}
public void testStringSplitWithDelimiterSubstringInValue() {
String fourCommasAndFourSpaces = ",,,, ";
Iterable<String> threeCommasThenThreeSpaces = Splitter.on(", ").split(
fourCommasAndFourSpaces);
ASSERT.that(threeCommasThenThreeSpaces).iteratesOverSequence(",,,", " ");
}
public void testStringSplitWithEmptyString() {
try {
Splitter.on("");
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testStringSplitOnEmptyString() {
Iterable<String> notMuch = Splitter.on('.').split("");
ASSERT.that(notMuch).iteratesOverSequence("");
}
public void testStringSplitOnEmptyStringOmitEmptyString() {
ASSERT.that(Splitter.on('.').omitEmptyStrings().split("")).isEmpty();
}
public void testStringSplitOnOnlyDelimiter() {
Iterable<String> blankblank = Splitter.on('.').split(".");
ASSERT.that(blankblank).iteratesOverSequence("", "");
}
public void testStringSplitOnOnlyDelimitersOmitEmptyStrings() {
Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("...");
ASSERT.that(empty).isEmpty();
}
public void testStringSplitWithTrim() {
String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, "
+ "ofar(Jemaine), aff(Tito)";
Iterable<String> family = Splitter.on(',')
.trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE))
.split(jacksons);
ASSERT.that(family).iteratesOverSequence(
"(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)");
}
// TODO(kevinb): the name of this method suggests it might not actually be testing what it
// intends to be testing?
public void testSplitterIterableIsUnmodifiable_char() {
assertIteratorIsUnmodifiable(COMMA_SPLITTER.split("a,b").iterator());
}
public void testSplitterIterableIsUnmodifiable_string() {
assertIteratorIsUnmodifiable(Splitter.on(',').split("a,b").iterator());
}
private void assertIteratorIsUnmodifiable(Iterator<?> iterator) {
iterator.next();
try {
iterator.remove();
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void testSplitterIterableIsLazy_char() {
assertSplitterIterableIsLazy(COMMA_SPLITTER);
}
public void testSplitterIterableIsLazy_string() {
assertSplitterIterableIsLazy(Splitter.on(','));
}
/**
* This test really pushes the boundaries of what we support. In general the
* splitter's behaviour is not well defined if the char sequence it's
* splitting is mutated during iteration.
*/
private void assertSplitterIterableIsLazy(Splitter splitter) {
StringBuilder builder = new StringBuilder();
Iterator<String> iterator = splitter.split(builder).iterator();
builder.append("A,");
assertEquals("A", iterator.next());
builder.append("B,");
assertEquals("B", iterator.next());
builder.append("C");
assertEquals("C", iterator.next());
assertFalse(iterator.hasNext());
}
public void testFixedLengthSimpleSplit() {
String simple = "abcde";
Iterable<String> letters = Splitter.fixedLength(2).split(simple);
ASSERT.that(letters).iteratesOverSequence("ab", "cd", "e");
}
public void testFixedLengthSplitEqualChunkLength() {
String simple = "abcdef";
Iterable<String> letters = Splitter.fixedLength(2).split(simple);
ASSERT.that(letters).iteratesOverSequence("ab", "cd", "ef");
}
public void testFixedLengthSplitOnlyOneChunk() {
String simple = "abc";
Iterable<String> letters = Splitter.fixedLength(3).split(simple);
ASSERT.that(letters).iteratesOverSequence("abc");
}
public void testFixedLengthSplitSmallerString() {
String simple = "ab";
Iterable<String> letters = Splitter.fixedLength(3).split(simple);
ASSERT.that(letters).iteratesOverSequence("ab");
}
public void testFixedLengthSplitEmptyString() {
String simple = "";
Iterable<String> letters = Splitter.fixedLength(3).split(simple);
ASSERT.that(letters).iteratesOverSequence("");
}
public void testFixedLengthSplitEmptyStringWithOmitEmptyStrings() {
ASSERT.that(Splitter.fixedLength(3).omitEmptyStrings().split("")).isEmpty();
}
public void testFixedLengthSplitIntoChars() {
String simple = "abcd";
Iterable<String> letters = Splitter.fixedLength(1).split(simple);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "d");
}
public void testFixedLengthSplitZeroChunkLen() {
try {
Splitter.fixedLength(0);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testFixedLengthSplitNegativeChunkLen() {
try {
Splitter.fixedLength(-1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testLimitLarge() {
String simple = "abcd";
Iterable<String> letters = Splitter.fixedLength(1).limit(100).split(simple);
ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "d");
}
public void testLimitOne() {
String simple = "abcd";
Iterable<String> letters = Splitter.fixedLength(1).limit(1).split(simple);
ASSERT.that(letters).iteratesOverSequence("abcd");
}
public void testLimitFixedLength() {
String simple = "abcd";
Iterable<String> letters = Splitter.fixedLength(1).limit(2).split(simple);
ASSERT.that(letters).iteratesOverSequence("a", "bcd");
}
public void testLimitSeparator() {
String simple = "a,b,c,d";
Iterable<String> items = COMMA_SPLITTER.limit(2).split(simple);
ASSERT.that(items).iteratesOverSequence("a", "b,c,d");
}
public void testLimitExtraSeparators() {
String text = "a,,,b,,c,d";
Iterable<String> items = COMMA_SPLITTER.limit(2).split(text);
ASSERT.that(items).iteratesOverSequence("a", ",,b,,c,d");
}
public void testLimitExtraSeparatorsOmitEmpty() {
String text = "a,,,b,,c,d";
Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().split(text);
ASSERT.that(items).iteratesOverSequence("a", "b,,c,d");
}
public void testLimitExtraSeparatorsOmitEmpty3() {
String text = "a,,,b,,c,d";
Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().split(text);
ASSERT.that(items).iteratesOverSequence("a", "b", "c,d");
}
public void testLimitExtraSeparatorsTrim() {
String text = ",,a,, , b ,, c,d ";
Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().trimResults().split(text);
ASSERT.that(items).iteratesOverSequence("a", "b ,, c,d");
}
public void testLimitExtraSeparatorsTrim3() {
String text = ",,a,, , b ,, c,d ";
Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().trimResults().split(text);
ASSERT.that(items).iteratesOverSequence("a", "b", "c,d");
}
public void testLimitExtraSeparatorsTrim1() {
String text = ",,a,, , b ,, c,d ";
Iterable<String> items = COMMA_SPLITTER.limit(1).omitEmptyStrings().trimResults().split(text);
ASSERT.that(items).iteratesOverSequence("a,, , b ,, c,d");
}
public void testLimitExtraSeparatorsTrim1NoOmit() {
String text = ",,a,, , b ,, c,d ";
Iterable<String> items = COMMA_SPLITTER.limit(1).trimResults().split(text);
ASSERT.that(items).iteratesOverSequence(",,a,, , b ,, c,d");
}
public void testLimitExtraSeparatorsTrim1Empty() {
String text = "";
Iterable<String> items = COMMA_SPLITTER.limit(1).split(text);
ASSERT.that(items).iteratesOverSequence("");
}
public void testLimitExtraSeparatorsTrim1EmptyOmit() {
String text = "";
Iterable<String> items = COMMA_SPLITTER.omitEmptyStrings().limit(1).split(text);
ASSERT.that(items).isEmpty();
}
@SuppressWarnings("ReturnValueIgnored") // testing for exception
public void testInvalidZeroLimit() {
try {
COMMA_SPLITTER.limit(0);
fail();
} catch (IllegalArgumentException expected) {
}
}
private static <E> List<E> asList(Collection<E> collection) {
return ImmutableList.copyOf(collection);
}
public void testMapSplitter_trimmedBoth() {
Map<String, String> m = COMMA_SPLITTER
.trimResults()
.withKeyValueSeparator(Splitter.on(':').trimResults())
.split("boy : tom , girl: tina , cat : kitty , dog: tommy ");
ImmutableMap<String, String> expected =
ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy");
ASSERT.that(m).isEqualTo(expected);
ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet()));
}
public void testMapSplitter_trimmedEntries() {
Map<String, String> m = COMMA_SPLITTER
.trimResults()
.withKeyValueSeparator(":")
.split("boy : tom , girl: tina , cat : kitty , dog: tommy ");
ImmutableMap<String, String> expected =
ImmutableMap.of("boy ", " tom", "girl", " tina", "cat ", " kitty", "dog", " tommy");
ASSERT.that(m).isEqualTo(expected);
ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet()));
}
public void testMapSplitter_trimmedKeyValue() {
Map<String, String> m =
COMMA_SPLITTER.withKeyValueSeparator(Splitter.on(':').trimResults()).split(
"boy : tom , girl: tina , cat : kitty , dog: tommy ");
ImmutableMap<String, String> expected =
ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy");
ASSERT.that(m).isEqualTo(expected);
ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet()));
}
public void testMapSplitter_notTrimmed() {
Map<String, String> m = COMMA_SPLITTER.withKeyValueSeparator(":").split(
" boy:tom , girl: tina , cat :kitty , dog: tommy ");
ImmutableMap<String, String> expected =
ImmutableMap.of(" boy", "tom ", " girl", " tina ", " cat ", "kitty ", " dog", " tommy ");
ASSERT.that(m).isEqualTo(expected);
ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet()));
}
public void testMapSplitter_CharacterSeparator() {
// try different delimiters.
Map<String, String> m = Splitter
.on(",")
.withKeyValueSeparator(':')
.split("boy:tom,girl:tina,cat:kitty,dog:tommy");
ImmutableMap<String, String> expected =
ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy");
ASSERT.that(m).isEqualTo(expected);
ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet()));
}
public void testMapSplitter_multiCharacterSeparator() {
// try different delimiters.
Map<String, String> m = Splitter
.on(",")
.withKeyValueSeparator(":^&")
.split("boy:^&tom,girl:^&tina,cat:^&kitty,dog:^&tommy");
ImmutableMap<String, String> expected =
ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy");
ASSERT.that(m).isEqualTo(expected);
ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet()));
}
@SuppressWarnings("ReturnValueIgnored") // testing for exception
public void testMapSplitter_emptySeparator() {
try {
COMMA_SPLITTER.withKeyValueSeparator("");
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMapSplitter_malformedEntry() {
try {
COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2");
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testMapSplitter_orderedResults() {
Map<String, String> m = Splitter.on(',')
.withKeyValueSeparator(":")
.split("boy:tom,girl:tina,cat:kitty,dog:tommy");
ASSERT.that(m.keySet()).iteratesOverSequence("boy", "girl", "cat", "dog");
ASSERT.that(m).isEqualTo(
ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"));
// try in a different order
m = Splitter.on(',')
.withKeyValueSeparator(":")
.split("girl:tina,boy:tom,dog:tommy,cat:kitty");
ASSERT.that(m.keySet()).iteratesOverSequence("girl", "boy", "dog", "cat");
ASSERT.that(m).isEqualTo(
ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"));
}
public void testMapSplitter_duplicateKeys() {
try {
Splitter.on(',').withKeyValueSeparator(":").split("a:1,b:2,a:3");
fail();
} catch (IllegalArgumentException expected) {
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/SplitterTest.java | Java | asf20 | 21,157 |
/*
* Copyright (C) 2005 The Guava 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.common.base;
import static com.google.common.base.CharMatcher.WHITESPACE;
import static com.google.common.collect.Lists.newArrayList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Unit test for {@link Predicates}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class PredicatesTest extends TestCase {
private static final Predicate<Integer> TRUE = Predicates.alwaysTrue();
private static final Predicate<Integer> FALSE = Predicates.alwaysFalse();
private static final Predicate<Integer> NEVER_REACHED =
new Predicate<Integer>() {
@Override
public boolean apply(Integer i) {
throw new AssertionFailedError(
"This predicate should never have been evaluated");
}
};
/** Instantiable predicate with reasonable hashCode() and equals() methods. */
static class IsOdd implements Predicate<Integer>, Serializable {
private static final long serialVersionUID = 0x150ddL;
@Override
public boolean apply(Integer i) {
return (i.intValue() & 1) == 1;
}
@Override public int hashCode() {
return 0x150dd;
}
@Override public boolean equals(Object obj) {
return obj instanceof IsOdd;
}
@Override public String toString() {
return "IsOdd";
}
}
/**
* Generates a new Predicate per call.
*
* <p>Creating a new Predicate each time helps catch cases where code is
* using {@code x == y} instead of {@code x.equals(y)}.
*/
private static IsOdd isOdd() {
return new IsOdd();
}
/*
* Tests for Predicates.alwaysTrue().
*/
public void testAlwaysTrue_apply() {
assertEvalsToTrue(Predicates.alwaysTrue());
}
public void testAlwaysTrue_equality() throws Exception {
new EqualsTester()
.addEqualityGroup(TRUE, Predicates.alwaysTrue())
.addEqualityGroup(isOdd())
.addEqualityGroup(Predicates.alwaysFalse())
.testEquals();
}
/*
* Tests for Predicates.alwaysFalse().
*/
public void testAlwaysFalse_apply() throws Exception {
assertEvalsToFalse(Predicates.alwaysFalse());
}
public void testAlwaysFalse_equality() throws Exception {
new EqualsTester()
.addEqualityGroup(FALSE, Predicates.alwaysFalse())
.addEqualityGroup(isOdd())
.addEqualityGroup(Predicates.alwaysTrue())
.testEquals();
}
/*
* Tests for Predicates.not(predicate).
*/
public void testNot_apply() {
assertEvalsToTrue(Predicates.not(FALSE));
assertEvalsToFalse(Predicates.not(TRUE));
assertEvalsLikeOdd(Predicates.not(Predicates.not(isOdd())));
}
public void testNot_equality() {
new EqualsTester()
.addEqualityGroup(Predicates.not(isOdd()), Predicates.not(isOdd()))
.addEqualityGroup(Predicates.not(TRUE))
.addEqualityGroup(isOdd())
.testEquals();
}
public void testNot_equalityForNotOfKnownValues() {
new EqualsTester()
.addEqualityGroup(TRUE, Predicates.alwaysTrue())
.addEqualityGroup(FALSE)
.addEqualityGroup(Predicates.not(TRUE))
.testEquals();
new EqualsTester()
.addEqualityGroup(FALSE, Predicates.alwaysFalse())
.addEqualityGroup(TRUE)
.addEqualityGroup(Predicates.not(FALSE))
.testEquals();
new EqualsTester()
.addEqualityGroup(Predicates.isNull(), Predicates.isNull())
.addEqualityGroup(Predicates.notNull())
.addEqualityGroup(Predicates.not(Predicates.isNull()))
.testEquals();
new EqualsTester()
.addEqualityGroup(Predicates.notNull(), Predicates.notNull())
.addEqualityGroup(Predicates.isNull())
.addEqualityGroup(Predicates.not(Predicates.notNull()))
.testEquals();
}
/*
* Tests for all the different flavors of Predicates.and().
*/
@SuppressWarnings("unchecked") // varargs
public void testAnd_applyNoArgs() {
assertEvalsToTrue(Predicates.and());
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_equalityNoArgs() {
new EqualsTester()
.addEqualityGroup(Predicates.and(), Predicates.and())
.addEqualityGroup(Predicates.and(FALSE))
.addEqualityGroup(Predicates.or())
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_applyOneArg() {
assertEvalsLikeOdd(Predicates.and(isOdd()));
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_equalityOneArg() {
Object[] notEqualObjects = {Predicates.and(NEVER_REACHED, FALSE)};
new EqualsTester()
.addEqualityGroup(
Predicates.and(NEVER_REACHED), Predicates.and(NEVER_REACHED))
.addEqualityGroup(notEqualObjects)
.addEqualityGroup(Predicates.and(isOdd()))
.addEqualityGroup(Predicates.and())
.addEqualityGroup(Predicates.or(NEVER_REACHED))
.testEquals();
}
public void testAnd_applyBinary() {
assertEvalsLikeOdd(Predicates.and(isOdd(), TRUE));
assertEvalsLikeOdd(Predicates.and(TRUE, isOdd()));
assertEvalsToFalse(Predicates.and(FALSE, NEVER_REACHED));
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_equalityBinary() {
new EqualsTester()
.addEqualityGroup(
Predicates.and(TRUE, NEVER_REACHED),
Predicates.and(TRUE, NEVER_REACHED))
.addEqualityGroup(Predicates.and(NEVER_REACHED, TRUE))
.addEqualityGroup(Predicates.and(TRUE))
.addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED))
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_applyTernary() {
assertEvalsLikeOdd(Predicates.and(isOdd(), TRUE, TRUE));
assertEvalsLikeOdd(Predicates.and(TRUE, isOdd(), TRUE));
assertEvalsLikeOdd(Predicates.and(TRUE, TRUE, isOdd()));
assertEvalsToFalse(Predicates.and(TRUE, FALSE, NEVER_REACHED));
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_equalityTernary() {
new EqualsTester()
.addEqualityGroup(
Predicates.and(TRUE, isOdd(), NEVER_REACHED),
Predicates.and(TRUE, isOdd(), NEVER_REACHED))
.addEqualityGroup(Predicates.and(isOdd(), NEVER_REACHED, TRUE))
.addEqualityGroup(Predicates.and(TRUE))
.addEqualityGroup(Predicates.or(TRUE, isOdd(), NEVER_REACHED))
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_applyIterable() {
Collection<Predicate<Integer>> empty = Arrays.asList();
assertEvalsToTrue(Predicates.and(empty));
assertEvalsLikeOdd(Predicates.and(Arrays.asList(isOdd())));
assertEvalsLikeOdd(Predicates.and(Arrays.asList(TRUE, isOdd())));
assertEvalsToFalse(Predicates.and(Arrays.asList(FALSE, NEVER_REACHED)));
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_equalityIterable() {
new EqualsTester()
.addEqualityGroup(
Predicates.and(Arrays.asList(TRUE, NEVER_REACHED)),
Predicates.and(Arrays.asList(TRUE, NEVER_REACHED)),
Predicates.and(TRUE, NEVER_REACHED))
.addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED))
.addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED))
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testAnd_arrayDefensivelyCopied() {
Predicate[] array = {Predicates.alwaysFalse()};
Predicate<Object> predicate = Predicates.and(array);
assertFalse(predicate.apply(1));
array[0] = Predicates.alwaysTrue();
assertFalse(predicate.apply(1));
}
public void testAnd_listDefensivelyCopied() {
List<Predicate<Object>> list = newArrayList();
Predicate<Object> predicate = Predicates.and(list);
assertTrue(predicate.apply(1));
list.add(Predicates.alwaysFalse());
assertTrue(predicate.apply(1));
}
public void testAnd_iterableDefensivelyCopied() {
final List<Predicate<Object>> list = newArrayList();
Iterable<Predicate<Object>> iterable = new Iterable<Predicate<Object>>() {
@Override
public Iterator<Predicate<Object>> iterator() {
return list.iterator();
}
};
Predicate<Object> predicate = Predicates.and(iterable);
assertTrue(predicate.apply(1));
list.add(Predicates.alwaysFalse());
assertTrue(predicate.apply(1));
}
/*
* Tests for all the different flavors of Predicates.or().
*/
@SuppressWarnings("unchecked") // varargs
public void testOr_applyNoArgs() {
assertEvalsToFalse(Predicates.or());
}
@SuppressWarnings("unchecked") // varargs
public void testOr_equalityNoArgs() {
new EqualsTester()
.addEqualityGroup(Predicates.or(), Predicates.or())
.addEqualityGroup(Predicates.or(TRUE))
.addEqualityGroup(Predicates.and())
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testOr_applyOneArg() {
assertEvalsToTrue(Predicates.or(TRUE));
assertEvalsToFalse(Predicates.or(FALSE));
}
@SuppressWarnings("unchecked") // varargs
public void testOr_equalityOneArg() {
new EqualsTester()
.addEqualityGroup(
Predicates.or(NEVER_REACHED), Predicates.or(NEVER_REACHED))
.addEqualityGroup(Predicates.or(NEVER_REACHED, TRUE))
.addEqualityGroup(Predicates.or(TRUE))
.addEqualityGroup(Predicates.or())
.addEqualityGroup(Predicates.and(NEVER_REACHED))
.testEquals();
}
public void testOr_applyBinary() {
Predicate<Integer> falseOrFalse = Predicates.or(FALSE, FALSE);
Predicate<Integer> falseOrTrue = Predicates.or(FALSE, TRUE);
Predicate<Integer> trueOrAnything = Predicates.or(TRUE, NEVER_REACHED);
assertEvalsToFalse(falseOrFalse);
assertEvalsToTrue(falseOrTrue);
assertEvalsToTrue(trueOrAnything);
}
@SuppressWarnings("unchecked") // varargs
public void testOr_equalityBinary() {
new EqualsTester()
.addEqualityGroup(
Predicates.or(FALSE, NEVER_REACHED),
Predicates.or(FALSE, NEVER_REACHED))
.addEqualityGroup(Predicates.or(NEVER_REACHED, FALSE))
.addEqualityGroup(Predicates.or(TRUE))
.addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED))
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testOr_applyTernary() {
assertEvalsLikeOdd(Predicates.or(isOdd(), FALSE, FALSE));
assertEvalsLikeOdd(Predicates.or(FALSE, isOdd(), FALSE));
assertEvalsLikeOdd(Predicates.or(FALSE, FALSE, isOdd()));
assertEvalsToTrue(Predicates.or(FALSE, TRUE, NEVER_REACHED));
}
@SuppressWarnings("unchecked") // varargs
public void testOr_equalityTernary() {
new EqualsTester()
.addEqualityGroup(
Predicates.or(FALSE, NEVER_REACHED, TRUE),
Predicates.or(FALSE, NEVER_REACHED, TRUE))
.addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED, FALSE))
.addEqualityGroup(Predicates.or(TRUE))
.addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED, TRUE))
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testOr_applyIterable() {
Predicate<Integer> vacuouslyFalse =
Predicates.or(Collections.<Predicate<Integer>>emptyList());
Predicate<Integer> troo = Predicates.or(Collections.singletonList(TRUE));
/*
* newLinkedList() takes varargs. TRUE and FALSE are both instances of
* Predicate<Integer>, so the call is safe.
*/
Predicate<Integer> trueAndFalse = Predicates.or(Arrays.asList(TRUE, FALSE));
assertEvalsToFalse(vacuouslyFalse);
assertEvalsToTrue(troo);
assertEvalsToTrue(trueAndFalse);
}
@SuppressWarnings("unchecked") // varargs
public void testOr_equalityIterable() {
new EqualsTester()
.addEqualityGroup(
Predicates.or(Arrays.asList(FALSE, NEVER_REACHED)),
Predicates.or(Arrays.asList(FALSE, NEVER_REACHED)),
Predicates.or(FALSE, NEVER_REACHED))
.addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED))
.addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED))
.testEquals();
}
@SuppressWarnings("unchecked") // varargs
public void testOr_arrayDefensivelyCopied() {
Predicate[] array = {Predicates.alwaysFalse()};
Predicate<Object> predicate = Predicates.or(array);
assertFalse(predicate.apply(1));
array[0] = Predicates.alwaysTrue();
assertFalse(predicate.apply(1));
}
public void testOr_listDefensivelyCopied() {
List<Predicate<Object>> list = newArrayList();
Predicate<Object> predicate = Predicates.or(list);
assertFalse(predicate.apply(1));
list.add(Predicates.alwaysTrue());
assertFalse(predicate.apply(1));
}
public void testOr_iterableDefensivelyCopied() {
final List<Predicate<Object>> list = newArrayList();
Iterable<Predicate<Object>> iterable = new Iterable<Predicate<Object>>() {
@Override
public Iterator<Predicate<Object>> iterator() {
return list.iterator();
}
};
Predicate<Object> predicate = Predicates.or(iterable);
assertFalse(predicate.apply(1));
list.add(Predicates.alwaysTrue());
assertFalse(predicate.apply(1));
}
/*
* Tests for Predicates.equalTo(x).
*/
public void testIsEqualTo_apply() {
Predicate<Integer> isOne = Predicates.equalTo(1);
assertTrue(isOne.apply(1));
assertFalse(isOne.apply(2));
assertFalse(isOne.apply(null));
}
public void testIsEqualTo_equality() {
new EqualsTester()
.addEqualityGroup(Predicates.equalTo(1), Predicates.equalTo(1))
.addEqualityGroup(Predicates.equalTo(2))
.addEqualityGroup(Predicates.equalTo(null))
.testEquals();
}
public void testIsEqualToNull_apply() {
Predicate<Integer> isNull = Predicates.equalTo(null);
assertTrue(isNull.apply(null));
assertFalse(isNull.apply(1));
}
public void testIsEqualToNull_equality() {
new EqualsTester()
.addEqualityGroup(Predicates.equalTo(null), Predicates.equalTo(null))
.addEqualityGroup(Predicates.equalTo(1))
.addEqualityGroup(Predicates.equalTo("null"))
.testEquals();
}
/*
* Tests for Predicates.isNull()
*/
public void testIsNull_apply() {
Predicate<Integer> isNull = Predicates.isNull();
assertTrue(isNull.apply(null));
assertFalse(isNull.apply(1));
}
public void testIsNull_equality() {
new EqualsTester()
.addEqualityGroup(Predicates.isNull(), Predicates.isNull())
.addEqualityGroup(Predicates.notNull())
.testEquals();
}
public void testNotNull_apply() {
Predicate<Integer> notNull = Predicates.notNull();
assertFalse(notNull.apply(null));
assertTrue(notNull.apply(1));
}
public void testNotNull_equality() {
new EqualsTester()
.addEqualityGroup(Predicates.notNull(), Predicates.notNull())
.addEqualityGroup(Predicates.isNull())
.testEquals();
}
public void testIn_apply() {
Collection<Integer> nums = Arrays.asList(1, 5);
Predicate<Integer> isOneOrFive = Predicates.in(nums);
assertTrue(isOneOrFive.apply(1));
assertTrue(isOneOrFive.apply(5));
assertFalse(isOneOrFive.apply(3));
assertFalse(isOneOrFive.apply(null));
}
public void testIn_equality() {
Collection<Integer> nums = ImmutableSet.of(1, 5);
Collection<Integer> sameOrder = ImmutableSet.of(1, 5);
Collection<Integer> differentOrder = ImmutableSet.of(5, 1);
Collection<Integer> differentNums = ImmutableSet.of(1, 3, 5);
new EqualsTester()
.addEqualityGroup(Predicates.in(nums), Predicates.in(nums),
Predicates.in(sameOrder), Predicates.in(differentOrder))
.addEqualityGroup(Predicates.in(differentNums))
.testEquals();
}
public void testIn_handlesNullPointerException() {
class CollectionThatThrowsNPE<T> extends ArrayList<T> {
private static final long serialVersionUID = 1L;
@Override public boolean contains(Object element) {
Preconditions.checkNotNull(element);
return super.contains(element);
}
}
Collection<Integer> nums = new CollectionThatThrowsNPE<Integer>();
Predicate<Integer> isFalse = Predicates.in(nums);
assertFalse(isFalse.apply(null));
}
public void testIn_handlesClassCastException() {
class CollectionThatThrowsCCE<T> extends ArrayList<T> {
private static final long serialVersionUID = 1L;
@Override public boolean contains(Object element) {
throw new ClassCastException("");
}
}
Collection<Integer> nums = new CollectionThatThrowsCCE<Integer>();
nums.add(3);
Predicate<Integer> isThree = Predicates.in(nums);
assertFalse(isThree.apply(3));
}
/*
* Tests that compilation will work when applying explicit types.
*/
@SuppressWarnings("unused") // compilation test
public void testIn_compilesWithExplicitSupertype() {
Collection<Number> nums = ImmutableSet.of();
Predicate<Number> p1 = Predicates.in(nums);
Predicate<Object> p2 = Predicates.<Object>in(nums);
// The next two lines are not expected to compile.
// Predicate<Integer> p3 = Predicates.in(nums);
// Predicate<Integer> p4 = Predicates.<Integer>in(nums);
}
// enum singleton pattern
private enum TrimStringFunction implements Function<String, String> {
INSTANCE;
@Override
public String apply(String string) {
return WHITESPACE.trimFrom(string);
}
}
public void testCompose() {
Function<String, String> trim = TrimStringFunction.INSTANCE;
Predicate<String> equalsFoo = Predicates.equalTo("Foo");
Predicate<String> equalsBar = Predicates.equalTo("Bar");
Predicate<String> trimEqualsFoo = Predicates.compose(equalsFoo, trim);
Function<String, String> identity = Functions.identity();
assertTrue(trimEqualsFoo.apply("Foo"));
assertTrue(trimEqualsFoo.apply(" Foo "));
assertFalse(trimEqualsFoo.apply("Foo-b-que"));
new EqualsTester()
.addEqualityGroup(trimEqualsFoo, Predicates.compose(equalsFoo, trim))
.addEqualityGroup(equalsFoo)
.addEqualityGroup(trim)
.addEqualityGroup(Predicates.compose(equalsFoo, identity))
.addEqualityGroup(Predicates.compose(equalsBar, trim))
.testEquals();
}
public void assertEqualHashCode(
Predicate<? super Integer> expected, Predicate<? super Integer> actual) {
assertEquals(actual + " should hash like " + expected, expected.hashCode(), actual.hashCode());
}
public void testHashCodeForBooleanOperations() {
Predicate<Integer> p1 = Predicates.isNull();
Predicate<Integer> p2 = isOdd();
// Make sure that hash codes are not computed per-instance.
assertEqualHashCode(
Predicates.not(p1),
Predicates.not(p1));
assertEqualHashCode(
Predicates.and(p1, p2),
Predicates.and(p1, p2));
assertEqualHashCode(
Predicates.or(p1, p2),
Predicates.or(p1, p2));
// While not a contractual requirement, we'd like the hash codes for ands
// & ors of the same predicates to not collide.
assertTrue(Predicates.and(p1, p2).hashCode() != Predicates.or(p1, p2).hashCode());
}
private static void assertEvalsToTrue(Predicate<? super Integer> predicate) {
assertTrue(predicate.apply(0));
assertTrue(predicate.apply(1));
assertTrue(predicate.apply(null));
}
private static void assertEvalsToFalse(Predicate<? super Integer> predicate) {
assertFalse(predicate.apply(0));
assertFalse(predicate.apply(1));
assertFalse(predicate.apply(null));
}
private static void assertEvalsLikeOdd(Predicate<? super Integer> predicate) {
assertEvalsLike(isOdd(), predicate);
}
private static void assertEvalsLike(
Predicate<? super Integer> expected,
Predicate<? super Integer> actual) {
assertEvalsLike(expected, actual, 0);
assertEvalsLike(expected, actual, 1);
assertEvalsLike(expected, actual, null);
}
private static <T> void assertEvalsLike(
Predicate<? super T> expected,
Predicate<? super T> actual,
T input) {
Boolean expectedResult = null;
RuntimeException expectedRuntimeException = null;
try {
expectedResult = expected.apply(input);
} catch (RuntimeException e) {
expectedRuntimeException = e;
}
Boolean actualResult = null;
RuntimeException actualRuntimeException = null;
try {
actualResult = actual.apply(input);
} catch (RuntimeException e) {
actualRuntimeException = e;
}
assertEquals(expectedResult, actualResult);
if (expectedRuntimeException != null) {
assertNotNull(actualRuntimeException);
assertEquals(
expectedRuntimeException.getClass(),
actualRuntimeException.getClass());
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/PredicatesTest.java | Java | asf20 | 21,717 |
/*
* Copyright (C) 2008 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Unit test for {@link Joiner}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class JoinerTest extends TestCase {
private static final Joiner J = Joiner.on("-");
// <Integer> needed to prevent warning :(
private static final Iterable<Integer> ITERABLE_ = Arrays.<Integer>asList();
private static final Iterable<Integer> ITERABLE_1 = Arrays.asList(1);
private static final Iterable<Integer> ITERABLE_12 = Arrays.asList(1, 2);
private static final Iterable<Integer> ITERABLE_123 = Arrays.asList(1, 2, 3);
private static final Iterable<Integer> ITERABLE_NULL = Arrays.asList((Integer) null);
private static final Iterable<Integer> ITERABLE_NULL_NULL
= Arrays.asList((Integer) null, null);
private static final Iterable<Integer> ITERABLE_NULL_1 = Arrays.asList(null, 1);
private static final Iterable<Integer> ITERABLE_1_NULL = Arrays.asList(1, null);
private static final Iterable<Integer> ITERABLE_1_NULL_2 = Arrays.asList(1, null, 2);
private static final Iterable<Integer> ITERABLE_FOUR_NULLS
= Arrays.asList((Integer) null, null, null, null);
public void testNoSpecialNullBehavior() {
checkNoOutput(J, ITERABLE_);
checkResult(J, ITERABLE_1, "1");
checkResult(J, ITERABLE_12, "1-2");
checkResult(J, ITERABLE_123, "1-2-3");
try {
J.join(ITERABLE_NULL);
fail();
} catch (NullPointerException expected) {
}
try {
J.join(ITERABLE_1_NULL_2);
fail();
} catch (NullPointerException expected) {
}
try {
J.join(ITERABLE_NULL.iterator());
fail();
} catch (NullPointerException expected) {
}
try {
J.join(ITERABLE_1_NULL_2.iterator());
fail();
} catch (NullPointerException expected) {
}
}
public void testOnCharOverride() {
Joiner onChar = Joiner.on('-');
checkNoOutput(onChar, ITERABLE_);
checkResult(onChar, ITERABLE_1, "1");
checkResult(onChar, ITERABLE_12, "1-2");
checkResult(onChar, ITERABLE_123, "1-2-3");
}
public void testSkipNulls() {
Joiner skipNulls = J.skipNulls();
checkNoOutput(skipNulls, ITERABLE_);
checkNoOutput(skipNulls, ITERABLE_NULL);
checkNoOutput(skipNulls, ITERABLE_NULL_NULL);
checkNoOutput(skipNulls, ITERABLE_FOUR_NULLS);
checkResult(skipNulls, ITERABLE_1, "1");
checkResult(skipNulls, ITERABLE_12, "1-2");
checkResult(skipNulls, ITERABLE_123, "1-2-3");
checkResult(skipNulls, ITERABLE_NULL_1, "1");
checkResult(skipNulls, ITERABLE_1_NULL, "1");
checkResult(skipNulls, ITERABLE_1_NULL_2, "1-2");
}
public void testUseForNull() {
Joiner zeroForNull = J.useForNull("0");
checkNoOutput(zeroForNull, ITERABLE_);
checkResult(zeroForNull, ITERABLE_1, "1");
checkResult(zeroForNull, ITERABLE_12, "1-2");
checkResult(zeroForNull, ITERABLE_123, "1-2-3");
checkResult(zeroForNull, ITERABLE_NULL, "0");
checkResult(zeroForNull, ITERABLE_NULL_NULL, "0-0");
checkResult(zeroForNull, ITERABLE_NULL_1, "0-1");
checkResult(zeroForNull, ITERABLE_1_NULL, "1-0");
checkResult(zeroForNull, ITERABLE_1_NULL_2, "1-0-2");
checkResult(zeroForNull, ITERABLE_FOUR_NULLS, "0-0-0-0");
}
private static void checkNoOutput(Joiner joiner, Iterable<Integer> set) {
assertEquals("", joiner.join(set));
assertEquals("", joiner.join(set.iterator()));
Object[] array = Lists.newArrayList(set).toArray(new Integer[0]);
assertEquals("", joiner.join(array));
StringBuilder sb1FromIterable = new StringBuilder();
assertSame(sb1FromIterable, joiner.appendTo(sb1FromIterable, set));
assertEquals(0, sb1FromIterable.length());
StringBuilder sb1FromIterator = new StringBuilder();
assertSame(sb1FromIterator, joiner.appendTo(sb1FromIterator, set));
assertEquals(0, sb1FromIterator.length());
StringBuilder sb2 = new StringBuilder();
assertSame(sb2, joiner.appendTo(sb2, array));
assertEquals(0, sb2.length());
try {
joiner.appendTo(NASTY_APPENDABLE, set);
} catch (IOException e) {
throw new AssertionError(e);
}
try {
joiner.appendTo(NASTY_APPENDABLE, set.iterator());
} catch (IOException e) {
throw new AssertionError(e);
}
try {
joiner.appendTo(NASTY_APPENDABLE, array);
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static final Appendable NASTY_APPENDABLE = new Appendable() {
@Override
public Appendable append(CharSequence csq) throws IOException {
throw new IOException();
}
@Override
public Appendable append(CharSequence csq, int start, int end) throws IOException {
throw new IOException();
}
@Override
public Appendable append(char c) throws IOException {
throw new IOException();
}
};
private static void checkResult(Joiner joiner, Iterable<Integer> parts, String expected) {
assertEquals(expected, joiner.join(parts));
assertEquals(expected, joiner.join(parts.iterator()));
StringBuilder sb1FromIterable = new StringBuilder().append('x');
joiner.appendTo(sb1FromIterable, parts);
assertEquals("x" + expected, sb1FromIterable.toString());
StringBuilder sb1FromIterator = new StringBuilder().append('x');
joiner.appendTo(sb1FromIterator, parts.iterator());
assertEquals("x" + expected, sb1FromIterator.toString());
Integer[] partsArray = Lists.newArrayList(parts).toArray(new Integer[0]);
assertEquals(expected, joiner.join(partsArray));
StringBuilder sb2 = new StringBuilder().append('x');
joiner.appendTo(sb2, partsArray);
assertEquals("x" + expected, sb2.toString());
int num = partsArray.length - 2;
if (num >= 0) {
Object[] rest = new Integer[num];
for (int i = 0; i < num; i++) {
rest[i] = partsArray[i + 2];
}
assertEquals(expected, joiner.join(partsArray[0], partsArray[1], rest));
StringBuilder sb3 = new StringBuilder().append('x');
joiner.appendTo(sb3, partsArray[0], partsArray[1], rest);
assertEquals("x" + expected, sb3.toString());
}
}
public void test_useForNull_skipNulls() {
Joiner j = Joiner.on("x").useForNull("y");
try {
j = j.skipNulls();
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void test_skipNulls_useForNull() {
Joiner j = Joiner.on("x").skipNulls();
try {
j = j.useForNull("y");
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void test_useForNull_twice() {
Joiner j = Joiner.on("x").useForNull("y");
try {
j = j.useForNull("y");
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void testMap() {
MapJoiner j = Joiner.on(";").withKeyValueSeparator(":");
assertEquals("", j.join(ImmutableMap.of()));
assertEquals(":", j.join(ImmutableMap.of("", "")));
Map<String, String> mapWithNulls = Maps.newLinkedHashMap();
mapWithNulls.put("a", null);
mapWithNulls.put(null, "b");
try {
j.join(mapWithNulls);
fail();
} catch (NullPointerException expected) {
}
assertEquals("a:00;00:b", j.useForNull("00").join(mapWithNulls));
StringBuilder sb = new StringBuilder();
j.appendTo(sb, ImmutableMap.of(1, 2, 3, 4, 5, 6));
assertEquals("1:2;3:4;5:6", sb.toString());
}
public void testEntries() {
MapJoiner j = Joiner.on(";").withKeyValueSeparator(":");
assertEquals("", j.join(ImmutableMultimap.of().entries()));
assertEquals("", j.join(ImmutableMultimap.of().entries().iterator()));
assertEquals(":", j.join(ImmutableMultimap.of("", "").entries()));
assertEquals(":", j.join(ImmutableMultimap.of("", "").entries().iterator()));
assertEquals("1:a;1:b", j.join(ImmutableMultimap.of("1", "a", "1", "b").entries()));
assertEquals("1:a;1:b", j.join(ImmutableMultimap.of("1", "a", "1", "b").entries().iterator()));
Map<String, String> mapWithNulls = Maps.newLinkedHashMap();
mapWithNulls.put("a", null);
mapWithNulls.put(null, "b");
Set<Map.Entry<String, String>> entriesWithNulls = mapWithNulls.entrySet();
try {
j.join(entriesWithNulls);
fail();
} catch (NullPointerException expected) {
}
try {
j.join(entriesWithNulls.iterator());
fail();
} catch (NullPointerException expected) {
}
assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls));
assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls.iterator()));
StringBuilder sb1 = new StringBuilder();
j.appendTo(sb1, ImmutableMultimap.of(1, 2, 3, 4, 5, 6, 1, 3, 5, 10).entries());
assertEquals("1:2;1:3;3:4;5:6;5:10", sb1.toString());
StringBuilder sb2 = new StringBuilder();
j.appendTo(sb2, ImmutableMultimap.of(1, 2, 3, 4, 5, 6, 1, 3, 5, 10).entries().iterator());
assertEquals("1:2;1:3;3:4;5:6;5:10", sb2.toString());
}
@SuppressWarnings("ReturnValueIgnored") // testing for exception
public void test_skipNulls_onMap() {
Joiner j = Joiner.on(",").skipNulls();
try {
j.withKeyValueSeparator("/");
fail();
} catch (UnsupportedOperationException expected) {
}
}
private static class DontStringMeBro implements CharSequence {
@Override
public int length() {
return 3;
}
@Override
public char charAt(int index) {
return "foo".charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return "foo".subSequence(start, end);
}
@Override public String toString() {
throw new AssertionFailedError("shouldn't be invoked");
}
}
// Don't do this.
private static class IterableIterator implements Iterable<Integer>, Iterator<Integer> {
private static final ImmutableSet<Integer> INTEGERS = ImmutableSet.of(1, 2, 3, 4);
private final Iterator<Integer> iterator;
public IterableIterator() {
this.iterator = iterator();
}
@Override public Iterator<Integer> iterator() {
return INTEGERS.iterator();
}
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public Integer next() {
return iterator.next();
}
@Override public void remove() {
iterator.remove();
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/JoinerTest.java | Java | asf20 | 11,456 |
/*
* Copyright (C) 2007 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Unit test for {@code AbstractIterator}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
// TODO(cpovirk): why is this slow (>1m/test) under GWT when fully optimized?
public class AbstractIteratorTest extends TestCase {
public void testDefaultBehaviorOfNextAndHasNext() {
// This sample AbstractIterator returns 0 on the first call, 1 on the
// second, then signals that it's reached the end of the data
Iterator<Integer> iter = new AbstractIterator<Integer>() {
private int rep;
@Override public Integer computeNext() {
switch (rep++) {
case 0:
return 0;
case 1:
return 1;
case 2:
return endOfData();
default:
fail("Should not have been invoked again");
return null;
}
}
};
assertTrue(iter.hasNext());
assertEquals(0, (int) iter.next());
// verify idempotence of hasNext()
assertTrue(iter.hasNext());
assertTrue(iter.hasNext());
assertTrue(iter.hasNext());
assertEquals(1, (int) iter.next());
assertFalse(iter.hasNext());
// Make sure computeNext() doesn't get invoked again
assertFalse(iter.hasNext());
try {
iter.next();
fail("no exception thrown");
} catch (NoSuchElementException expected) {
}
}
public void testSneakyThrow() throws Exception {
Iterator<Integer> iter = new AbstractIterator<Integer>() {
boolean haveBeenCalled;
@Override public Integer computeNext() {
if (haveBeenCalled) {
fail("Should not have been called again");
} else {
haveBeenCalled = true;
sneakyThrow(new SomeCheckedException());
}
return null; // never reached
}
};
// The first time, the sneakily-thrown exception comes out
try {
iter.hasNext();
fail("No exception thrown");
} catch (Exception e) {
if (!(e instanceof SomeCheckedException)) {
throw e;
}
}
// But the second time, AbstractIterator itself throws an ISE
try {
iter.hasNext();
fail("No exception thrown");
} catch (IllegalStateException expected) {
}
}
public void testException() {
final SomeUncheckedException exception = new SomeUncheckedException();
Iterator<Integer> iter = new AbstractIterator<Integer>() {
@Override public Integer computeNext() {
throw exception;
}
};
// It should pass through untouched
try {
iter.hasNext();
fail("No exception thrown");
} catch (SomeUncheckedException e) {
assertSame(exception, e);
}
}
public void testExceptionAfterEndOfData() {
Iterator<Integer> iter = new AbstractIterator<Integer>() {
@Override public Integer computeNext() {
endOfData();
throw new SomeUncheckedException();
}
};
try {
iter.hasNext();
fail("No exception thrown");
} catch (SomeUncheckedException expected) {
}
}
public void testCantRemove() {
Iterator<Integer> iter = new AbstractIterator<Integer>() {
boolean haveBeenCalled;
@Override public Integer computeNext() {
if (haveBeenCalled) {
endOfData();
}
haveBeenCalled = true;
return 0;
}
};
assertEquals(0, (int) iter.next());
try {
iter.remove();
fail("No exception thrown");
} catch (UnsupportedOperationException expected) {
}
}
public void testReentrantHasNext() {
Iterator<Integer> iter = new AbstractIterator<Integer>() {
@Override protected Integer computeNext() {
hasNext();
return null;
}
};
try {
iter.hasNext();
fail();
} catch (IllegalStateException expected) {
}
}
// Technically we should test other reentrant scenarios (4 combinations of
// hasNext/next), but we'll cop out for now, knowing that
// next() both start by invoking hasNext() anyway.
/**
* Throws a undeclared checked exception.
*/
private static void sneakyThrow(Throwable t) {
class SneakyThrower<T extends Throwable> {
@SuppressWarnings("unchecked") // intentionally unsafe for test
void throwIt(Throwable t) throws T {
throw (T) t;
}
}
new SneakyThrower<Error>().throwIt(t);
}
private static class SomeCheckedException extends Exception {
}
private static class SomeUncheckedException extends RuntimeException {
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/AbstractIteratorTest.java | Java | asf20 | 5,299 |
/*
* Copyright (C) 2006 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
/**
* Tests for {@link Objects}.
*
* @author Laurence Gonsalves
*/
@GwtCompatible(emulated = true)
public class ObjectsTest extends TestCase {
public void testEqual() throws Exception {
assertTrue(Objects.equal(1, 1));
assertTrue(Objects.equal(null, null));
// test distinct string objects
String s1 = "foobar";
String s2 = new String(s1);
assertTrue(Objects.equal(s1, s2));
assertFalse(Objects.equal(s1, null));
assertFalse(Objects.equal(null, s1));
assertFalse(Objects.equal("foo", "bar"));
assertFalse(Objects.equal("1", 1));
}
public void testHashCode() throws Exception {
int h1 = Objects.hashCode(1, "two", 3.0);
int h2 = Objects.hashCode(
new Integer(1), new String("two"), new Double(3.0));
// repeatable
assertEquals(h1, h2);
// These don't strictly need to be true, but they're nice properties.
assertTrue(Objects.hashCode(1, 2, null) != Objects.hashCode(1, 2));
assertTrue(Objects.hashCode(1, 2, null) != Objects.hashCode(1, null, 2));
assertTrue(Objects.hashCode(1, null, 2) != Objects.hashCode(1, 2));
assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(3, 2, 1));
assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(2, 3, 1));
}
public void testFirstNonNull_withNonNull() throws Exception {
String s1 = "foo";
String s2 = Objects.firstNonNull(s1, "bar");
assertSame(s1, s2);
Long n1 = new Long(42);
Long n2 = Objects.firstNonNull(null, n1);
assertSame(n1, n2);
}
public void testFirstNonNull_throwsNullPointerException() throws Exception {
try {
Objects.firstNonNull(null, null);
fail("expected NullPointerException");
} catch (NullPointerException expected) {
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/ObjectsTest.java | Java | asf20 | 2,478 |
/*
* Copyright (C) 2006 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
/**
* Unit test for {@link Preconditions}.
*
* @author Kevin Bourrillion
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class PreconditionsTest extends TestCase {
public void testCheckArgument_simple_success() {
Preconditions.checkArgument(true);
}
public void testCheckArgument_simple_failure() {
try {
Preconditions.checkArgument(false);
fail("no exception thrown");
} catch (IllegalArgumentException expected) {
}
}
public void testCheckArgument_simpleMessage_success() {
Preconditions.checkArgument(true, IGNORE_ME);
}
public void testCheckArgument_simpleMessage_failure() {
try {
Preconditions.checkArgument(false, new Message());
fail("no exception thrown");
} catch (IllegalArgumentException expected) {
verifySimpleMessage(expected);
}
}
public void testCheckArgument_nullMessage_failure() {
try {
Preconditions.checkArgument(false, null);
fail("no exception thrown");
} catch (IllegalArgumentException expected) {
assertEquals("null", expected.getMessage());
}
}
public void testCheckArgument_complexMessage_success() {
Preconditions.checkArgument(true, "%s", IGNORE_ME);
}
public void testCheckArgument_complexMessage_failure() {
try {
Preconditions.checkArgument(false, FORMAT, 5);
fail("no exception thrown");
} catch (IllegalArgumentException expected) {
verifyComplexMessage(expected);
}
}
public void testCheckState_simple_success() {
Preconditions.checkState(true);
}
public void testCheckState_simple_failure() {
try {
Preconditions.checkState(false);
fail("no exception thrown");
} catch (IllegalStateException expected) {
}
}
public void testCheckState_simpleMessage_success() {
Preconditions.checkState(true, IGNORE_ME);
}
public void testCheckState_simpleMessage_failure() {
try {
Preconditions.checkState(false, new Message());
fail("no exception thrown");
} catch (IllegalStateException expected) {
verifySimpleMessage(expected);
}
}
public void testCheckState_nullMessage_failure() {
try {
Preconditions.checkState(false, null);
fail("no exception thrown");
} catch (IllegalStateException expected) {
assertEquals("null", expected.getMessage());
}
}
public void testCheckState_complexMessage_success() {
Preconditions.checkState(true, "%s", IGNORE_ME);
}
public void testCheckState_complexMessage_failure() {
try {
Preconditions.checkState(false, FORMAT, 5);
fail("no exception thrown");
} catch (IllegalStateException expected) {
verifyComplexMessage(expected);
}
}
private static final String NON_NULL_STRING = "foo";
public void testCheckNotNull_simple_success() {
String result = Preconditions.checkNotNull(NON_NULL_STRING);
assertSame(NON_NULL_STRING, result);
}
public void testCheckNotNull_simple_failure() {
try {
Preconditions.checkNotNull(null);
fail("no exception thrown");
} catch (NullPointerException expected) {
}
}
public void testCheckNotNull_simpleMessage_success() {
String result = Preconditions.checkNotNull(NON_NULL_STRING, IGNORE_ME);
assertSame(NON_NULL_STRING, result);
}
public void testCheckNotNull_simpleMessage_failure() {
try {
Preconditions.checkNotNull(null, new Message());
fail("no exception thrown");
} catch (NullPointerException expected) {
verifySimpleMessage(expected);
}
}
public void testCheckNotNull_complexMessage_success() {
String result = Preconditions.checkNotNull(
NON_NULL_STRING, "%s", IGNORE_ME);
assertSame(NON_NULL_STRING, result);
}
public void testCheckNotNull_complexMessage_failure() {
try {
Preconditions.checkNotNull(null, FORMAT, 5);
fail("no exception thrown");
} catch (NullPointerException expected) {
verifyComplexMessage(expected);
}
}
public void testCheckElementIndex_ok() {
assertEquals(0, Preconditions.checkElementIndex(0, 1));
assertEquals(0, Preconditions.checkElementIndex(0, 2));
assertEquals(1, Preconditions.checkElementIndex(1, 2));
}
public void testCheckElementIndex_badSize() {
try {
Preconditions.checkElementIndex(1, -1);
fail();
} catch (IllegalArgumentException expected) {
// don't care what the message text is, as this is an invalid usage of
// the Preconditions class, unlike all the other exceptions it throws
}
}
public void testCheckElementIndex_negative() {
try {
Preconditions.checkElementIndex(-1, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("index (-1) must not be negative", expected.getMessage());
}
}
public void testCheckElementIndex_tooHigh() {
try {
Preconditions.checkElementIndex(1, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("index (1) must be less than size (1)",
expected.getMessage());
}
}
public void testCheckElementIndex_withDesc_negative() {
try {
Preconditions.checkElementIndex(-1, 1, "foo");
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("foo (-1) must not be negative", expected.getMessage());
}
}
public void testCheckElementIndex_withDesc_tooHigh() {
try {
Preconditions.checkElementIndex(1, 1, "foo");
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("foo (1) must be less than size (1)",
expected.getMessage());
}
}
public void testCheckPositionIndex_ok() {
assertEquals(0, Preconditions.checkPositionIndex(0, 0));
assertEquals(0, Preconditions.checkPositionIndex(0, 1));
assertEquals(1, Preconditions.checkPositionIndex(1, 1));
}
public void testCheckPositionIndex_badSize() {
try {
Preconditions.checkPositionIndex(1, -1);
fail();
} catch (IllegalArgumentException expected) {
// don't care what the message text is, as this is an invalid usage of
// the Preconditions class, unlike all the other exceptions it throws
}
}
public void testCheckPositionIndex_negative() {
try {
Preconditions.checkPositionIndex(-1, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("index (-1) must not be negative", expected.getMessage());
}
}
public void testCheckPositionIndex_tooHigh() {
try {
Preconditions.checkPositionIndex(2, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("index (2) must not be greater than size (1)",
expected.getMessage());
}
}
public void testCheckPositionIndex_withDesc_negative() {
try {
Preconditions.checkPositionIndex(-1, 1, "foo");
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("foo (-1) must not be negative", expected.getMessage());
}
}
public void testCheckPositionIndex_withDesc_tooHigh() {
try {
Preconditions.checkPositionIndex(2, 1, "foo");
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("foo (2) must not be greater than size (1)",
expected.getMessage());
}
}
public void testCheckPositionIndexes_ok() {
Preconditions.checkPositionIndexes(0, 0, 0);
Preconditions.checkPositionIndexes(0, 0, 1);
Preconditions.checkPositionIndexes(0, 1, 1);
Preconditions.checkPositionIndexes(1, 1, 1);
}
public void testCheckPositionIndexes_badSize() {
try {
Preconditions.checkPositionIndexes(1, 1, -1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testCheckPositionIndex_startNegative() {
try {
Preconditions.checkPositionIndexes(-1, 1, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("start index (-1) must not be negative",
expected.getMessage());
}
}
public void testCheckPositionIndexes_endTooHigh() {
try {
Preconditions.checkPositionIndexes(0, 2, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("end index (2) must not be greater than size (1)",
expected.getMessage());
}
}
public void testCheckPositionIndexes_reversed() {
try {
Preconditions.checkPositionIndexes(1, 0, 1);
fail();
} catch (IndexOutOfBoundsException expected) {
assertEquals("end index (0) must not be less than start index (1)",
expected.getMessage());
}
}
public void testFormat() {
assertEquals("%s", Preconditions.format("%s"));
assertEquals("5", Preconditions.format("%s", 5));
assertEquals("foo [5]", Preconditions.format("foo", 5));
assertEquals("foo [5, 6, 7]", Preconditions.format("foo", 5, 6, 7));
assertEquals("%s 1 2", Preconditions.format("%s %s %s", "%s", 1, 2));
assertEquals(" [5, 6]", Preconditions.format("", 5, 6));
assertEquals("123", Preconditions.format("%s%s%s", 1, 2, 3));
assertEquals("1%s%s", Preconditions.format("%s%s%s", 1));
assertEquals("5 + 6 = 11", Preconditions.format("%s + 6 = 11", 5));
assertEquals("5 + 6 = 11", Preconditions.format("5 + %s = 11", 6));
assertEquals("5 + 6 = 11", Preconditions.format("5 + 6 = %s", 11));
assertEquals("5 + 6 = 11", Preconditions.format("%s + %s = %s", 5, 6, 11));
assertEquals("null [null, null]",
Preconditions.format("%s", null, null, null));
assertEquals("null [5, 6]", Preconditions.format(null, 5, 6));
}
private static final Object IGNORE_ME = new Object() {
@Override public String toString() {
throw new AssertionFailedError();
}
};
private static class Message {
boolean invoked;
@Override public String toString() {
assertFalse(invoked);
invoked = true;
return "A message";
}
}
private static final String FORMAT = "I ate %s pies.";
private static void verifySimpleMessage(Exception e) {
assertEquals("A message", e.getMessage());
}
private static void verifyComplexMessage(Exception e) {
assertEquals("I ate 5 pies.", e.getMessage());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/PreconditionsTest.java | Java | asf20 | 11,033 |
/*
* Copyright (C) 2010 The Guava 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
* diOBJECTibuted under the License is diOBJECTibuted on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence.Wrapper;
import com.google.common.collect.ImmutableList;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.EquivalenceTester;
import junit.framework.TestCase;
/**
* Unit test for {@link Equivalence}.
*
* @author Jige Yu
*/
@GwtCompatible(emulated = true)
public class EquivalenceTest extends TestCase {
@SuppressWarnings("unchecked") // varargs
public void testPairwiseEquivalent() {
EquivalenceTester.of(Equivalence.equals().<String>pairwise())
.addEquivalenceGroup(ImmutableList.<String>of())
.addEquivalenceGroup(ImmutableList.of("a"))
.addEquivalenceGroup(ImmutableList.of("b"))
.addEquivalenceGroup(ImmutableList.of("a", "b"), ImmutableList.of("a", "b"))
.test();
}
public void testPairwiseEquivalent_equals() {
new EqualsTester()
.addEqualityGroup(Equivalence.equals().pairwise(), Equivalence.equals().pairwise())
.addEqualityGroup(Equivalence.identity().pairwise())
.testEquals();
}
private enum LengthFunction implements Function<String, Integer> {
INSTANCE;
@Override public Integer apply(String input) {
return input.length();
}
}
private static final Equivalence<String> LENGTH_EQUIVALENCE = Equivalence.equals()
.onResultOf(LengthFunction.INSTANCE);
public void testWrap() {
new EqualsTester()
.addEqualityGroup(
LENGTH_EQUIVALENCE.wrap("hello"),
LENGTH_EQUIVALENCE.wrap("hello"),
LENGTH_EQUIVALENCE.wrap("world"))
.addEqualityGroup(
LENGTH_EQUIVALENCE.wrap("hi"),
LENGTH_EQUIVALENCE.wrap("yo"))
.addEqualityGroup(
LENGTH_EQUIVALENCE.wrap(null),
LENGTH_EQUIVALENCE.wrap(null))
.addEqualityGroup(Equivalence.equals().wrap("hello"))
.addEqualityGroup(Equivalence.equals().wrap(null))
.testEquals();
}
public void testWrap_get() {
String test = "test";
Wrapper<String> wrapper = LENGTH_EQUIVALENCE.wrap(test);
assertSame(test, wrapper.get());
}
private static class IntValue {
private final int value;
IntValue(int value) {
this.value = value;
}
@Override public String toString() {
return "value = " + value;
}
}
public void testOnResultOf() {
EquivalenceTester.of(Equivalence.equals().onResultOf(Functions.toStringFunction()))
.addEquivalenceGroup(new IntValue(1), new IntValue(1))
.addEquivalenceGroup(new IntValue(2))
.test();
}
public void testOnResultOf_equals() {
new EqualsTester()
.addEqualityGroup(
Equivalence.identity().onResultOf(Functions.toStringFunction()),
Equivalence.identity().onResultOf(Functions.toStringFunction()))
.addEqualityGroup(Equivalence.equals().onResultOf(Functions.toStringFunction()))
.addEqualityGroup(Equivalence.identity().onResultOf(Functions.identity()))
.testEquals();
}
public void testEquivalentTo() {
Predicate<Object> equalTo1 = Equivalence.equals().equivalentTo("1");
assertTrue(equalTo1.apply("1"));
assertFalse(equalTo1.apply("2"));
assertFalse(equalTo1.apply(null));
Predicate<Object> isNull = Equivalence.equals().equivalentTo(null);
assertFalse(isNull.apply("1"));
assertFalse(isNull.apply("2"));
assertTrue(isNull.apply(null));
new EqualsTester()
.addEqualityGroup(equalTo1, Equivalence.equals().equivalentTo("1"))
.addEqualityGroup(isNull)
.addEqualityGroup(Equivalence.identity().equivalentTo("1"))
.testEquals();
}
public void testEqualsEquivalent() {
EquivalenceTester.of(Equivalence.equals())
.addEquivalenceGroup(new Integer(42), 42)
.addEquivalenceGroup("a")
.test();
}
public void testIdentityEquivalent() {
EquivalenceTester.of(Equivalence.identity())
.addEquivalenceGroup(new Integer(42))
.addEquivalenceGroup(new Integer(42))
.addEquivalenceGroup("a")
.test();
}
public void testEquals() {
new EqualsTester()
.addEqualityGroup(Equivalence.equals(), Equivalence.equals())
.addEqualityGroup(Equivalence.identity(), Equivalence.identity())
.testEquals();
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/EquivalenceTest.java | Java | asf20 | 5,007 |
/*
* Copyright (C) 2011 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.SerializableTester;
import junit.framework.TestCase;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Tests for {@link Enums}.
*
* @author Steve McKay
*/
@GwtCompatible(emulated = true)
public class EnumsTest extends TestCase {
private enum TestEnum {
CHEETO,
HONDA,
POODLE,
}
private enum OtherEnum {}
public void testValueOfFunction() {
Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class);
assertEquals(TestEnum.CHEETO, function.apply("CHEETO"));
assertEquals(TestEnum.HONDA, function.apply("HONDA"));
assertEquals(TestEnum.POODLE, function.apply("POODLE"));
}
public void testValueOfFunction_caseSensitive() {
Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class);
assertNull(function.apply("cHEETO"));
assertNull(function.apply("Honda"));
assertNull(function.apply("poodlE"));
}
public void testValueOfFunction_nullWhenNoMatchingConstant() {
Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class);
assertNull(function.apply("WOMBAT"));
}
public void testValueOfFunction_equals() {
new EqualsTester()
.addEqualityGroup(
Enums.valueOfFunction(TestEnum.class), Enums.valueOfFunction(TestEnum.class))
.addEqualityGroup(Enums.valueOfFunction(OtherEnum.class))
.testEquals();
}
public void testGetIfPresent() {
assertEquals(Optional.of(TestEnum.CHEETO), Enums.getIfPresent(TestEnum.class, "CHEETO"));
assertEquals(Optional.of(TestEnum.HONDA), Enums.getIfPresent(TestEnum.class, "HONDA"));
assertEquals(Optional.of(TestEnum.POODLE), Enums.getIfPresent(TestEnum.class, "POODLE"));
assertTrue(Enums.getIfPresent(TestEnum.class, "CHEETO").isPresent());
assertTrue(Enums.getIfPresent(TestEnum.class, "HONDA").isPresent());
assertTrue(Enums.getIfPresent(TestEnum.class, "POODLE").isPresent());
assertEquals(TestEnum.CHEETO, Enums.getIfPresent(TestEnum.class, "CHEETO").get());
assertEquals(TestEnum.HONDA, Enums.getIfPresent(TestEnum.class, "HONDA").get());
assertEquals(TestEnum.POODLE, Enums.getIfPresent(TestEnum.class, "POODLE").get());
}
public void testGetIfPresent_caseSensitive() {
assertFalse(Enums.getIfPresent(TestEnum.class, "cHEETO").isPresent());
assertFalse(Enums.getIfPresent(TestEnum.class, "Honda").isPresent());
assertFalse(Enums.getIfPresent(TestEnum.class, "poodlE").isPresent());
}
public void testGetIfPresent_whenNoMatchingConstant() {
assertEquals(Optional.absent(), Enums.getIfPresent(TestEnum.class, "WOMBAT"));
}
// Create a second ClassLoader and use it to get a second version of the TestEnum class.
// Run Enums.getIfPresent on that other TestEnum and then return a WeakReference containing the
// new ClassLoader. If Enums.getIfPresent does caching that prevents the shadow TestEnum
// (and therefore its ClassLoader) from being unloaded, then this WeakReference will never be
// cleared.
public void testStringConverter_convert() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertEquals(TestEnum.CHEETO, converter.convert("CHEETO"));
assertEquals(TestEnum.HONDA, converter.convert("HONDA"));
assertEquals(TestEnum.POODLE, converter.convert("POODLE"));
assertNull(converter.convert(null));
assertNull(converter.reverse().convert(null));
}
public void testStringConverter_convertError() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
try {
converter.convert("xxx");
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testStringConverter_reverse() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertEquals("CHEETO", converter.reverse().convert(TestEnum.CHEETO));
assertEquals("HONDA", converter.reverse().convert(TestEnum.HONDA));
assertEquals("POODLE", converter.reverse().convert(TestEnum.POODLE));
}
public void testStringConverter_nullConversions() {
Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
assertNull(converter.convert(null));
assertNull(converter.reverse().convert(null));
}
public void testStringConverter_serialization() {
SerializableTester.reserializeAndAssert(Enums.stringConverter(TestEnum.class));
}
@Retention(RetentionPolicy.RUNTIME)
private @interface ExampleAnnotation {}
private enum AnEnum {
@ExampleAnnotation FOO,
BAR
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/EnumsTest.java | Java | asf20 | 5,340 |
/*
* Copyright (C) 2011 The Guava 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.common.base;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import junit.framework.TestCase;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Unit test for {@link Optional}.
*
* @author Kurt Alfred Kluever
*/
@GwtCompatible(emulated = true)
public final class OptionalTest extends TestCase {
public void testAbsent() {
Optional<String> optionalName = Optional.absent();
assertFalse(optionalName.isPresent());
}
public void testOf() {
assertEquals("training", Optional.of("training").get());
}
public void testOf_null() {
try {
Optional.of(null);
fail();
} catch (NullPointerException expected) {
}
}
public void testFromNullable() {
Optional<String> optionalName = Optional.fromNullable("bob");
assertEquals("bob", optionalName.get());
}
public void testFromNullable_null() {
// not promised by spec, but easier to test
assertSame(Optional.absent(), Optional.fromNullable(null));
}
public void testIsPresent_no() {
assertFalse(Optional.absent().isPresent());
}
public void testIsPresent_yes() {
assertTrue(Optional.of("training").isPresent());
}
public void testGet_absent() {
Optional<String> optional = Optional.absent();
try {
optional.get();
fail();
} catch (IllegalStateException expected) {
}
}
public void testGet_present() {
assertEquals("training", Optional.of("training").get());
}
public void testOr_T_present() {
assertEquals("a", Optional.of("a").or("default"));
}
public void testOr_T_absent() {
assertEquals("default", Optional.absent().or("default"));
}
public void testOr_supplier_present() {
assertEquals("a", Optional.of("a").or(Suppliers.ofInstance("fallback")));
}
public void testOr_supplier_absent() {
assertEquals("fallback", Optional.absent().or(Suppliers.ofInstance("fallback")));
}
public void testOr_nullSupplier_absent() {
Supplier<Object> nullSupplier = Suppliers.ofInstance(null);
Optional<Object> absentOptional = Optional.absent();
try {
absentOptional.or(nullSupplier);
fail();
} catch (NullPointerException expected) {
}
}
public void testOr_nullSupplier_present() {
Supplier<String> nullSupplier = Suppliers.ofInstance(null);
assertEquals("a", Optional.of("a").or(nullSupplier));
}
public void testOr_Optional_present() {
assertEquals(Optional.of("a"), Optional.of("a").or(Optional.of("fallback")));
}
public void testOr_Optional_absent() {
assertEquals(Optional.of("fallback"), Optional.absent().or(Optional.of("fallback")));
}
public void testOrNull_present() {
assertEquals("a", Optional.of("a").orNull());
}
public void testOrNull_absent() {
assertNull(Optional.absent().orNull());
}
public void testAsSet_present() {
Set<String> expected = Collections.singleton("a");
assertEquals(expected, Optional.of("a").asSet());
}
public void testAsSet_absent() {
assertTrue("Returned set should be empty", Optional.absent().asSet().isEmpty());
}
public void testAsSet_presentIsImmutable() {
Set<String> presentAsSet = Optional.of("a").asSet();
try {
presentAsSet.add("b");
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void testAsSet_absentIsImmutable() {
Set<Object> absentAsSet = Optional.absent().asSet();
try {
absentAsSet.add("foo");
fail();
} catch (UnsupportedOperationException expected) {
}
}
public void testTransform_absent() {
assertEquals(Optional.absent(), Optional.absent().transform(Functions.identity()));
assertEquals(Optional.absent(), Optional.absent().transform(Functions.toStringFunction()));
}
public void testTransform_presentIdentity() {
assertEquals(Optional.of("a"), Optional.of("a").transform(Functions.identity()));
}
public void testTransform_presentToString() {
assertEquals(Optional.of("42"), Optional.of(42).transform(Functions.toStringFunction()));
}
public void testTransform_present_functionReturnsNull() {
try {
Optional.of("a").transform(
new Function<String, String>() {
@Override public String apply(String input) {
return null;
}
});
fail("Should throw if Function returns null.");
} catch (NullPointerException expected) {
}
}
public void testTransform_abssent_functionReturnsNull() {
assertEquals(Optional.absent(),
Optional.absent().transform(
new Function<Object, Object>() {
@Override public Object apply(Object input) {
return null;
}
}));
}
// TODO(kevinb): use EqualsTester
public void testEqualsAndHashCode_absent() {
assertEquals(Optional.<String>absent(), Optional.<Integer>absent());
assertEquals(Optional.absent().hashCode(), Optional.absent().hashCode());
}
public void testEqualsAndHashCode_present() {
assertEquals(Optional.of("training"), Optional.of("training"));
assertFalse(Optional.of("a").equals(Optional.of("b")));
assertFalse(Optional.of("a").equals(Optional.absent()));
assertEquals(Optional.of("training").hashCode(), Optional.of("training").hashCode());
}
public void testToString_absent() {
assertEquals("Optional.absent()", Optional.absent().toString());
}
public void testToString_present() {
assertEquals("Optional.of(training)", Optional.of("training").toString());
}
public void testPresentInstances_allPresent() {
List<Optional<String>> optionals =
ImmutableList.of(Optional.of("a"), Optional.of("b"), Optional.of("c"));
ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "b", "c");
}
public void testPresentInstances_allAbsent() {
List<Optional<Object>> optionals =
ImmutableList.of(Optional.absent(), Optional.absent());
ASSERT.that(Optional.presentInstances(optionals)).isEmpty();
}
public void testPresentInstances_somePresent() {
List<Optional<String>> optionals =
ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c"));
ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "c");
}
public void testPresentInstances_callingIteratorTwice() {
List<Optional<String>> optionals =
ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c"));
Iterable<String> onlyPresent = Optional.presentInstances(optionals);
ASSERT.that(onlyPresent).iteratesOverSequence("a", "c");
ASSERT.that(onlyPresent).iteratesOverSequence("a", "c");
}
public void testPresentInstances_wildcards() {
List<Optional<? extends Number>> optionals =
ImmutableList.<Optional<? extends Number>>of(Optional.<Double>absent(), Optional.of(2));
Iterable<Number> onlyPresent = Optional.presentInstances(optionals);
ASSERT.that(onlyPresent).iteratesOverSequence(2);
}
private static Optional<Integer> getSomeOptionalInt() {
return Optional.of(1);
}
private static FluentIterable<? extends Number> getSomeNumbers() {
return FluentIterable.from(ImmutableList.<Number>of());
}
/*
* The following tests demonstrate the shortcomings of or() and test that the casting workaround
* mentioned in the method Javadoc does in fact compile.
*/
@SuppressWarnings("unused") // compilation test
public void testSampleCodeError1() {
Optional<Integer> optionalInt = getSomeOptionalInt();
// Number value = optionalInt.or(0.5); // error
}
@SuppressWarnings("unused") // compilation test
public void testSampleCodeError2() {
FluentIterable<? extends Number> numbers = getSomeNumbers();
Optional<? extends Number> first = numbers.first();
// Number value = first.or(0.5); // error
}
@SuppressWarnings("unused") // compilation test
public void testSampleCodeFine1() {
Optional<Number> optionalInt = Optional.of((Number) 1);
Number value = optionalInt.or(0.5); // fine
}
@SuppressWarnings("unused") // compilation test
public void testSampleCodeFine2() {
FluentIterable<? extends Number> numbers = getSomeNumbers();
// Sadly, the following is what users will have to do in some circumstances.
@SuppressWarnings("unchecked") // safe covariant cast
Optional<Number> first = (Optional) numbers.first();
Number value = first.or(0.5); // fine
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/OptionalTest.java | Java | asf20 | 9,226 |
/*
* Copyright (C) 2010 The Guava 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.common.base;
import com.google.common.annotations.GwtCompatible;
import junit.framework.TestCase;
/**
* Unit test for {@link Strings}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class StringsTest extends TestCase {
public void testNullToEmpty() {
assertEquals("", Strings.nullToEmpty(null));
assertEquals("", Strings.nullToEmpty(""));
assertEquals("a", Strings.nullToEmpty("a"));
}
public void testEmptyToNull() {
assertNull(Strings.emptyToNull(null));
assertNull(Strings.emptyToNull(""));
assertEquals("a", Strings.emptyToNull("a"));
}
public void testIsNullOrEmpty() {
assertTrue(Strings.isNullOrEmpty(null));
assertTrue(Strings.isNullOrEmpty(""));
assertFalse(Strings.isNullOrEmpty("a"));
}
public void testPadStart_noPadding() {
assertSame("", Strings.padStart("", 0, '-'));
assertSame("x", Strings.padStart("x", 0, '-'));
assertSame("x", Strings.padStart("x", 1, '-'));
assertSame("xx", Strings.padStart("xx", 0, '-'));
assertSame("xx", Strings.padStart("xx", 2, '-'));
}
public void testPadStart_somePadding() {
assertEquals("-", Strings.padStart("", 1, '-'));
assertEquals("--", Strings.padStart("", 2, '-'));
assertEquals("-x", Strings.padStart("x", 2, '-'));
assertEquals("--x", Strings.padStart("x", 3, '-'));
assertEquals("-xx", Strings.padStart("xx", 3, '-'));
}
public void testPadStart_negativeMinLength() {
assertSame("x", Strings.padStart("x", -1, '-'));
}
// TODO: could remove if we got NPT working in GWT somehow
public void testPadStart_null() {
try {
Strings.padStart(null, 5, '0');
fail();
} catch (NullPointerException expected) {
}
}
public void testPadEnd_noPadding() {
assertSame("", Strings.padEnd("", 0, '-'));
assertSame("x", Strings.padEnd("x", 0, '-'));
assertSame("x", Strings.padEnd("x", 1, '-'));
assertSame("xx", Strings.padEnd("xx", 0, '-'));
assertSame("xx", Strings.padEnd("xx", 2, '-'));
}
public void testPadEnd_somePadding() {
assertEquals("-", Strings.padEnd("", 1, '-'));
assertEquals("--", Strings.padEnd("", 2, '-'));
assertEquals("x-", Strings.padEnd("x", 2, '-'));
assertEquals("x--", Strings.padEnd("x", 3, '-'));
assertEquals("xx-", Strings.padEnd("xx", 3, '-'));
}
public void testPadEnd_negativeMinLength() {
assertSame("x", Strings.padEnd("x", -1, '-'));
}
// TODO: could remove if we got NPT working in GWT somehow
public void testPadEnd_null() {
try {
Strings.padEnd(null, 5, '0');
fail();
} catch (NullPointerException expected) {
}
}
public void testRepeat() {
String input = "20";
assertEquals("", Strings.repeat(input, 0));
assertEquals("20", Strings.repeat(input, 1));
assertEquals("2020", Strings.repeat(input, 2));
assertEquals("202020", Strings.repeat(input, 3));
assertEquals("", Strings.repeat("", 4));
for (int i = 0; i < 100; ++i) {
assertEquals(2 * i, Strings.repeat(input, i).length());
}
try {
Strings.repeat("x", -1);
fail();
} catch (IllegalArgumentException expected) {
}
try {
// Massive string
Strings.repeat("12345678", (1 << 30) + 3);
fail();
} catch (ArrayIndexOutOfBoundsException expected) {
}
}
// TODO: could remove if we got NPT working in GWT somehow
public void testRepeat_null() {
try {
Strings.repeat(null, 5);
fail();
} catch (NullPointerException expected) {
}
}
public void testCommonPrefix() {
assertEquals("", Strings.commonPrefix("", ""));
assertEquals("", Strings.commonPrefix("abc", ""));
assertEquals("", Strings.commonPrefix("", "abc"));
assertEquals("", Strings.commonPrefix("abcde", "xyz"));
assertEquals("", Strings.commonPrefix("xyz", "abcde"));
assertEquals("", Strings.commonPrefix("xyz", "abcxyz"));
assertEquals("a", Strings.commonPrefix("abc", "aaaaa"));
assertEquals("aa", Strings.commonPrefix("aa", "aaaaa"));
assertEquals("abc",
Strings.commonPrefix(new StringBuffer("abcdef"), "abcxyz"));
// Identical valid surrogate pairs.
assertEquals("abc\uD8AB\uDCAB",
Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uDCABxyz"));
// Differing valid surrogate pairs.
assertEquals("abc",
Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uDCACxyz"));
// One invalid pair.
assertEquals("abc",
Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uD8ABxyz"));
// Two identical invalid pairs.
assertEquals("abc\uD8AB\uD8AC",
Strings.commonPrefix("abc\uD8AB\uD8ACdef", "abc\uD8AB\uD8ACxyz"));
// Two differing invalid pairs.
assertEquals("abc\uD8AB",
Strings.commonPrefix("abc\uD8AB\uD8ABdef", "abc\uD8AB\uD8ACxyz"));
// One orphan high surrogate.
assertEquals("", Strings.commonPrefix("\uD8AB\uDCAB", "\uD8AB"));
// Two orphan high surrogates.
assertEquals("\uD8AB", Strings.commonPrefix("\uD8AB", "\uD8AB"));
}
public void testCommonSuffix() {
assertEquals("", Strings.commonSuffix("", ""));
assertEquals("", Strings.commonSuffix("abc", ""));
assertEquals("", Strings.commonSuffix("", "abc"));
assertEquals("", Strings.commonSuffix("abcde", "xyz"));
assertEquals("", Strings.commonSuffix("xyz", "abcde"));
assertEquals("", Strings.commonSuffix("xyz", "xyzabc"));
assertEquals("c", Strings.commonSuffix("abc", "ccccc"));
assertEquals("aa", Strings.commonSuffix("aa", "aaaaa"));
assertEquals("abc",
Strings.commonSuffix(new StringBuffer("xyzabc"), "xxxabc"));
// Identical valid surrogate pairs.
assertEquals("\uD8AB\uDCABdef",
Strings.commonSuffix("abc\uD8AB\uDCABdef", "xyz\uD8AB\uDCABdef"));
// Differing valid surrogate pairs.
assertEquals("def",
Strings.commonSuffix("abc\uD8AB\uDCABdef", "abc\uD8AC\uDCABdef"));
// One invalid pair.
assertEquals("def",
Strings.commonSuffix("abc\uD8AB\uDCABdef", "xyz\uDCAB\uDCABdef"));
// Two identical invalid pairs.
assertEquals("\uD8AB\uD8ABdef",
Strings.commonSuffix("abc\uD8AB\uD8ABdef", "xyz\uD8AB\uD8ABdef"));
// Two differing invalid pairs.
assertEquals("\uDCABdef",
Strings.commonSuffix("abc\uDCAB\uDCABdef", "abc\uDCAC\uDCABdef"));
// One orphan low surrogate.
assertEquals("", Strings.commonSuffix("x\uD8AB\uDCAB", "\uDCAB"));
// Two orphan low surrogates.
assertEquals("\uDCAB", Strings.commonSuffix("\uDCAB", "\uDCAB"));
}
public void testValidSurrogatePairAt() {
assertTrue(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 0));
assertTrue(Strings.validSurrogatePairAt("abc\uD8AB\uDCAB", 3));
assertTrue(Strings.validSurrogatePairAt("abc\uD8AB\uDCABxyz", 3));
assertFalse(Strings.validSurrogatePairAt("\uD8AB\uD8AB", 0));
assertFalse(Strings.validSurrogatePairAt("\uDCAB\uDCAB", 0));
assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", -1));
assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 1));
assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", -2));
assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 2));
assertFalse(Strings.validSurrogatePairAt("x\uDCAB", 0));
assertFalse(Strings.validSurrogatePairAt("\uD8ABx", 0));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/StringsTest.java | Java | asf20 | 7,963 |
/*
* Copyright (C) 2008 The Guava 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.common.base;
import static com.google.common.base.CharMatcher.BREAKING_WHITESPACE;
import static com.google.common.base.CharMatcher.WHITESPACE;
import static com.google.common.base.CharMatcher.anyOf;
import static com.google.common.base.CharMatcher.forPredicate;
import static com.google.common.base.CharMatcher.inRange;
import static com.google.common.base.CharMatcher.is;
import static com.google.common.base.CharMatcher.isNot;
import static com.google.common.base.CharMatcher.noneOf;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Sets;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* Unit test for {@link CharMatcher}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class CharMatcherTest extends TestCase {
private static final CharMatcher WHATEVER = new CharMatcher() {
@Override public boolean matches(char c) {
throw new AssertionFailedError(
"You weren't supposed to actually invoke me!");
}
};
public void testAnyAndNone_logicalOps() throws Exception {
// These are testing behavior that's never promised by the API, but since
// we're lucky enough that these do pass, it saves us from having to write
// more excruciating tests! Hooray!
assertSame(CharMatcher.ANY, CharMatcher.NONE.negate());
assertSame(CharMatcher.NONE, CharMatcher.ANY.negate());
assertSame(WHATEVER, CharMatcher.ANY.and(WHATEVER));
assertSame(CharMatcher.ANY, CharMatcher.ANY.or(WHATEVER));
assertSame(CharMatcher.NONE, CharMatcher.NONE.and(WHATEVER));
assertSame(WHATEVER, CharMatcher.NONE.or(WHATEVER));
}
// The rest of the behavior of ANY and DEFAULT will be covered in the tests for
// the text processing methods below.
public void testWhitespaceBreakingWhitespaceSubset() throws Exception {
for (int c = 0; c <= Character.MAX_VALUE; c++) {
if (BREAKING_WHITESPACE.apply((char) c)) {
assertTrue(Integer.toHexString(c), WHITESPACE.apply((char) c));
}
}
}
// The next tests require ICU4J and have, at least for now, been sliced out
// of the open-source view of the tests.
// Omitting tests for the rest of the JAVA_* constants as these are defined
// as extremely straightforward pass-throughs to the JDK methods.
// We're testing the is(), isNot(), anyOf(), noneOf() and inRange() methods
// below by testing their text-processing methods.
// The organization of this test class is unusual, as it's not done by
// method, but by overall "scenario". Also, the variety of actual tests we
// do borders on absurd overkill. Better safe than sorry, though?
public void testEmpty() throws Exception {
doTestEmpty(CharMatcher.ANY);
doTestEmpty(CharMatcher.NONE);
doTestEmpty(is('a'));
doTestEmpty(isNot('a'));
doTestEmpty(anyOf(""));
doTestEmpty(anyOf("x"));
doTestEmpty(anyOf("xy"));
doTestEmpty(anyOf("CharMatcher"));
doTestEmpty(noneOf("CharMatcher"));
doTestEmpty(inRange('n', 'q'));
doTestEmpty(forPredicate(Predicates.equalTo('c')));
}
private void doTestEmpty(CharMatcher matcher) throws Exception {
reallyTestEmpty(matcher);
reallyTestEmpty(matcher.negate());
reallyTestEmpty(matcher.precomputed());
}
private void reallyTestEmpty(CharMatcher matcher) throws Exception {
assertEquals(-1, matcher.indexIn(""));
assertEquals(-1, matcher.indexIn("", 0));
try {
matcher.indexIn("", 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
try {
matcher.indexIn("", -1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertEquals(-1, matcher.lastIndexIn(""));
assertFalse(matcher.matchesAnyOf(""));
assertTrue(matcher.matchesAllOf(""));
assertTrue(matcher.matchesNoneOf(""));
assertEquals("", matcher.removeFrom(""));
assertEquals("", matcher.replaceFrom("", 'z'));
assertEquals("", matcher.replaceFrom("", "ZZ"));
assertEquals("", matcher.trimFrom(""));
assertEquals(0, matcher.countIn(""));
}
public void testNoMatches() {
doTestNoMatches(CharMatcher.NONE, "blah");
doTestNoMatches(is('a'), "bcde");
doTestNoMatches(isNot('a'), "aaaa");
doTestNoMatches(anyOf(""), "abcd");
doTestNoMatches(anyOf("x"), "abcd");
doTestNoMatches(anyOf("xy"), "abcd");
doTestNoMatches(anyOf("CharMatcher"), "zxqy");
doTestNoMatches(noneOf("CharMatcher"), "ChMa");
doTestNoMatches(inRange('p', 'x'), "mom");
doTestNoMatches(forPredicate(Predicates.equalTo('c')), "abe");
doTestNoMatches(inRange('A', 'Z').and(inRange('F', 'K').negate()), "F1a");
doTestNoMatches(CharMatcher.DIGIT, "\tAz()");
doTestNoMatches(CharMatcher.JAVA_DIGIT, "\tAz()");
doTestNoMatches(CharMatcher.DIGIT.and(CharMatcher.ASCII), "\tAz()");
doTestNoMatches(CharMatcher.SINGLE_WIDTH, "\u05bf\u3000");
}
private void doTestNoMatches(CharMatcher matcher, String s) {
reallyTestNoMatches(matcher, s);
reallyTestAllMatches(matcher.negate(), s);
reallyTestNoMatches(matcher.precomputed(), s);
reallyTestAllMatches(matcher.negate().precomputed(), s);
reallyTestAllMatches(matcher.precomputed().negate(), s);
reallyTestNoMatches(forPredicate(matcher), s);
reallyTestNoMatches(matcher, new StringBuilder(s));
}
public void testAllMatches() {
doTestAllMatches(CharMatcher.ANY, "blah");
doTestAllMatches(isNot('a'), "bcde");
doTestAllMatches(is('a'), "aaaa");
doTestAllMatches(noneOf("CharMatcher"), "zxqy");
doTestAllMatches(anyOf("x"), "xxxx");
doTestAllMatches(anyOf("xy"), "xyyx");
doTestAllMatches(anyOf("CharMatcher"), "ChMa");
doTestAllMatches(inRange('m', 'p'), "mom");
doTestAllMatches(forPredicate(Predicates.equalTo('c')), "ccc");
doTestAllMatches(CharMatcher.DIGIT, "0123456789\u0ED0\u1B59");
doTestAllMatches(CharMatcher.JAVA_DIGIT, "0123456789");
doTestAllMatches(CharMatcher.DIGIT.and(CharMatcher.ASCII), "0123456789");
doTestAllMatches(CharMatcher.SINGLE_WIDTH, "\t0123ABCdef~\u00A0\u2111");
}
private void doTestAllMatches(CharMatcher matcher, String s) {
reallyTestAllMatches(matcher, s);
reallyTestNoMatches(matcher.negate(), s);
reallyTestAllMatches(matcher.precomputed(), s);
reallyTestNoMatches(matcher.negate().precomputed(), s);
reallyTestNoMatches(matcher.precomputed().negate(), s);
reallyTestAllMatches(forPredicate(matcher), s);
reallyTestAllMatches(matcher, new StringBuilder(s));
}
private void reallyTestNoMatches(CharMatcher matcher, CharSequence s) {
assertFalse(matcher.matches(s.charAt(0)));
assertEquals(-1, matcher.indexIn(s));
assertEquals(-1, matcher.indexIn(s, 0));
assertEquals(-1, matcher.indexIn(s, 1));
assertEquals(-1, matcher.indexIn(s, s.length()));
try {
matcher.indexIn(s, s.length() + 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
try {
matcher.indexIn(s, -1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
assertEquals(-1, matcher.lastIndexIn(s));
assertFalse(matcher.matchesAnyOf(s));
assertFalse(matcher.matchesAllOf(s));
assertTrue(matcher.matchesNoneOf(s));
assertEquals(s.toString(), matcher.removeFrom(s));
assertEquals(s.toString(), matcher.replaceFrom(s, 'z'));
assertEquals(s.toString(), matcher.replaceFrom(s, "ZZ"));
assertEquals(s.toString(), matcher.trimFrom(s));
assertEquals(0, matcher.countIn(s));
}
private void reallyTestAllMatches(CharMatcher matcher, CharSequence s) {
assertTrue(matcher.matches(s.charAt(0)));
assertEquals(0, matcher.indexIn(s));
assertEquals(0, matcher.indexIn(s, 0));
assertEquals(1, matcher.indexIn(s, 1));
assertEquals(-1, matcher.indexIn(s, s.length()));
assertEquals(s.length() - 1, matcher.lastIndexIn(s));
assertTrue(matcher.matchesAnyOf(s));
assertTrue(matcher.matchesAllOf(s));
assertFalse(matcher.matchesNoneOf(s));
assertEquals("", matcher.removeFrom(s));
assertEquals(Strings.repeat("z", s.length()),
matcher.replaceFrom(s, 'z'));
assertEquals(Strings.repeat("ZZ", s.length()),
matcher.replaceFrom(s, "ZZ"));
assertEquals("", matcher.trimFrom(s));
assertEquals(s.length(), matcher.countIn(s));
}
public void testGeneral() {
doTestGeneral(is('a'), 'a', 'b');
doTestGeneral(isNot('a'), 'b', 'a');
doTestGeneral(anyOf("x"), 'x', 'z');
doTestGeneral(anyOf("xy"), 'y', 'z');
doTestGeneral(anyOf("CharMatcher"), 'C', 'z');
doTestGeneral(noneOf("CharMatcher"), 'z', 'C');
doTestGeneral(inRange('p', 'x'), 'q', 'z');
}
private void doTestGeneral(CharMatcher matcher, char match, char noMatch) {
doTestOneCharMatch(matcher, "" + match);
doTestOneCharNoMatch(matcher, "" + noMatch);
doTestMatchThenNoMatch(matcher, "" + match + noMatch);
doTestNoMatchThenMatch(matcher, "" + noMatch + match);
}
private void doTestOneCharMatch(CharMatcher matcher, String s) {
reallyTestOneCharMatch(matcher, s);
reallyTestOneCharNoMatch(matcher.negate(), s);
reallyTestOneCharMatch(matcher.precomputed(), s);
reallyTestOneCharNoMatch(matcher.negate().precomputed(), s);
reallyTestOneCharNoMatch(matcher.precomputed().negate(), s);
}
private void doTestOneCharNoMatch(CharMatcher matcher, String s) {
reallyTestOneCharNoMatch(matcher, s);
reallyTestOneCharMatch(matcher.negate(), s);
reallyTestOneCharNoMatch(matcher.precomputed(), s);
reallyTestOneCharMatch(matcher.negate().precomputed(), s);
reallyTestOneCharMatch(matcher.precomputed().negate(), s);
}
private void doTestMatchThenNoMatch(CharMatcher matcher, String s) {
reallyTestMatchThenNoMatch(matcher, s);
reallyTestNoMatchThenMatch(matcher.negate(), s);
reallyTestMatchThenNoMatch(matcher.precomputed(), s);
reallyTestNoMatchThenMatch(matcher.negate().precomputed(), s);
reallyTestNoMatchThenMatch(matcher.precomputed().negate(), s);
}
private void doTestNoMatchThenMatch(CharMatcher matcher, String s) {
reallyTestNoMatchThenMatch(matcher, s);
reallyTestMatchThenNoMatch(matcher.negate(), s);
reallyTestNoMatchThenMatch(matcher.precomputed(), s);
reallyTestMatchThenNoMatch(matcher.negate().precomputed(), s);
reallyTestMatchThenNoMatch(matcher.precomputed().negate(), s);
}
private void reallyTestOneCharMatch(CharMatcher matcher, String s) {
assertTrue(matcher.matches(s.charAt(0)));
assertTrue(matcher.apply(s.charAt(0)));
assertEquals(0, matcher.indexIn(s));
assertEquals(0, matcher.indexIn(s, 0));
assertEquals(-1, matcher.indexIn(s, 1));
assertEquals(0, matcher.lastIndexIn(s));
assertTrue(matcher.matchesAnyOf(s));
assertTrue(matcher.matchesAllOf(s));
assertFalse(matcher.matchesNoneOf(s));
assertEquals("", matcher.removeFrom(s));
assertEquals("z", matcher.replaceFrom(s, 'z'));
assertEquals("ZZ", matcher.replaceFrom(s, "ZZ"));
assertEquals("", matcher.trimFrom(s));
assertEquals(1, matcher.countIn(s));
}
private void reallyTestOneCharNoMatch(CharMatcher matcher, String s) {
assertFalse(matcher.matches(s.charAt(0)));
assertFalse(matcher.apply(s.charAt(0)));
assertEquals(-1, matcher.indexIn(s));
assertEquals(-1, matcher.indexIn(s, 0));
assertEquals(-1, matcher.indexIn(s, 1));
assertEquals(-1, matcher.lastIndexIn(s));
assertFalse(matcher.matchesAnyOf(s));
assertFalse(matcher.matchesAllOf(s));
assertTrue(matcher.matchesNoneOf(s));
assertSame(s, matcher.removeFrom(s));
assertSame(s, matcher.replaceFrom(s, 'z'));
assertSame(s, matcher.replaceFrom(s, "ZZ"));
assertSame(s, matcher.trimFrom(s));
assertSame(0, matcher.countIn(s));
}
private void reallyTestMatchThenNoMatch(CharMatcher matcher, String s) {
assertEquals(0, matcher.indexIn(s));
assertEquals(0, matcher.indexIn(s, 0));
assertEquals(-1, matcher.indexIn(s, 1));
assertEquals(-1, matcher.indexIn(s, 2));
assertEquals(0, matcher.lastIndexIn(s));
assertTrue(matcher.matchesAnyOf(s));
assertFalse(matcher.matchesAllOf(s));
assertFalse(matcher.matchesNoneOf(s));
assertEquals(s.substring(1), matcher.removeFrom(s));
assertEquals("z" + s.substring(1), matcher.replaceFrom(s, 'z'));
assertEquals("ZZ" + s.substring(1), matcher.replaceFrom(s, "ZZ"));
assertEquals(s.substring(1), matcher.trimFrom(s));
assertEquals(1, matcher.countIn(s));
}
private void reallyTestNoMatchThenMatch(CharMatcher matcher, String s) {
assertEquals(1, matcher.indexIn(s));
assertEquals(1, matcher.indexIn(s, 0));
assertEquals(1, matcher.indexIn(s, 1));
assertEquals(-1, matcher.indexIn(s, 2));
assertEquals(1, matcher.lastIndexIn(s));
assertTrue(matcher.matchesAnyOf(s));
assertFalse(matcher.matchesAllOf(s));
assertFalse(matcher.matchesNoneOf(s));
assertEquals(s.substring(0, 1), matcher.removeFrom(s));
assertEquals(s.substring(0, 1) + "z", matcher.replaceFrom(s, 'z'));
assertEquals(s.substring(0, 1) + "ZZ", matcher.replaceFrom(s, "ZZ"));
assertEquals(s.substring(0, 1), matcher.trimFrom(s));
assertEquals(1, matcher.countIn(s));
}
/**
* Checks that expected is equals to out, and further, if in is
* equals to expected, then out is successfully optimized to be
* identical to in, i.e. that "in" is simply returned.
*/
private void assertEqualsSame(String expected, String in, String out) {
if (expected.equals(in)) {
assertSame(in, out);
} else {
assertEquals(expected, out);
}
}
// Test collapse() a little differently than the rest, as we really want to
// cover lots of different configurations of input text
public void testCollapse() {
// collapsing groups of '-' into '_' or '-'
doTestCollapse("-", "_");
doTestCollapse("x-", "x_");
doTestCollapse("-x", "_x");
doTestCollapse("--", "_");
doTestCollapse("x--", "x_");
doTestCollapse("--x", "_x");
doTestCollapse("-x-", "_x_");
doTestCollapse("x-x", "x_x");
doTestCollapse("---", "_");
doTestCollapse("--x-", "_x_");
doTestCollapse("--xx", "_xx");
doTestCollapse("-x--", "_x_");
doTestCollapse("-x-x", "_x_x");
doTestCollapse("-xx-", "_xx_");
doTestCollapse("x--x", "x_x");
doTestCollapse("x-x-", "x_x_");
doTestCollapse("x-xx", "x_xx");
doTestCollapse("x-x--xx---x----x", "x_x_xx_x_x");
doTestCollapseWithNoChange("");
doTestCollapseWithNoChange("x");
doTestCollapseWithNoChange("xx");
}
private void doTestCollapse(String in, String out) {
// Try a few different matchers which all match '-' and not 'x'
// Try replacement chars that both do and do not change the value.
for (char replacement : new char[] { '_', '-' }) {
String expected = out.replace('_', replacement);
assertEqualsSame(expected, in, is('-').collapseFrom(in, replacement));
assertEqualsSame(expected, in, is('-').collapseFrom(in, replacement));
assertEqualsSame(expected, in, is('-').or(is('#')).collapseFrom(in, replacement));
assertEqualsSame(expected, in, isNot('x').collapseFrom(in, replacement));
assertEqualsSame(expected, in, is('x').negate().collapseFrom(in, replacement));
assertEqualsSame(expected, in, anyOf("-").collapseFrom(in, replacement));
assertEqualsSame(expected, in, anyOf("-#").collapseFrom(in, replacement));
assertEqualsSame(expected, in, anyOf("-#123").collapseFrom(in, replacement));
}
}
private void doTestCollapseWithNoChange(String inout) {
assertSame(inout, is('-').collapseFrom(inout, '_'));
assertSame(inout, is('-').or(is('#')).collapseFrom(inout, '_'));
assertSame(inout, isNot('x').collapseFrom(inout, '_'));
assertSame(inout, is('x').negate().collapseFrom(inout, '_'));
assertSame(inout, anyOf("-").collapseFrom(inout, '_'));
assertSame(inout, anyOf("-#").collapseFrom(inout, '_'));
assertSame(inout, anyOf("-#123").collapseFrom(inout, '_'));
assertSame(inout, CharMatcher.NONE.collapseFrom(inout, '_'));
}
public void testCollapse_any() {
assertEquals("", CharMatcher.ANY.collapseFrom("", '_'));
assertEquals("_", CharMatcher.ANY.collapseFrom("a", '_'));
assertEquals("_", CharMatcher.ANY.collapseFrom("ab", '_'));
assertEquals("_", CharMatcher.ANY.collapseFrom("abcd", '_'));
}
public void testTrimFrom() {
// trimming -
doTestTrimFrom("-", "");
doTestTrimFrom("x-", "x");
doTestTrimFrom("-x", "x");
doTestTrimFrom("--", "");
doTestTrimFrom("x--", "x");
doTestTrimFrom("--x", "x");
doTestTrimFrom("-x-", "x");
doTestTrimFrom("x-x", "x-x");
doTestTrimFrom("---", "");
doTestTrimFrom("--x-", "x");
doTestTrimFrom("--xx", "xx");
doTestTrimFrom("-x--", "x");
doTestTrimFrom("-x-x", "x-x");
doTestTrimFrom("-xx-", "xx");
doTestTrimFrom("x--x", "x--x");
doTestTrimFrom("x-x-", "x-x");
doTestTrimFrom("x-xx", "x-xx");
doTestTrimFrom("x-x--xx---x----x", "x-x--xx---x----x");
// additional testing using the doc example
assertEquals("cat", anyOf("ab").trimFrom("abacatbab"));
}
private void doTestTrimFrom(String in, String out) {
// Try a few different matchers which all match '-' and not 'x'
assertEquals(out, is('-').trimFrom(in));
assertEquals(out, is('-').or(is('#')).trimFrom(in));
assertEquals(out, isNot('x').trimFrom(in));
assertEquals(out, is('x').negate().trimFrom(in));
assertEquals(out, anyOf("-").trimFrom(in));
assertEquals(out, anyOf("-#").trimFrom(in));
assertEquals(out, anyOf("-#123").trimFrom(in));
}
public void testTrimLeadingFrom() {
// trimming -
doTestTrimLeadingFrom("-", "");
doTestTrimLeadingFrom("x-", "x-");
doTestTrimLeadingFrom("-x", "x");
doTestTrimLeadingFrom("--", "");
doTestTrimLeadingFrom("x--", "x--");
doTestTrimLeadingFrom("--x", "x");
doTestTrimLeadingFrom("-x-", "x-");
doTestTrimLeadingFrom("x-x", "x-x");
doTestTrimLeadingFrom("---", "");
doTestTrimLeadingFrom("--x-", "x-");
doTestTrimLeadingFrom("--xx", "xx");
doTestTrimLeadingFrom("-x--", "x--");
doTestTrimLeadingFrom("-x-x", "x-x");
doTestTrimLeadingFrom("-xx-", "xx-");
doTestTrimLeadingFrom("x--x", "x--x");
doTestTrimLeadingFrom("x-x-", "x-x-");
doTestTrimLeadingFrom("x-xx", "x-xx");
doTestTrimLeadingFrom("x-x--xx---x----x", "x-x--xx---x----x");
// additional testing using the doc example
assertEquals("catbab", anyOf("ab").trimLeadingFrom("abacatbab"));
}
private void doTestTrimLeadingFrom(String in, String out) {
// Try a few different matchers which all match '-' and not 'x'
assertEquals(out, is('-').trimLeadingFrom(in));
assertEquals(out, is('-').or(is('#')).trimLeadingFrom(in));
assertEquals(out, isNot('x').trimLeadingFrom(in));
assertEquals(out, is('x').negate().trimLeadingFrom(in));
assertEquals(out, anyOf("-#").trimLeadingFrom(in));
assertEquals(out, anyOf("-#123").trimLeadingFrom(in));
}
public void testTrimTrailingFrom() {
// trimming -
doTestTrimTrailingFrom("-", "");
doTestTrimTrailingFrom("x-", "x");
doTestTrimTrailingFrom("-x", "-x");
doTestTrimTrailingFrom("--", "");
doTestTrimTrailingFrom("x--", "x");
doTestTrimTrailingFrom("--x", "--x");
doTestTrimTrailingFrom("-x-", "-x");
doTestTrimTrailingFrom("x-x", "x-x");
doTestTrimTrailingFrom("---", "");
doTestTrimTrailingFrom("--x-", "--x");
doTestTrimTrailingFrom("--xx", "--xx");
doTestTrimTrailingFrom("-x--", "-x");
doTestTrimTrailingFrom("-x-x", "-x-x");
doTestTrimTrailingFrom("-xx-", "-xx");
doTestTrimTrailingFrom("x--x", "x--x");
doTestTrimTrailingFrom("x-x-", "x-x");
doTestTrimTrailingFrom("x-xx", "x-xx");
doTestTrimTrailingFrom("x-x--xx---x----x", "x-x--xx---x----x");
// additional testing using the doc example
assertEquals("abacat", anyOf("ab").trimTrailingFrom("abacatbab"));
}
private void doTestTrimTrailingFrom(String in, String out) {
// Try a few different matchers which all match '-' and not 'x'
assertEquals(out, is('-').trimTrailingFrom(in));
assertEquals(out, is('-').or(is('#')).trimTrailingFrom(in));
assertEquals(out, isNot('x').trimTrailingFrom(in));
assertEquals(out, is('x').negate().trimTrailingFrom(in));
assertEquals(out, anyOf("-#").trimTrailingFrom(in));
assertEquals(out, anyOf("-#123").trimTrailingFrom(in));
}
public void testTrimAndCollapse() {
// collapsing groups of '-' into '_' or '-'
doTestTrimAndCollapse("", "");
doTestTrimAndCollapse("x", "x");
doTestTrimAndCollapse("-", "");
doTestTrimAndCollapse("x-", "x");
doTestTrimAndCollapse("-x", "x");
doTestTrimAndCollapse("--", "");
doTestTrimAndCollapse("x--", "x");
doTestTrimAndCollapse("--x", "x");
doTestTrimAndCollapse("-x-", "x");
doTestTrimAndCollapse("x-x", "x_x");
doTestTrimAndCollapse("---", "");
doTestTrimAndCollapse("--x-", "x");
doTestTrimAndCollapse("--xx", "xx");
doTestTrimAndCollapse("-x--", "x");
doTestTrimAndCollapse("-x-x", "x_x");
doTestTrimAndCollapse("-xx-", "xx");
doTestTrimAndCollapse("x--x", "x_x");
doTestTrimAndCollapse("x-x-", "x_x");
doTestTrimAndCollapse("x-xx", "x_xx");
doTestTrimAndCollapse("x-x--xx---x----x", "x_x_xx_x_x");
}
private void doTestTrimAndCollapse(String in, String out) {
// Try a few different matchers which all match '-' and not 'x'
for (char replacement : new char[] { '_', '-' }) {
String expected = out.replace('_', replacement);
assertEqualsSame(expected, in, is('-').trimAndCollapseFrom(in, replacement));
assertEqualsSame(expected, in, is('-').or(is('#')).trimAndCollapseFrom(in, replacement));
assertEqualsSame(expected, in, isNot('x').trimAndCollapseFrom(in, replacement));
assertEqualsSame(expected, in, is('x').negate().trimAndCollapseFrom(in, replacement));
assertEqualsSame(expected, in, anyOf("-").trimAndCollapseFrom(in, replacement));
assertEqualsSame(expected, in, anyOf("-#").trimAndCollapseFrom(in, replacement));
assertEqualsSame(expected, in, anyOf("-#123").trimAndCollapseFrom(in, replacement));
}
}
public void testReplaceFrom() {
assertEquals("yoho", is('a').replaceFrom("yaha", 'o'));
assertEquals("yh", is('a').replaceFrom("yaha", ""));
assertEquals("yoho", is('a').replaceFrom("yaha", "o"));
assertEquals("yoohoo", is('a').replaceFrom("yaha", "oo"));
assertEquals("12 > 5", is('>').replaceFrom("12 > 5", ">"));
}
public void testPrecomputedOptimizations() {
// These are testing behavior that's never promised by the API.
// Some matchers are so efficient that it is a waste of effort to
// build a precomputed version.
CharMatcher m1 = is('x');
assertSame(m1, m1.precomputed());
assertSame(m1.toString(), m1.precomputed().toString());
CharMatcher m2 = anyOf("Az");
assertSame(m2, m2.precomputed());
assertSame(m2.toString(), m2.precomputed().toString());
CharMatcher m3 = inRange('A', 'Z');
assertSame(m3, m3.precomputed());
assertSame(m3.toString(), m3.precomputed().toString());
assertSame(CharMatcher.NONE, CharMatcher.NONE.precomputed());
assertSame(CharMatcher.ANY, CharMatcher.ANY.precomputed());
}
static void checkExactMatches(CharMatcher m, char[] chars) {
Set<Character> positive = Sets.newHashSetWithExpectedSize(chars.length);
for (int i = 0; i < chars.length; i++) {
positive.add(chars[i]);
}
for (int c = 0; c <= Character.MAX_VALUE; c++) {
assertFalse(positive.contains(new Character((char) c)) ^ m.matches((char) c));
}
}
static char[] randomChars(Random rand, int size) {
Set<Character> chars = new HashSet<Character>(size);
for (int i = 0; i < size; i++) {
char c;
while (true) {
c = (char) rand.nextInt(Character.MAX_VALUE - Character.MIN_VALUE + 1);
if (!chars.contains(c)) {
break;
}
}
chars.add(c);
}
char[] retValue = new char[chars.size()];
int i = 0;
for (char c : chars) {
retValue[i++] = c;
}
Arrays.sort(retValue);
return retValue;
}
public void testToString() {
assertToStringWorks("CharMatcher.NONE", CharMatcher.anyOf(""));
assertToStringWorks("CharMatcher.is('\\u0031')", CharMatcher.anyOf("1"));
assertToStringWorks("CharMatcher.isNot('\\u0031')", CharMatcher.isNot('1'));
assertToStringWorks("CharMatcher.anyOf(\"\\u0031\\u0032\")", CharMatcher.anyOf("12"));
assertToStringWorks("CharMatcher.anyOf(\"\\u0031\\u0032\\u0033\")",
CharMatcher.anyOf("321"));
assertToStringWorks("CharMatcher.inRange('\\u0031', '\\u0033')",
CharMatcher.inRange('1', '3'));
}
private static void assertToStringWorks(String expected, CharMatcher matcher) {
assertEquals(expected, matcher.toString());
assertEquals(expected, matcher.precomputed().toString());
assertEquals(expected, matcher.negate().negate().toString());
assertEquals(expected, matcher.negate().precomputed().negate().toString());
assertEquals(expected, matcher.negate().precomputed().negate().precomputed().toString());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/base/super/com/google/common/base/CharMatcherTest.java | Java | asf20 | 26,063 |
/*
* Copyright (C) 2013 The Guava 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.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* Tests for {@code Multiset#count}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetCountTester<E> extends AbstractMultisetTester<E> {
public void testCount_0() {
assertEquals("multiset.count(missing) didn't return 0",
0, getMultiset().count(samples.e3));
}
@CollectionSize.Require(absent = ZERO)
public void testCount_1() {
assertEquals("multiset.count(present) didn't return 1",
1, getMultiset().count(samples.e0));
}
@CollectionSize.Require(SEVERAL)
public void testCount_3() {
initThreeCopies();
assertEquals("multiset.count(thriceContained) didn't return 3",
3, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(ALLOWS_NULL_QUERIES)
public void testCount_nullAbsent() {
assertEquals("multiset.count(null) didn't return 0",
0, getMultiset().count(null));
}
@CollectionFeature.Require(absent = ALLOWS_NULL_QUERIES)
public void testCount_null_forbidden() {
try {
getMultiset().count(null);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testCount_nullPresent() {
initCollectionWithNullElement();
assertEquals(1, getMultiset().count(null));
}
public void testCount_wrongType() {
assertEquals("multiset.count(wrongType) didn't return 0",
0, getMultiset().count(WrongType.VALUE));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/google/super/com/google/common/collect/testing/google/MultisetCountTester.java | Java | asf20 | 2,757 |
/*
* Copyright (C) 2013 The Guava 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.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_QUERIES;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collections;
import java.util.List;
/**
* Tests for {@code Multiset#remove}, {@code Multiset.removeAll}, and {@code Multiset.retainAll}
* not already covered by the corresponding Collection testers.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class MultisetRemoveTester<E> extends AbstractMultisetTester<E> {
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveNegative() {
try {
getMultiset().remove(samples.e0, -1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException expected) {}
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemoveUnsupported() {
try {
getMultiset().remove(samples.e0, 2);
fail("Expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveZeroNoOp() {
int originalCount = getMultiset().count(samples.e0);
assertEquals("old count", originalCount, getMultiset().remove(samples.e0, 0));
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_present() {
assertEquals("multiset.remove(present, 2) didn't return the old count",
1, getMultiset().remove(samples.e0, 2));
assertFalse("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(samples.e0));
assertEquals(0, getMultiset().count(samples.e0));
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_some_occurrences_present() {
initThreeCopies();
assertEquals("multiset.remove(present, 2) didn't return the old count",
3, getMultiset().remove(samples.e0, 2));
assertTrue("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(samples.e0));
assertEquals(1, getMultiset().count(samples.e0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_absent() {
assertEquals("multiset.remove(absent, 0) didn't return 0",
0, getMultiset().remove(samples.e3, 2));
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testRemove_occurrences_unsupported_absent() {
// notice: we don't care whether it succeeds, or fails with UOE
try {
assertEquals(
"multiset.remove(absent, 2) didn't return 0 or throw an exception",
0, getMultiset().remove(samples.e3, 2));
} catch (UnsupportedOperationException ok) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_0() {
int oldCount = getMultiset().count(samples.e0);
assertEquals("multiset.remove(E, 0) didn't return the old count",
oldCount, getMultiset().remove(samples.e0, 0));
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_negative() {
try {
getMultiset().remove(samples.e0, -1);
fail("multiset.remove(E, -1) didn't throw an exception");
} catch (IllegalArgumentException required) {}
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemove_occurrences_wrongType() {
assertEquals("multiset.remove(wrongType, 1) didn't return 0",
0, getMultiset().remove(WrongType.VALUE, 1));
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testRemove_nullPresent() {
initCollectionWithNullElement();
assertEquals(1, getMultiset().remove(null, 2));
assertFalse("multiset contains present after multiset.remove(present, 2)",
getMultiset().contains(null));
assertEquals(0, getMultiset().count(null));
}
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_QUERIES})
public void testRemove_nullAbsent() {
assertEquals(0, getMultiset().remove(null, 2));
}
@CollectionFeature.Require(value = SUPPORTS_REMOVE, absent = ALLOWS_NULL_QUERIES)
public void testRemove_nullForbidden() {
try {
getMultiset().remove(null, 2);
fail("Expected NullPointerException");
} catch (NullPointerException expected) {}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRemoveAllIgnoresCount() {
initThreeCopies();
assertTrue(getMultiset().removeAll(Collections.singleton(samples.e0)));
ASSERT.that(getMultiset()).isEmpty();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testRetainAllIgnoresCount() {
initThreeCopies();
List<E> contents = Helpers.copyToList(getMultiset());
assertFalse(getMultiset().retainAll(Collections.singleton(samples.e0)));
expectContents(contents);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/google/super/com/google/common/collect/testing/google/MultisetRemoveTester.java | Java | asf20 | 6,291 |
/*
* Copyright (C) 2009 The Guava 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.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.CollectionSize.SEVERAL;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* Common superclass for {@link MultisetSetCountUnconditionallyTester} and
* {@link MultisetSetCountConditionallyTester}. It is used by those testers to
* test calls to the unconditional {@code setCount()} method and calls to the
* conditional {@code setCount()} method when the expected present count is
* correct.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public abstract class AbstractMultisetSetCountTester<E>
extends AbstractMultisetTester<E> {
/*
* TODO: consider adding MultisetFeatures.SUPPORTS_SET_COUNT. Currently we
* assume that using setCount() to increase the count is permitted iff add()
* is permitted and similarly for decrease/remove(). We assume that a
* setCount() no-op is permitted if either add() or remove() is permitted,
* though we also allow it to "succeed" if neither is permitted.
*/
private void assertSetCount(E element, int count) {
setCountCheckReturnValue(element, count);
assertEquals(
"multiset.count() should return the value passed to setCount()",
count, getMultiset().count(element));
int size = 0;
for (Multiset.Entry<E> entry : getMultiset().entrySet()) {
size += entry.getCount();
}
assertEquals(
"multiset.size() should be the sum of the counts of all entries",
size, getMultiset().size());
}
/**
* Call the {@code setCount()} method under test, and check its return value.
*/
abstract void setCountCheckReturnValue(E element, int count);
/**
* Call the {@code setCount()} method under test, but do not check its return
* value. Callers should use this method over
* {@link #setCountCheckReturnValue(Object, int)} when they expect
* {@code setCount()} to throw an exception, as checking the return value
* could produce an incorrect error message like
* "setCount() should return the original count" instead of the message passed
* to a later invocation of {@code fail()}, like "setCount should throw
* UnsupportedOperationException."
*/
abstract void setCountNoCheckReturnValue(E element, int count);
private void assertSetCountIncreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to increase an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
private void assertSetCountDecreasingFailure(E element, int count) {
try {
setCountNoCheckReturnValue(element, count);
fail("a call to multiset.setCount() to decrease an element's count "
+ "should throw");
} catch (UnsupportedOperationException expected) {
}
}
// Unconditional setCount no-ops.
private void assertZeroToZero() {
assertSetCount(samples.e3, 0);
}
private void assertOneToOne() {
assertSetCount(samples.e0, 1);
}
private void assertThreeToThree() {
initThreeCopies();
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToZero_addSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_zeroToZero_removeSupported() {
assertZeroToZero();
}
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_zeroToZero_unsupported() {
try {
assertZeroToZero();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToOne_addSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToOne_removeSupported() {
assertOneToOne();
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_oneToOne_unsupported() {
try {
assertOneToOne();
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_threeToThree_addSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToThree_removeSupported() {
assertThreeToThree();
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = {SUPPORTS_ADD, SUPPORTS_REMOVE})
public void testSetCount_threeToThree_unsupported() {
try {
assertThreeToThree();
} catch (UnsupportedOperationException tolerated) {
}
}
// Unconditional setCount size increases:
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToOne_supported() {
assertSetCount(samples.e3, 1);
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
public void testSetCountZeroToOneConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e3, 1);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_zeroToThree_supported() {
assertSetCount(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_ADD)
public void testSetCount_oneToThree_supported() {
assertSetCount(samples.e0, 3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToOne_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 1);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_zeroToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testSetCount_oneToThree_unsupported() {
assertSetCountIncreasingFailure(samples.e3, 3);
}
// Unconditional setCount size decreases:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_oneToZero_supported() {
assertSetCount(samples.e0, 0);
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require({SUPPORTS_REMOVE,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testSetCountOneToZeroConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<E>> iterator = getMultiset().entrySet().iterator();
assertSetCount(samples.e0, 0);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToZero_supported() {
initThreeCopies();
assertSetCount(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_threeToOne_supported() {
initThreeCopies();
assertSetCount(samples.e0, 1);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_oneToZero_unsupported() {
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToZero_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 0);
}
@CollectionSize.Require(SEVERAL)
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_threeToOne_unsupported() {
initThreeCopies();
assertSetCountDecreasingFailure(samples.e0, 1);
}
// setCount with nulls:
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require({SUPPORTS_REMOVE, ALLOWS_NULL_VALUES})
public void testSetCount_removeNull_nullSupported() {
initCollectionWithNullElement();
assertSetCount(null, 0);
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testSetCount_addNull_nullSupported() {
assertSetCount(null, 1);
}
@CollectionFeature.Require(value = SUPPORTS_ADD, absent = ALLOWS_NULL_VALUES)
public void testSetCount_addNull_nullUnsupported() {
try {
setCountNoCheckReturnValue(null, 1);
fail("adding null with setCount() should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullSupported() {
try {
assertSetCount(null, 0);
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSetCount_noOpNull_nullUnsupported() {
try {
assertSetCount(null, 0);
} catch (NullPointerException tolerated) {
} catch (UnsupportedOperationException tolerated) {
}
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testSetCount_existingNoNopNull_nullSupported() {
initCollectionWithNullElement();
try {
assertSetCount(null, 1);
} catch (UnsupportedOperationException tolerated) {
}
}
// Negative count.
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testSetCount_negative_removeSupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
}
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
public void testSetCount_negative_removeUnsupported() {
try {
setCountNoCheckReturnValue(samples.e3, -1);
fail("calling setCount() with a negative count should throw "
+ "IllegalArgumentException or UnsupportedOperationException");
} catch (IllegalArgumentException expected) {
} catch (UnsupportedOperationException expected) {
}
}
// TODO: test adding element of wrong type
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/google/super/com/google/common/collect/testing/google/AbstractMultisetSetCountTester.java | Java | asf20 | 12,842 |
/*
* Copyright (C) 2012 The Guava 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.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.BiMap;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.testing.SerializableTester;
import java.io.Serializable;
/**
* Tests for the {@code inverse} view of a BiMap.
*
* <p>This assumes that {@code bimap.inverse().inverse() == bimap}, which is not technically
* required but is fulfilled by all current implementations.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class BiMapInverseTester<K, V> extends AbstractBiMapTester<K, V> {
public void testInverseSame() {
assertSame(getMap(), getMap().inverse().inverse());
}
@CollectionFeature.Require(SERIALIZABLE)
public void testInverseSerialization() {
BiMapPair<K, V> pair = new BiMapPair<K, V>(getMap());
BiMapPair<K, V> copy = SerializableTester.reserialize(pair);
assertEquals(pair.forward, copy.forward);
assertEquals(pair.backward, copy.backward);
assertSame(copy.backward, copy.forward.inverse());
assertSame(copy.forward, copy.backward.inverse());
}
private static class BiMapPair<K, V> implements Serializable {
final BiMap<K, V> forward;
final BiMap<V, K> backward;
BiMapPair(BiMap<K, V> original) {
this.forward = original;
this.backward = original.inverse();
}
private static final long serialVersionUID = 0;
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/google/super/com/google/common/collect/testing/google/BiMapInverseTester.java | Java | asf20 | 2,162 |
/*
* Copyright (C) 2011 The Guava 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.common.collect.testing.google;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import java.util.Arrays;
import java.util.Iterator;
/**
* Tester to make sure the {@code iterator().remove()} implementation of {@code Multiset} works when
* there are multiple occurrences of elements.
*
* @author Louis Wasserman
*/
@GwtCompatible(emulated = true)
public class MultisetIteratorTester<E> extends AbstractMultisetTester<E> {
@SuppressWarnings("unchecked")
@CollectionFeature.Require({SUPPORTS_ITERATOR_REMOVE, KNOWN_ORDER})
public void testRemovingIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = SUPPORTS_ITERATOR_REMOVE, absent = KNOWN_ORDER)
public void testRemovingIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.MODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE)
public void testIteratorKnownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, getSubjectGenerator().order(
Arrays.asList(samples.e0, samples.e1, samples.e1, samples.e2)),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
@SuppressWarnings("unchecked")
@CollectionFeature.Require(absent = {SUPPORTS_ITERATOR_REMOVE, KNOWN_ORDER})
public void testIteratorUnknownOrder() {
new IteratorTester<E>(4, IteratorFeature.UNMODIFIABLE, Arrays.asList(samples.e0, samples.e1,
samples.e1, samples.e2), IteratorTester.KnownOrder.UNKNOWN_ORDER) {
@Override
protected Iterator<E> newTargetIterator() {
return getSubjectGenerator().create(samples.e0, samples.e1, samples.e1, samples.e2)
.iterator();
}
}.test();
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/google/super/com/google/common/collect/testing/google/MultisetIteratorTester.java | Java | asf20 | 3,661 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.google;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newTreeSet;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST;
import static com.google.common.collect.testing.SampleElements.Strings.AFTER_LAST_2;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST;
import static com.google.common.collect.testing.SampleElements.Strings.BEFORE_FIRST_2;
import static junit.framework.Assert.assertEquals;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.testing.TestCollectionGenerator;
import com.google.common.collect.testing.TestCollidingSetGenerator;
import com.google.common.collect.testing.TestIntegerSortedSetGenerator;
import com.google.common.collect.testing.TestSetGenerator;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.TestStringSortedSetGenerator;
import com.google.common.collect.testing.TestUnhashableCollectionGenerator;
import com.google.common.collect.testing.UnhashableObject;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
/**
* Generators of different types of sets and derived collections from sets.
*
* @author Kevin Bourrillion
* @author Jared Levy
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
public class SetGenerators {
public static class ImmutableSetCopyOfGenerator extends TestStringSetGenerator {
@Override protected Set<String> create(String[] elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class ImmutableSetWithBadHashesGenerator
extends TestCollidingSetGenerator
// Work around a GWT compiler bug. Not explicitly listing this will
// cause the createArray() method missing in the generated javascript.
// TODO: Remove this once the GWT bug is fixed.
implements TestCollectionGenerator<Object> {
@Override
public Set<Object> create(Object... elements) {
return ImmutableSet.copyOf(elements);
}
}
public static class DegeneratedImmutableSetGenerator
extends TestStringSetGenerator {
// Make sure we get what we think we're getting, or else this test
// is pointless
@SuppressWarnings("cast")
@Override protected Set<String> create(String[] elements) {
return (ImmutableSet<String>)
ImmutableSet.of(elements[0], elements[0]);
}
}
public static class ImmutableSortedSetCopyOfGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSortedSetHeadsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.headSet("zzy");
}
}
public static class ImmutableSortedSetTailsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
return ImmutableSortedSet.copyOf(list)
.tailSet("\0\0");
}
}
public static class ImmutableSortedSetSubsetGenerator
extends TestStringSortedSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
List<String> list = Lists.newArrayList(elements);
list.add("\0");
list.add("zzz");
return ImmutableSortedSet.copyOf(list)
.subSet("\0\0", "zzy");
}
}
public static class ImmutableSortedSetExplicitComparator
extends TestStringSetGenerator {
private static final Comparator<String> STRING_REVERSED
= Collections.reverseOrder();
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.orderedBy(STRING_REVERSED)
.add(elements)
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetExplicitSuperclassComparatorGenerator
extends TestStringSetGenerator {
private static final Comparator<Comparable<?>> COMPARABLE_REVERSED
= Collections.reverseOrder();
@Override protected SortedSet<String> create(String[] elements) {
return new ImmutableSortedSet.Builder<String>(COMPARABLE_REVERSED)
.add(elements)
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetReversedOrderGenerator
extends TestStringSetGenerator {
@Override protected SortedSet<String> create(String[] elements) {
return ImmutableSortedSet.<String>reverseOrder()
.addAll(Arrays.asList(elements).iterator())
.build();
}
@Override public List<String> order(List<String> insertionOrder) {
Collections.sort(insertionOrder, Collections.reverseOrder());
return insertionOrder;
}
}
public static class ImmutableSortedSetUnhashableGenerator
extends TestUnhashableSetGenerator {
@Override public Set<UnhashableObject> create(
UnhashableObject[] elements) {
return ImmutableSortedSet.copyOf(elements);
}
}
public static class ImmutableSetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
return ImmutableSet.copyOf(elements).asList();
}
}
public static class ImmutableSortedSetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSet<String> set = ImmutableSortedSet.copyOf(
comparator, Arrays.asList(elements));
return set.asList();
}
}
public static class ImmutableSortedSetSubsetAsListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST).asList();
}
}
public static class ImmutableSortedSetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(elements);
builder.add(AFTER_LAST);
return builder.build().asList().subList(1, elements.length + 1);
}
}
public static class ImmutableSortedSetSubsetAsListSubListGenerator
extends TestStringListGenerator {
@Override protected List<String> create(String[] elements) {
Comparator<String> comparator = createExplicitComparator(elements);
ImmutableSortedSet.Builder<String> builder
= ImmutableSortedSet.orderedBy(comparator);
builder.add(BEFORE_FIRST);
builder.add(BEFORE_FIRST_2);
builder.add(elements);
builder.add(AFTER_LAST);
builder.add(AFTER_LAST_2);
return builder.build().subSet(BEFORE_FIRST_2,
AFTER_LAST_2)
.asList().subList(1, elements.length + 1);
}
}
public abstract static class TestUnhashableSetGenerator
extends TestUnhashableCollectionGenerator<Set<UnhashableObject>>
implements TestSetGenerator<UnhashableObject> {
}
private static Ordering<String> createExplicitComparator(
String[] elements) {
// Collapse equal elements, which Ordering.explicit() doesn't support, while
// maintaining the ordering by first occurrence.
Set<String> elementsPlus = Sets.newLinkedHashSet();
elementsPlus.add(BEFORE_FIRST);
elementsPlus.add(BEFORE_FIRST_2);
elementsPlus.addAll(Arrays.asList(elements));
elementsPlus.add(AFTER_LAST);
elementsPlus.add(AFTER_LAST_2);
return Ordering.explicit(Lists.newArrayList(elementsPlus));
}
/*
* All the ContiguousSet generators below manually reject nulls here. In principle, we'd like to
* defer that to Range, since it's ContiguousSet.create() that's used to create the sets. However,
* that gets messy here, and we already have null tests for Range.
*/
/*
* These generators also rely on consecutive integer inputs (not necessarily in order, but no
* holes).
*/
// SetCreationTester has some tests that pass in duplicates. Dedup them.
private static <E extends Comparable<? super E>> SortedSet<E> nullCheckedTreeSet(E[] elements) {
SortedSet<E> set = newTreeSet();
for (E element : elements) {
// Explicit null check because TreeSet wrongly accepts add(null) when empty.
set.add(checkNotNull(element));
}
return set;
}
public static class ContiguousSetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
return checkedCreate(nullCheckedTreeSet(elements));
}
}
public static class ContiguousSetHeadsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooHigh = (set.isEmpty()) ? 0 : set.last() + 1;
set.add(tooHigh);
return checkedCreate(set).headSet(tooHigh);
}
}
public static class ContiguousSetTailsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
int tooLow = (set.isEmpty()) ? 0 : set.first() - 1;
set.add(tooLow);
return checkedCreate(set).tailSet(tooLow + 1);
}
}
public static class ContiguousSetSubsetGenerator extends AbstractContiguousSetGenerator {
@Override protected SortedSet<Integer> create(Integer[] elements) {
SortedSet<Integer> set = nullCheckedTreeSet(elements);
if (set.isEmpty()) {
/*
* The (tooLow + 1, tooHigh) arguments below would be invalid because tooLow would be
* greater than tooHigh.
*/
return ContiguousSet.create(Range.openClosed(0, 1), DiscreteDomain.integers()).subSet(0, 1);
}
int tooHigh = set.last() + 1;
int tooLow = set.first() - 1;
set.add(tooHigh);
set.add(tooLow);
return checkedCreate(set).subSet(tooLow + 1, tooHigh);
}
}
private abstract static class AbstractContiguousSetGenerator
extends TestIntegerSortedSetGenerator {
protected final ContiguousSet<Integer> checkedCreate(SortedSet<Integer> elementsSet) {
List<Integer> elements = newArrayList(elementsSet);
/*
* A ContiguousSet can't have holes. If a test demands a hole, it should be changed so that it
* doesn't need one, or it should be suppressed for ContiguousSet.
*/
for (int i = 0; i < elements.size() - 1; i++) {
assertEquals(elements.get(i) + 1, (int) elements.get(i + 1));
}
Range<Integer> range =
(elements.isEmpty()) ? Range.closedOpen(0, 0) : Range.encloseAll(elements);
return ContiguousSet.create(range, DiscreteDomain.integers());
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/google/super/com/google/common/collect/testing/google/SetGenerators.java | Java | asf20 | 13,122 |
/*
* Copyright (C) 2009 The Guava 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.common.collect.testing;
import static java.util.Collections.sort;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@GwtCompatible(emulated = true)
public class Helpers {
// Clone of Objects.equal
static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
// Clone of Lists.newArrayList
public static <E> List<E> copyToList(Iterable<? extends E> elements) {
List<E> list = new ArrayList<E>();
addAll(list, elements);
return list;
}
public static <E> List<E> copyToList(E[] elements) {
return copyToList(Arrays.asList(elements));
}
// Clone of Sets.newLinkedHashSet
public static <E> Set<E> copyToSet(Iterable<? extends E> elements) {
Set<E> set = new LinkedHashSet<E>();
addAll(set, elements);
return set;
}
public static <E> Set<E> copyToSet(E[] elements) {
return copyToSet(Arrays.asList(elements));
}
// Would use Maps.immutableEntry
public static <K, V> Entry<K, V> mapEntry(K key, V value) {
return Collections.singletonMap(key, value).entrySet().iterator().next();
}
public static void assertEqualIgnoringOrder(
Iterable<?> expected, Iterable<?> actual) {
List<?> exp = copyToList(expected);
List<?> act = copyToList(actual);
String actString = act.toString();
// Of course we could take pains to give the complete description of the
// problem on any failure.
// Yeah it's n^2.
for (Object object : exp) {
if (!act.remove(object)) {
Assert.fail("did not contain expected element " + object + ", "
+ "expected = " + exp + ", actual = " + actString);
}
}
assertTrue("unexpected elements: " + act, act.isEmpty());
}
public static void assertContentsAnyOrder(
Iterable<?> actual, Object... expected) {
assertEqualIgnoringOrder(Arrays.asList(expected), actual);
}
public static <E> boolean addAll(
Collection<E> addTo, Iterable<? extends E> elementsToAdd) {
boolean modified = false;
for (E e : elementsToAdd) {
modified |= addTo.add(e);
}
return modified;
}
static <T> Iterable<T> reverse(final List<T> list) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
final ListIterator<T> listIter = list.listIterator(list.size());
return new Iterator<T>() {
@Override
public boolean hasNext() {
return listIter.hasPrevious();
}
@Override
public T next() {
return listIter.previous();
}
@Override
public void remove() {
listIter.remove();
}
};
}
};
}
static <T> Iterator<T> cycle(final Iterable<T> iterable) {
return new Iterator<T>() {
Iterator<T> iterator = Collections.<T>emptySet().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
if (!iterator.hasNext()) {
iterator = iterable.iterator();
}
return iterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
static <T> T get(Iterator<T> iterator, int position) {
for (int i = 0; i < position; i++) {
iterator.next();
}
return iterator.next();
}
static void fail(Throwable cause, Object message) {
AssertionFailedError assertionFailedError =
new AssertionFailedError(String.valueOf(message));
assertionFailedError.initCause(cause);
throw assertionFailedError;
}
public static <K, V> Comparator<Entry<K, V>> entryComparator(
final Comparator<? super K> keyComparator) {
return new Comparator<Entry<K, V>>() {
@Override
@SuppressWarnings("unchecked") // no less safe than putting it in the map!
public int compare(Entry<K, V> a, Entry<K, V> b) {
return (keyComparator == null)
? ((Comparable) a.getKey()).compareTo(b.getKey())
: keyComparator.compare(a.getKey(), b.getKey());
}
};
}
public static <T> void testComparator(
Comparator<? super T> comparator, T... valuesInExpectedOrder) {
testComparator(comparator, Arrays.asList(valuesInExpectedOrder));
}
public static <T> void testComparator(
Comparator<? super T> comparator, List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
T t = valuesInExpectedOrder.get(i);
for (int j = 0; j < i; j++) {
T lesser = valuesInExpectedOrder.get(j);
assertTrue(comparator + ".compare(" + lesser + ", " + t + ")",
comparator.compare(lesser, t) < 0);
}
assertEquals(comparator + ".compare(" + t + ", " + t + ")",
0, comparator.compare(t, t));
for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) {
T greater = valuesInExpectedOrder.get(j);
assertTrue(comparator + ".compare(" + greater + ", " + t + ")",
comparator.compare(greater, t) > 0);
}
}
}
public static <T extends Comparable<? super T>> void testCompareToAndEquals(
List<T> valuesInExpectedOrder) {
// This does an O(n^2) test of all pairs of values in both orders
for (int i = 0; i < valuesInExpectedOrder.size(); i++) {
T t = valuesInExpectedOrder.get(i);
for (int j = 0; j < i; j++) {
T lesser = valuesInExpectedOrder.get(j);
assertTrue(lesser + ".compareTo(" + t + ')', lesser.compareTo(t) < 0);
assertFalse(lesser.equals(t));
}
assertEquals(t + ".compareTo(" + t + ')', 0, t.compareTo(t));
assertTrue(t.equals(t));
for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) {
T greater = valuesInExpectedOrder.get(j);
assertTrue(greater + ".compareTo(" + t + ')', greater.compareTo(t) > 0);
assertFalse(greater.equals(t));
}
}
}
/**
* Returns a collection that simulates concurrent modification by
* having its size method return incorrect values. This is useful
* for testing methods that must treat the return value from size()
* as a hint only.
*
* @param delta the difference between the true size of the
* collection and the values returned by the size method
*/
public static <T> Collection<T> misleadingSizeCollection(final int delta) {
// It would be nice to be able to return a real concurrent
// collection like ConcurrentLinkedQueue, so that e.g. concurrent
// iteration would work, but that would not be GWT-compatible.
return new ArrayList<T>() {
@Override public int size() { return Math.max(0, super.size() + delta); }
};
}
/**
* Returns a "nefarious" map entry with the specified key and value,
* meaning an entry that is suitable for testing that map entries cannot be
* modified via a nefarious implementation of equals. This is used for testing
* unmodifiable collections of map entries; for example, it should not be
* possible to access the raw (modifiable) map entry via a nefarious equals
* method.
*/
public static <K, V> Map.Entry<K, V> nefariousMapEntry(final K key,
final V value) {
return new Map.Entry<K, V>() {
@Override public K getKey() {
return key;
}
@Override public V getValue() {
return value;
}
@Override public V setValue(V value) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override public boolean equals(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<K, V> e = (Map.Entry<K, V>) o;
e.setValue(value); // muhahaha!
return equal(this.getKey(), e.getKey())
&& equal(this.getValue(), e.getValue());
}
return false;
}
@Override public int hashCode() {
K k = getKey();
V v = getValue();
return ((k == null) ?
0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());
}
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Override public String toString() {
return getKey() + "=" + getValue();
}
};
}
static <E> List<E> castOrCopyToList(Iterable<E> iterable) {
if (iterable instanceof List) {
return (List<E>) iterable;
}
List<E> list = new ArrayList<E>();
for (E e : iterable) {
list.add(e);
}
return list;
}
private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() {
@SuppressWarnings("unchecked") // assume any Comparable is Comparable<Self>
@Override public int compare(Comparable left, Comparable right) {
return left.compareTo(right);
}
};
public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey(
List<Entry<K, V>> insertionOrder) {
sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER));
return insertionOrder;
}
/**
* Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} to work around
* build-system quirks.
*/
private @interface GwtTransient {}
/**
* Compares strings in natural order except that null comes immediately before a given value. This
* works better than Ordering.natural().nullsFirst() because, if null comes before all other
* values, it lies outside the submap/submultiset ranges we test, and the variety of tests that
* exercise null handling fail on those subcollections.
*/
public abstract static class NullsBefore implements Comparator<String>, Serializable {
/*
* We don't serialize this class in GWT, so we don't care about whether GWT will serialize this
* field.
*/
@GwtTransient private final String justAfterNull;
protected NullsBefore(String justAfterNull) {
if (justAfterNull == null) {
throw new NullPointerException();
}
this.justAfterNull = justAfterNull;
}
@Override
public int compare(String lhs, String rhs) {
if (lhs == rhs) {
return 0;
}
if (lhs == null) {
// lhs (null) comes just before justAfterNull.
// If rhs is b, lhs comes first.
if (rhs.equals(justAfterNull)) {
return -1;
}
return justAfterNull.compareTo(rhs);
}
if (rhs == null) {
// rhs (null) comes just before justAfterNull.
// If lhs is b, rhs comes first.
if (lhs.equals(justAfterNull)) {
return 1;
}
return lhs.compareTo(justAfterNull);
}
return lhs.compareTo(rhs);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof NullsBefore) {
NullsBefore other = (NullsBefore) obj;
return justAfterNull.equals(other.justAfterNull);
}
return false;
}
@Override
public int hashCode() {
return justAfterNull.hashCode();
}
}
public static final class NullsBeforeB extends NullsBefore {
public static final NullsBeforeB INSTANCE = new NullsBeforeB();
private NullsBeforeB() {
super("b");
}
}
public static final class NullsBeforeTwo extends NullsBefore {
public static final NullsBeforeTwo INSTANCE = new NullsBeforeTwo();
private NullsBeforeTwo() {
super("two"); // from TestStringSortedMapGenerator's sample keys
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/Helpers.java | Java | asf20 | 12,708 |
/*
* Copyright (C) 2009 The Guava 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.common.collect.testing;
import com.google.gwt.core.client.GwtScriptOnly;
import com.google.gwt.lang.Array;
/**
* Version of {@link GwtPlatform} used in web-mode. It includes methods in
* {@link Platform} that requires different implementions in web mode and
* hosted mode. It is factored out from {@link Platform} because <code>
* {@literal @}GwtScriptOnly</code> only supports public classes and methods.
*
* @author Hayward Chan
*/
@GwtScriptOnly
public final class GwtPlatform {
private GwtPlatform() {}
public static <T> T[] clone(T[] array) {
return (T[]) Array.clone(array);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/GwtPlatform.java | Java | asf20 | 1,229 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_REMOVE_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static java.util.Collections.emptyList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import com.google.common.testing.SerializableTester;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A generic JUnit test which tests {@code subList()} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListSubListTester<E> extends AbstractListTester<E> {
public void testSubList_startNegative() {
try {
getList().subList(-1, 0);
fail("subList(-1, 0) should throw");
} catch (IndexOutOfBoundsException expected) {
}
}
public void testSubList_endTooLarge() {
try {
getList().subList(0, getNumElements() + 1);
fail("subList(0, size + 1) should throw");
} catch (IndexOutOfBoundsException expected) {
}
}
public void testSubList_startGreaterThanEnd() {
try {
getList().subList(1, 0);
fail("subList(1, 0) should throw");
} catch (IndexOutOfBoundsException expected) {
} catch (IllegalArgumentException expected) {
/*
* The subList() docs claim that this should be an
* IndexOutOfBoundsException, but many JDK implementations throw
* IllegalArgumentException:
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4506427
*/
}
}
public void testSubList_empty() {
assertEquals("subList(0, 0) should be empty",
emptyList(), getList().subList(0, 0));
}
public void testSubList_entireList() {
assertEquals("subList(0, size) should be equal to the original list",
getList(), getList().subList(0, getNumElements()));
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListRemoveAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.remove(0);
List<E> expected =
Arrays.asList(createSamplesArray()).subList(1, getNumElements());
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListClearAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.clear();
List<E> expected =
Arrays.asList(createSamplesArray()).subList(1, getNumElements());
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testSubList_subListAddAffectsOriginal() {
List<E> subList = getList().subList(0, 0);
subList.add(samples.e3);
expectAdded(0, samples.e3);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSubList_subListSetAffectsOriginal() {
List<E> subList = getList().subList(0, 1);
subList.set(0, samples.e3);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.set(0, samples.e3);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSubList_originalListSetAffectsSubList() {
List<E> subList = getList().subList(0, 1);
getList().set(0, samples.e3);
assertEquals("A set() call to a list after a sublist has been created "
+ "should be reflected in the sublist",
Collections.singletonList(samples.e3), subList);
}
@ListFeature.Require(SUPPORTS_REMOVE_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListRemoveAffectsOriginalLargeList() {
List<E> subList = getList().subList(1, 3);
subList.remove(samples.e2);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.remove(2);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListAddAtIndexAffectsOriginalLargeList() {
List<E> subList = getList().subList(2, 3);
subList.add(0, samples.e3);
expectAdded(2, samples.e3);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_subListSetAffectsOriginalLargeList() {
List<E> subList = getList().subList(1, 2);
subList.set(0, samples.e3);
List<E> expected = Helpers.copyToList(createSamplesArray());
expected.set(1, samples.e3);
expectContents(expected);
}
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_originalListSetAffectsSubListLargeList() {
List<E> subList = getList().subList(1, 3);
getList().set(1, samples.e3);
assertEquals("A set() call to a list after a sublist has been created "
+ "should be reflected in the sublist",
Arrays.asList(samples.e3, samples.e2), subList);
}
public void testSubList_ofSubListEmpty() {
List<E> subList = getList().subList(0, 0).subList(0, 0);
assertEquals("subList(0, 0).subList(0, 0) should be an empty list",
emptyList(), subList);
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_ofSubListNonEmpty() {
List<E> subList = getList().subList(0, 2).subList(1, 2);
assertEquals("subList(0, 2).subList(1, 2) "
+ "should be a single-element list of the element at index 1",
Collections.singletonList(getOrderedElements().get(1)), subList);
}
@CollectionSize.Require(absent = {ZERO})
public void testSubList_size() {
List<E> list = getList();
int size = getNumElements();
assertEquals(list.subList(0, size).size(),
size);
assertEquals(list.subList(0, size - 1).size(),
size - 1);
assertEquals(list.subList(1, size).size(),
size - 1);
assertEquals(list.subList(size, size).size(),
0);
assertEquals(list.subList(0, 0).size(),
0);
}
@CollectionSize.Require(absent = {ZERO})
public void testSubList_isEmpty() {
List<E> list = getList();
int size = getNumElements();
for (List<E> subList : Arrays.asList(
list.subList(0, size),
list.subList(0, size - 1),
list.subList(1, size),
list.subList(0, 0),
list.subList(size, size))) {
assertEquals(subList.isEmpty(), subList.size() == 0);
}
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_get() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(list.get(0), copy.get(0));
assertEquals(list.get(size - 1), copy.get(size - 1));
assertEquals(list.get(1), tail.get(0));
assertEquals(list.get(size - 1), tail.get(size - 2));
assertEquals(list.get(0), head.get(0));
assertEquals(list.get(size - 2), head.get(size - 2));
for (List<E> subList : Arrays.asList(copy, head, tail)) {
for (int index : Arrays.asList(-1, subList.size())) {
try {
subList.get(index);
fail("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
}
}
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_contains() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertTrue(copy.contains(list.get(0)));
assertTrue(head.contains(list.get(0)));
assertTrue(tail.contains(list.get(1)));
// The following assumes all elements are distinct.
assertTrue(copy.contains(list.get(size - 1)));
assertTrue(head.contains(list.get(size - 2)));
assertTrue(tail.contains(list.get(size - 1)));
assertFalse(head.contains(list.get(size - 1)));
assertFalse(tail.contains(list.get(0)));
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_indexOf() {
List<E> list = getList();
int size = getNumElements();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(copy.indexOf(list.get(0)),
0);
assertEquals(head.indexOf(list.get(0)),
0);
assertEquals(tail.indexOf(list.get(1)),
0);
// The following assumes all elements are distinct.
assertEquals(copy.indexOf(list.get(size - 1)),
size - 1);
assertEquals(head.indexOf(list.get(size - 2)),
size - 2);
assertEquals(tail.indexOf(list.get(size - 1)),
size - 2);
assertEquals(head.indexOf(list.get(size - 1)),
-1);
assertEquals(tail.indexOf(list.get(0)),
-1);
}
@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_lastIndexOf() {
List<E> list = getList();
int size = list.size();
List<E> copy = list.subList(0, size);
List<E> head = list.subList(0, size - 1);
List<E> tail = list.subList(1, size);
assertEquals(copy.lastIndexOf(list.get(size - 1)),
size - 1);
assertEquals(head.lastIndexOf(list.get(size - 2)),
size - 2);
assertEquals(tail.lastIndexOf(list.get(size - 1)),
size - 2);
// The following assumes all elements are distinct.
assertEquals(copy.lastIndexOf(list.get(0)),
0);
assertEquals(head.lastIndexOf(list.get(0)),
0);
assertEquals(tail.lastIndexOf(list.get(1)),
0);
assertEquals(head.lastIndexOf(list.get(size - 1)),
-1);
assertEquals(tail.lastIndexOf(list.get(0)),
-1);
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testReserializeWholeSubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, getNumElements()));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
public void testReserializeEmptySubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, 0));
}
@CollectionFeature.Require(SERIALIZABLE_INCLUDING_VIEWS)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testReserializeSubList() {
SerializableTester.reserializeAndAssert(getList().subList(0, 2));
}
/*
* TODO: perform all List tests on subList(), but beware infinite recursion
*/
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/ListSubListTester.java | Java | asf20 | 12,036 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import com.google.common.annotations.GwtCompatible;
/**
* Tests {@link java.util.List#hashCode}.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class ListHashCodeTester<E> extends AbstractListTester<E> {
public void testHashCode() {
int expectedHashCode = 1;
for (E element : getOrderedElements()) {
expectedHashCode = 31 * expectedHashCode +
((element == null) ? 0 : element.hashCode());
}
assertEquals(
"A List's hashCode() should be computed from those of its elements.",
expectedHashCode, getList().hashCode());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/ListHashCodeTester.java | Java | asf20 | 1,264 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
/**
* A generic JUnit test which tests {@code set()} operations on a list. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class ListSetTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_SET)
@CollectionSize.Require(absent = ZERO)
public void testSet() {
doTestSet(samples.e3);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@ListFeature.Require(SUPPORTS_SET)
public void testSet_null() {
doTestSet(null);
}
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@ListFeature.Require(SUPPORTS_SET)
public void testSet_replacingNull() {
E[] elements = createSamplesArray();
int i = aValidIndex();
elements[i] = null;
collection = getSubjectGenerator().create(elements);
doTestSet(samples.e3);
}
private void doTestSet(E newValue) {
int index = aValidIndex();
E initialValue = getList().get(index);
assertEquals("set(i, x) should return the old element at position i.",
initialValue, getList().set(index, newValue));
assertEquals("After set(i, x), get(i) should return x",
newValue, getList().get(index));
assertEquals("set() should not change the size of a list.",
getNumElements(), getList().size());
}
@ListFeature.Require(SUPPORTS_SET)
public void testSet_indexTooLow() {
try {
getList().set(-1, samples.e3);
fail("set(-1) should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_SET)
public void testSet_indexTooHigh() {
int index = getNumElements();
try {
getList().set(index, samples.e3);
fail("set(size) should throw IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@ListFeature.Require(absent = SUPPORTS_SET)
public void testSet_unsupported() {
try {
getList().set(aValidIndex(), samples.e3);
fail("set() should throw UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionSize.Require(ZERO)
@ListFeature.Require(absent = SUPPORTS_SET)
public void testSet_unsupportedByEmptyList() {
try {
getList().set(0, samples.e3);
fail("set() should throw UnsupportedOperationException "
+ "or IndexOutOfBoundsException");
} catch (UnsupportedOperationException tolerated) {
} catch (IndexOutOfBoundsException tolerated) {
}
expectUnchanged();
}
@CollectionSize.Require(absent = ZERO)
@ListFeature.Require(SUPPORTS_SET)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testSet_nullUnsupported() {
try {
getList().set(aValidIndex(), null);
fail("set(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
expectUnchanged();
}
private int aValidIndex() {
return getList().size() / 2;
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/ListSetTester.java | Java | asf20 | 4,386 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public class CollectionCreationTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNull_supported() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
expectContents(array);
}
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNull_unsupported() {
E[] array = createArrayWithNullElement();
try {
getSubjectGenerator().create(array);
fail("Creating a collection containing null should fail");
} catch (NullPointerException expected) {
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/CollectionCreationTester.java | Java | asf20 | 2,105 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code add} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class CollectionAddTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAdd_supportedNotPresent() {
assertTrue("add(notPresent) should return true",
collection.add(samples.e3));
expectAdded(samples.e3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAdd_unsupportedNotPresent() {
try {
collection.add(samples.e3);
fail("add(notPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_unsupportedPresent() {
try {
assertFalse("add(present) should return false or throw",
collection.add(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(
value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES},
absent = RESTRICTS_ELEMENTS)
public void testAdd_nullSupported() {
assertTrue("add(null) should return true", collection.add(null));
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD,
absent = ALLOWS_NULL_VALUES)
public void testAdd_nullUnsupported() {
try {
collection.add(null);
fail("add(null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported add(null)");
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.add(samples.e3));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/CollectionAddTester.java | Java | asf20 | 3,860 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ITERATOR_REMOVE;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.IteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A generic JUnit test which tests {@code iterator} operations on a collection.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public class CollectionIteratorTester<E> extends AbstractCollectionTester<E> {
public void testIterator() {
List<E> iteratorElements = new ArrayList<E>();
for (E element : collection) { // uses iterator()
iteratorElements.add(element);
}
Helpers.assertEqualIgnoringOrder(
Arrays.asList(createSamplesArray()), iteratorElements);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testIterationOrdering() {
List<E> iteratorElements = new ArrayList<E>();
for (E element : collection) { // uses iterator()
iteratorElements.add(element);
}
List<E> expected = Helpers.copyToList(getOrderedElements());
assertEquals("Different ordered iteration", expected, iteratorElements);
}
// TODO: switch to DerivedIteratorTestSuiteBuilder
@CollectionFeature.Require({KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE})
public void testIterator_knownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(value = KNOWN_ORDER, absent = SUPPORTS_ITERATOR_REMOVE)
public void testIterator_knownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.KNOWN_ORDER,
getOrderedElements());
}
@CollectionFeature.Require(absent = KNOWN_ORDER, value = SUPPORTS_ITERATOR_REMOVE)
public void testIterator_unknownOrderRemoveSupported() {
runIteratorTest(MODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
@CollectionFeature.Require(absent = {KNOWN_ORDER, SUPPORTS_ITERATOR_REMOVE})
public void testIterator_unknownOrderRemoveUnsupported() {
runIteratorTest(UNMODIFIABLE, IteratorTester.KnownOrder.UNKNOWN_ORDER,
getSampleElements());
}
private void runIteratorTest(Set<IteratorFeature> features,
IteratorTester.KnownOrder knownOrder, Iterable<E> elements) {
new IteratorTester<E>(Platform.collectionIteratorTesterNumIterations(), features, elements,
knownOrder) {
@Override protected Iterator<E> newTargetIterator() {
resetCollection();
return collection.iterator();
}
@Override protected void verify(List<E> elements) {
expectContents(elements);
}
}.test();
}
public void testIteratorNoSuchElementException() {
Iterator<E> iterator = collection.iterator();
while (iterator.hasNext()) {
iterator.next();
}
try {
iterator.next();
fail("iterator.next() should throw NoSuchElementException");
} catch (NoSuchElementException expected) {}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/CollectionIteratorTester.java | Java | asf20 | 4,389 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
/**
* A generic JUnit test which tests add operations on a set. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.SetTestSuiteBuilder}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class SetAddTester<E> extends AbstractSetTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedPresent() {
assertFalse("add(present) should return false", getSet().add(samples.e0));
expectUnchanged();
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedNullPresent() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
assertFalse("add(nullPresent) should return false", getSet().add(null));
expectContents(array);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/SetAddTester.java | Java | asf20 | 2,011 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.ListFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
/**
* A generic JUnit test which tests {@code add(int, Object)} operations on a
* list. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListAddAtIndexTester<E> extends AbstractListTester<E> {
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAtIndex_supportedPresent() {
getList().add(0, samples.e0);
expectAdded(0, samples.e0);
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
/*
* absent = ZERO isn't required, since unmodList.add() must
* throw regardless, but it keeps the method name accurate.
*/
public void testAddAtIndex_unsupportedPresent() {
try {
getList().add(0, samples.e0);
fail("add(n, present) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_supportedNotPresent() {
getList().add(0, samples.e3);
expectAdded(0, samples.e3);
}
@CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION)
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndexConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
getList().add(0, samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_unsupportedNotPresent() {
try {
getList().add(0, samples.e3);
fail("add(n, notPresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testAddAtIndex_middle() {
getList().add(getNumElements() / 2, samples.e3);
expectAdded(getNumElements() / 2, samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionSize.Require(absent = ZERO)
public void testAddAtIndex_end() {
getList().add(getNumElements(), samples.e3);
expectAdded(getNumElements(), samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testAddAtIndex_nullSupported() {
getList().add(0, null);
expectAdded(0, (E) null);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
@CollectionFeature.Require(absent = ALLOWS_NULL_VALUES)
public void testAddAtIndex_nullUnsupported() {
try {
getList().add(0, null);
fail("add(n, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported add(n, null)");
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_negative() {
try {
getList().add(-1, samples.e3);
fail("add(-1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@ListFeature.Require(SUPPORTS_ADD_WITH_INDEX)
public void testAddAtIndex_tooLarge() {
try {
getList().add(getNumElements() + 1, samples.e3);
fail("add(size + 1, e) should throw");
} catch (IndexOutOfBoundsException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/ListAddAtIndexTester.java | Java | asf20 | 5,167 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.List;
/**
* A generic JUnit test which tests {@code add(Object)} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* @author Chris Povirk
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class ListAddTester<E> extends AbstractListTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedPresent() {
assertTrue("add(present) should return true", getList().add(samples.e0));
expectAdded(samples.e0);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
/*
* absent = ZERO isn't required, since unmodList.add() must
* throw regardless, but it keeps the method name accurate.
*/
public void testAdd_unsupportedPresent() {
try {
getList().add(samples.e0);
fail("add(present) should throw");
} catch (UnsupportedOperationException expected) {
}
}
@CollectionFeature.Require(value = {SUPPORTS_ADD, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testAdd_supportedNullPresent() {
E[] array = createArrayWithNullElement();
collection = getSubjectGenerator().create(array);
assertTrue("add(nullPresent) should return true", getList().add(null));
List<E> expected = Helpers.copyToList(array);
expected.add(null);
expectContents(expected);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/ListAddTester.java | Java | asf20 | 2,684 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.IteratorFeature.MODIFIABLE;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_REMOVE;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_ADD_WITH_INDEX;
import static com.google.common.collect.testing.features.ListFeature.SUPPORTS_SET;
import static com.google.common.collect.testing.testers.Platform.listListIteratorTesterNumIterations;
import static java.util.Collections.singleton;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.IteratorFeature;
import com.google.common.collect.testing.ListIteratorTester;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.ListFeature;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
/**
* A generic JUnit test which tests {@code listIterator} operations on a list.
* Can't be invoked directly; please see
* {@link com.google.common.collect.testing.ListTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class ListListIteratorTester<E> extends AbstractListTester<E> {
// TODO: switch to DerivedIteratorTestSuiteBuilder
@CollectionFeature.Require(absent = SUPPORTS_REMOVE)
@ListFeature.Require(absent = {SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX})
public void testListIterator_unmodifiable() {
runListIteratorTest(UNMODIFIABLE);
}
/*
* For now, we don't cope with testing this when the list supports only some
* modification operations.
*/
@CollectionFeature.Require(SUPPORTS_REMOVE)
@ListFeature.Require({SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX})
public void testListIterator_fullyModifiable() {
runListIteratorTest(MODIFIABLE);
}
private void runListIteratorTest(Set<IteratorFeature> features) {
new ListIteratorTester<E>(
listListIteratorTesterNumIterations(), singleton(samples.e4), features,
Helpers.copyToList(getOrderedElements()), 0) {
{
// TODO: don't set this universally
stopTestingWhenAddThrowsException();
}
@Override protected ListIterator<E> newTargetIterator() {
resetCollection();
return getList().listIterator();
}
@Override protected void verify(List<E> elements) {
expectContents(elements);
}
}.test();
}
public void testListIterator_tooLow() {
try {
getList().listIterator(-1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testListIterator_tooHigh() {
try {
getList().listIterator(getNumElements() + 1);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testListIterator_atSize() {
getList().listIterator(getNumElements());
// TODO: run the iterator through ListIteratorTester
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/ListListIteratorTester.java | Java | asf20 | 3,704 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.KNOWN_ORDER;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.Helpers;
import com.google.common.collect.testing.WrongType;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Arrays;
import java.util.List;
/**
* A generic JUnit test which tests {@code toArray()} operations on a
* collection. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
@GwtCompatible(emulated = true)
public class CollectionToArrayTester<E> extends AbstractCollectionTester<E> {
public void testToArray_noArgs() {
Object[] array = collection.toArray();
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
/**
* {@link Collection#toArray(Object[])} says: "Note that
* <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>."
*
* <p>For maximum effect, the collection under test should be created from an
* element array of a type other than {@code Object[]}.
*/
public void testToArray_isPlainObjectArray() {
Object[] array = collection.toArray();
assertEquals(Object[].class, array.getClass());
}
public void testToArray_emptyArray() {
E[] empty = getSubjectGenerator().createArray(0);
E[] array = collection.toArray(empty);
assertEquals("toArray(emptyT[]) should return an array of type T",
empty.getClass(), array.getClass());
assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_emptyArray_ordered() {
E[] empty = getSubjectGenerator().createArray(0);
E[] array = collection.toArray(empty);
assertEquals("toArray(emptyT[]) should return an array of type T",
empty.getClass(), array.getClass());
assertEquals("toArray(emptyT[]).length:", getNumElements(), array.length);
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_emptyArrayOfObject() {
Object[] in = new Object[0];
Object[] array = collection.toArray(in);
assertEquals("toArray(emptyObject[]) should return an array of type Object",
Object[].class, array.getClass());
assertEquals("toArray(emptyObject[]).length",
getNumElements(), array.length);
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
public void testToArray_rightSizedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements());
assertSame("toArray(sameSizeE[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_rightSizedArray_ordered() {
E[] array = getSubjectGenerator().createArray(getNumElements());
assertSame("toArray(sameSizeE[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_rightSizedArrayOfObject() {
Object[] array = new Object[getNumElements()];
assertSame("toArray(sameSizeObject[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsAnyOrder(createSamplesArray(), array);
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_rightSizedArrayOfObject_ordered() {
Object[] array = new Object[getNumElements()];
assertSame("toArray(sameSizeObject[]) should return the given array",
array, collection.toArray(array));
expectArrayContentsInOrder(getOrderedElements(), array);
}
public void testToArray_oversizedArray() {
E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
array[getNumElements()] = samples.e3;
array[getNumElements() + 1] = samples.e3;
assertSame("toArray(overSizedE[]) should return the given array",
array, collection.toArray(array));
List<E> subArray = Arrays.asList(array).subList(0, getNumElements());
E[] expectedSubArray = createSamplesArray();
for (int i = 0; i < getNumElements(); i++) {
assertTrue(
"toArray(overSizedE[]) should contain element " + expectedSubArray[i],
subArray.contains(expectedSubArray[i]));
}
assertNull("The array element "
+ "immediately following the end of the collection should be nulled",
array[getNumElements()]);
// array[getNumElements() + 1] might or might not have been nulled
}
@CollectionFeature.Require(KNOWN_ORDER)
public void testToArray_oversizedArray_ordered() {
E[] array = getSubjectGenerator().createArray(getNumElements() + 2);
array[getNumElements()] = samples.e3;
array[getNumElements() + 1] = samples.e3;
assertSame("toArray(overSizedE[]) should return the given array",
array, collection.toArray(array));
List<E> expected = getOrderedElements();
for (int i = 0; i < getNumElements(); i++) {
assertEquals(expected.get(i), array[i]);
}
assertNull("The array element "
+ "immediately following the end of the collection should be nulled",
array[getNumElements()]);
// array[getNumElements() + 1] might or might not have been nulled
}
@CollectionSize.Require(absent = ZERO)
public void testToArray_emptyArrayOfWrongTypeForNonEmptyCollection() {
try {
WrongType[] array = new WrongType[0];
collection.toArray(array);
fail("toArray(notAssignableTo[]) should throw");
} catch (ArrayStoreException expected) {
}
}
@CollectionSize.Require(ZERO)
public void testToArray_emptyArrayOfWrongTypeForEmptyCollection() {
WrongType[] array = new WrongType[0];
assertSame(
"toArray(sameSizeNotAssignableTo[]) should return the given array",
array, collection.toArray(array));
}
private void expectArrayContentsAnyOrder(Object[] expected, Object[] actual) {
Helpers.assertEqualIgnoringOrder(
Arrays.asList(expected), Arrays.asList(actual));
}
private void expectArrayContentsInOrder(List<E> expected, Object[] actual) {
assertEquals("toArray() ordered contents: ",
expected, Arrays.asList(actual));
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/CollectionToArrayTester.java | Java | asf20 | 7,287 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.Collection;
/**
* Tests {@link java.util.Set#hashCode}.
*
* @author George van den Driessche
*/
@GwtCompatible(emulated = true)
public class SetHashCodeTester<E> extends AbstractSetTester<E> {
public void testHashCode() {
int expectedHashCode = 0;
for (E element : getSampleElements()) {
expectedHashCode += ((element == null) ? 0 : element.hashCode());
}
assertEquals(
"A Set's hashCode() should be the sum of those of its elements.",
expectedHashCode, getSet().hashCode());
}
@CollectionSize.Require(absent = CollectionSize.ZERO)
@CollectionFeature.Require(ALLOWS_NULL_VALUES)
public void testHashCode_containingNull() {
Collection<E> elements = getSampleElements(getNumElements() - 1);
int expectedHashCode = 0;
for (E element : elements) {
expectedHashCode += ((element == null) ? 0 : element.hashCode());
}
elements.add(null);
collection = getSubjectGenerator().create(elements.toArray());
assertEquals(
"A Set's hashCode() should be the sum of those of its elements (with "
+ "a null element counting as having a hash of zero).",
expectedHashCode, getSet().hashCode());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/SetHashCodeTester.java | Java | asf20 | 2,155 |
/*
* Copyright (C) 2009 The Guava 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.common.collect.testing.testers;
import com.google.common.annotations.GwtCompatible;
import com.google.gwt.core.client.GWT;
/**
* The emulation source used in GWT.
*
* @author Hayward Chan
*/
@GwtCompatible(emulated = true)
final class Platform {
// Use fewer steps in the ListIteratorTester in ListListIteratorTester because it's slow in prod
// mode.
static int listListIteratorTesterNumIterations() {
// TODO(hhchan): It's 4 in java. Figure out why even 3 is too slow in prod mode.
return GWT.isProdMode() ? 2 : 4;
}
// Use fewer steps in the IteratorTester in CollectionIteratorTester because it's slow in prod
// mode..
static int collectionIteratorTesterNumIterations() {
return GWT.isProdMode() ? 3 : 5;
}
// TODO: Consolidate different copies in one single place.
static String format(String template, Object... args) {
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append("]");
}
return builder.toString();
}
private Platform() {}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/Platform.java | Java | asf20 | 2,430 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code put} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class MapPutTester<K, V> extends AbstractMapTester<K, V> {
private Entry<K, V> nullKeyEntry;
private Entry<K, V> nullValueEntry;
private Entry<K, V> nullKeyValueEntry;
private Entry<K, V> presentKeyNullValueEntry;
@Override public void setUp() throws Exception {
super.setUp();
nullKeyEntry = entry(null, samples.e3.getValue());
nullValueEntry = entry(samples.e3.getKey(), null);
nullKeyValueEntry = entry(null, null);
presentKeyNullValueEntry = entry(samples.e0.getKey(), null);
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPut_supportedNotPresent() {
assertNull("put(notPresent, value) should return null", put(samples.e3));
expectAdded(samples.e3);
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithKeySetIteration() {
try {
Iterator<K> iterator = getMap().keySet().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require({FAILS_FAST_ON_CONCURRENT_MODIFICATION, SUPPORTS_PUT})
@CollectionSize.Require(absent = ZERO)
public void testPutAbsentConcurrentWithValueIteration() {
try {
Iterator<V> iterator = getMap().values().iterator();
put(samples.e3);
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPut_unsupportedNotPresent() {
try {
put(samples.e3);
fail("put(notPresent, value) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3);
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPut_unsupportedPresentExistingValue() {
try {
assertEquals("put(present, existingValue) should return present or throw",
samples.e0.getValue(), put(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPut_unsupportedPresentDifferentValue() {
try {
getMap().put(samples.e0.getKey(), samples.e3.getValue());
fail("put(present, differentValue) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
public void testPut_nullKeySupportedNotPresent() {
assertNull("put(null, value) should return null", put(nullKeyEntry));
expectAdded(nullKeyEntry);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS})
@CollectionSize.Require(absent = ZERO)
public void testPut_nullKeySupportedPresent() {
Entry<K, V> newEntry = entry(null, samples.e3.getValue());
initMapWithNullKey();
assertEquals("put(present, value) should return the associated value",
getValueForNullKey(), put(newEntry));
Entry<K, V>[] expected = createArrayWithNullKey();
expected[getNullLocation()] = newEntry;
expectContents(expected);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_KEYS)
public void testPut_nullKeyUnsupported() {
try {
put(nullKeyEntry);
fail("put(null, value) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullKeyMissingWhenNullKeysUnsupported(
"Should not contain null key after unsupported put(null, value)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
public void testPut_nullValueSupported() {
assertNull("put(key, null) should return null", put(nullValueEntry));
expectAdded(nullValueEntry);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testPut_nullValueUnsupported() {
try {
put(nullValueEntry);
fail("put(key, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null value after unsupported put(key, null)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceWithNullValueSupported() {
assertEquals("put(present, null) should return the associated value",
samples.e0.getValue(), put(presentKeyNullValueEntry));
expectReplacement(presentKeyNullValueEntry);
}
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceWithNullValueUnsupported() {
try {
put(presentKeyNullValueEntry);
fail("put(present, null) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null after unsupported put(present, null)");
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceNullValueWithNullSupported() {
initMapWithNullValue();
assertNull("put(present, null) should return the associated value (null)",
getMap().put(getKeyForNullValue(), null));
expectContents(createArrayWithNullValue());
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testPut_replaceNullValueWithNonNullSupported() {
Entry<K, V> newEntry = entry(getKeyForNullValue(), samples.e3.getValue());
initMapWithNullValue();
assertNull("put(present, value) should return the associated value (null)",
put(newEntry));
Entry<K, V>[] expected = createArrayWithNullValue();
expected[getNullLocation()] = newEntry;
expectContents(expected);
}
@MapFeature.Require({SUPPORTS_PUT, ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
public void testPut_nullKeyAndValueSupported() {
assertNull("put(null, null) should return null", put(nullKeyValueEntry));
expectAdded(nullKeyValueEntry);
}
private V put(Map.Entry<K, V> entry) {
return getMap().put(entry.getKey(), entry.getValue());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/MapPutTester.java | Java | asf20 | 8,674 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.CollectionFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.CollectionFeature.RESTRICTS_ELEMENTS;
import static com.google.common.collect.testing.features.CollectionFeature.SUPPORTS_ADD;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static java.util.Collections.singletonList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractCollectionTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
/**
* A generic JUnit test which tests addAll operations on a collection. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.CollectionTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class CollectionAddAllTester<E> extends AbstractCollectionTester<E> {
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_supportedNothing() {
assertFalse("addAll(nothing) should return false",
collection.addAll(emptyCollection()));
expectUnchanged();
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddAll_unsupportedNothing() {
try {
assertFalse("addAll(nothing) should return false or throw",
collection.addAll(emptyCollection()));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_supportedNonePresent() {
assertTrue("addAll(nonePresent) should return true",
collection.addAll(createDisjointCollection()));
expectAdded(samples.e3, samples.e4);
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
public void testAddAll_unsupportedNonePresent() {
try {
collection.addAll(createDisjointCollection());
fail("addAll(nonePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3, samples.e4);
}
@CollectionFeature.Require(SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_supportedSomePresent() {
assertTrue("addAll(somePresent) should return true",
collection.addAll(MinimalCollection.of(samples.e3, samples.e0)));
assertTrue("should contain " + samples.e3, collection.contains(samples.e3));
assertTrue("should contain " + samples.e0, collection.contains(samples.e0));
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedSomePresent() {
try {
collection.addAll(MinimalCollection.of(samples.e3, samples.e0));
fail("addAll(somePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@CollectionFeature.Require({SUPPORTS_ADD,
FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddAllConcurrentWithIteration() {
try {
Iterator<E> iterator = collection.iterator();
assertTrue(collection.addAll(MinimalCollection.of(samples.e3, samples.e0)));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@CollectionFeature.Require(absent = SUPPORTS_ADD)
@CollectionSize.Require(absent = ZERO)
public void testAddAll_unsupportedAllPresent() {
try {
assertFalse("addAll(allPresent) should return false or throw",
collection.addAll(MinimalCollection.of(samples.e0)));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@CollectionFeature.Require(value = {SUPPORTS_ADD,
ALLOWS_NULL_VALUES}, absent = RESTRICTS_ELEMENTS)
public void testAddAll_nullSupported() {
List<E> containsNull = singletonList(null);
assertTrue("addAll(containsNull) should return true", collection
.addAll(containsNull));
/*
* We need (E) to force interpretation of null as the single element of a
* varargs array, not the array itself
*/
expectAdded((E) null);
}
@CollectionFeature.Require(value = SUPPORTS_ADD,
absent = ALLOWS_NULL_VALUES)
public void testAddAll_nullUnsupported() {
List<E> containsNull = singletonList(null);
try {
collection.addAll(containsNull);
fail("addAll(containsNull) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullMissingWhenNullUnsupported(
"Should not contain null after unsupported addAll(containsNull)");
}
@CollectionFeature.Require(SUPPORTS_ADD)
public void testAddAll_nullCollectionReference() {
try {
collection.addAll(null);
fail("addAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/CollectionAddAllTester.java | Java | asf20 | 6,027 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION;
import static com.google.common.collect.testing.features.MapFeature.SUPPORTS_PUT;
import static java.util.Collections.singletonList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests {@code putAll} operations on a map. Can't be
* invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@SuppressWarnings("unchecked") // too many "unchecked generic array creations"
@GwtCompatible(emulated = true)
public class MapPutAllTester<K, V> extends AbstractMapTester<K, V> {
private List<Entry<K, V>> containsNullKey;
private List<Entry<K, V>> containsNullValue;
@Override public void setUp() throws Exception {
super.setUp();
containsNullKey = singletonList(entry(null, samples.e3.getValue()));
containsNullValue = singletonList(entry(samples.e3.getKey(), null));
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll_supportedNothing() {
getMap().putAll(emptyMap());
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPutAll_unsupportedNothing() {
try {
getMap().putAll(emptyMap());
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll_supportedNonePresent() {
putAll(createDisjointCollection());
expectAdded(samples.e3, samples.e4);
}
@MapFeature.Require(absent = SUPPORTS_PUT)
public void testPutAll_unsupportedNonePresent() {
try {
putAll(createDisjointCollection());
fail("putAll(nonePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
expectMissing(samples.e3, samples.e4);
}
@MapFeature.Require(SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_supportedSomePresent() {
putAll(MinimalCollection.of(samples.e3, samples.e0));
expectAdded(samples.e3);
}
@MapFeature.Require({ FAILS_FAST_ON_CONCURRENT_MODIFICATION,
SUPPORTS_PUT })
@CollectionSize.Require(absent = ZERO)
public void testPutAllSomePresentConcurrentWithEntrySetIteration() {
try {
Iterator<Entry<K, V>> iterator = getMap().entrySet().iterator();
putAll(MinimalCollection.of(samples.e3, samples.e0));
iterator.next();
fail("Expected ConcurrentModificationException");
} catch (ConcurrentModificationException expected) {
// success
}
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_unsupportedSomePresent() {
try {
putAll(MinimalCollection.of(samples.e3, samples.e0));
fail("putAll(somePresent) should throw");
} catch (UnsupportedOperationException expected) {
}
expectUnchanged();
}
@MapFeature.Require(absent = SUPPORTS_PUT)
@CollectionSize.Require(absent = ZERO)
public void testPutAll_unsupportedAllPresent() {
try {
putAll(MinimalCollection.of(samples.e0));
} catch (UnsupportedOperationException tolerated) {
}
expectUnchanged();
}
@MapFeature.Require({SUPPORTS_PUT,
ALLOWS_NULL_KEYS})
public void testPutAll_nullKeySupported() {
putAll(containsNullKey);
expectAdded(containsNullKey.get(0));
}
@MapFeature.Require(value = SUPPORTS_PUT,
absent = ALLOWS_NULL_KEYS)
public void testPutAll_nullKeyUnsupported() {
try {
putAll(containsNullKey);
fail("putAll(containsNullKey) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullKeyMissingWhenNullKeysUnsupported(
"Should not contain null key after unsupported " +
"putAll(containsNullKey)");
}
@MapFeature.Require({SUPPORTS_PUT,
ALLOWS_NULL_VALUES})
public void testPutAll_nullValueSupported() {
putAll(containsNullValue);
expectAdded(containsNullValue.get(0));
}
@MapFeature.Require(value = SUPPORTS_PUT,
absent = ALLOWS_NULL_VALUES)
public void testPutAll_nullValueUnsupported() {
try {
putAll(containsNullValue);
fail("putAll(containsNullValue) should throw");
} catch (NullPointerException expected) {
}
expectUnchanged();
expectNullValueMissingWhenNullValuesUnsupported(
"Should not contain null value after unsupported " +
"putAll(containsNullValue)");
}
@MapFeature.Require(SUPPORTS_PUT)
public void testPutAll_nullCollectionReference() {
try {
getMap().putAll(null);
fail("putAll(null) should throw NullPointerException");
} catch (NullPointerException expected) {
}
}
private Map<K, V> emptyMap() {
return Collections.emptyMap();
}
private void putAll(Iterable<Entry<K, V>> entries) {
Map<K, V> map = new LinkedHashMap<K, V>();
for (Entry<K, V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
getMap().putAll(map);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/MapPutAllTester.java | Java | asf20 | 6,445 |
/*
* Copyright (C) 2007 The Guava 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.common.collect.testing.testers;
import static com.google.common.collect.testing.features.CollectionSize.ONE;
import static com.google.common.collect.testing.features.CollectionSize.ZERO;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_KEYS;
import static com.google.common.collect.testing.features.MapFeature.ALLOWS_NULL_VALUES;
import static com.google.common.collect.testing.features.MapFeature.REJECTS_DUPLICATES_AT_CREATION;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.testing.AbstractMapTester;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
/**
* A generic JUnit test which tests creation (typically through a constructor or
* static factory method) of a map. Can't be invoked directly; please see
* {@link com.google.common.collect.testing.MapTestSuiteBuilder}.
*
* @author Chris Povirk
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class MapCreationTester<K, V> extends AbstractMapTester<K, V> {
@MapFeature.Require(ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeySupported() {
initMapWithNullKey();
expectContents(createArrayWithNullKey());
}
@MapFeature.Require(absent = ALLOWS_NULL_KEYS)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyUnsupported() {
try {
initMapWithNullKey();
fail("Creating a map containing a null key should fail");
} catch (NullPointerException expected) {
}
}
@MapFeature.Require(ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueSupported() {
initMapWithNullValue();
expectContents(createArrayWithNullValue());
}
@MapFeature.Require(absent = ALLOWS_NULL_VALUES)
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullValueUnsupported() {
try {
initMapWithNullValue();
fail("Creating a map containing a null value should fail");
} catch (NullPointerException expected) {
}
}
@MapFeature.Require({ALLOWS_NULL_KEYS, ALLOWS_NULL_VALUES})
@CollectionSize.Require(absent = ZERO)
public void testCreateWithNullKeyAndValueSupported() {
Entry<K, V>[] entries = createSamplesArray();
entries[getNullLocation()] = entry(null, null);
resetMap(entries);
expectContents(entries);
}
@MapFeature.Require(value = ALLOWS_NULL_KEYS,
absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNullKeys());
}
@MapFeature.Require(absent = REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesNotRejected() {
expectFirstRemoved(getEntriesMultipleNonNullKeys());
}
@MapFeature.Require({ALLOWS_NULL_KEYS, REJECTS_DUPLICATES_AT_CREATION})
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNullKeys();
try {
resetMap(entries);
fail("Should reject duplicate null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
@MapFeature.Require(REJECTS_DUPLICATES_AT_CREATION)
@CollectionSize.Require(absent = {ZERO, ONE})
public void testCreateWithDuplicates_nonNullDuplicatesRejected() {
Entry<K, V>[] entries = getEntriesMultipleNonNullKeys();
try {
resetMap(entries);
fail("Should reject duplicate non-null elements at creation");
} catch (IllegalArgumentException expected) {
}
}
private Entry<K, V>[] getEntriesMultipleNullKeys() {
Entry<K, V>[] entries = createArrayWithNullKey();
entries[0] = entry(null, entries[0].getValue());
return entries;
}
private Entry<K, V>[] getEntriesMultipleNonNullKeys() {
Entry<K, V>[] entries = createSamplesArray();
entries[0] = entry(samples.e1.getKey(), samples.e0.getValue());
return entries;
}
private void expectFirstRemoved(Entry<K, V>[] entries) {
resetMap(entries);
List<Entry<K, V>> expectedWithDuplicateRemoved =
Arrays.asList(entries).subList(1, getNumElements());
expectContents(expectedWithDuplicateRemoved);
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/testers/MapCreationTester.java | Java | asf20 | 5,101 |
/*
* Copyright (C) 2008 The Guava 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.common.collect.testing;
/**
* Minimal GWT emulation of {@code com.google.common.collect.testing.Platform}.
*
* <p><strong>This .java file should never be consumed by javac.</strong>
*
* @author Hayward Chan
*/
final class Platform {
static boolean checkIsInstance(Class<?> clazz, Object obj) {
/*
* In GWT, we can't tell whether obj is an instance of clazz because GWT
* doesn't support reflections. For testing purposes, we give up this
* particular assertion (so that we can keep the rest).
*/
return true;
}
// Class.cast is not supported in GWT.
static void checkCast(Class<?> clazz, Object obj) {
}
static <T> T[] clone(T[] array) {
return GwtPlatform.clone(array);
}
// TODO: Consolidate different copies in one single place.
static String format(String template, Object... args) {
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append("]");
}
return builder.toString();
}
static String classGetSimpleName(Class<?> clazz) {
throw new UnsupportedOperationException("Shouldn't be called in GWT.");
}
private Platform() {}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/testing/super/com/google/common/collect/testing/Platform.java | Java | asf20 | 2,547 |
/*
* Copyright (C) 2007 The Guava 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.common.collect;
import static com.google.common.collect.testing.IteratorFeature.UNMODIFIABLE;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.collect.testing.IteratorTester;
import junit.framework.TestCase;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
/**
* Unit test for {@code Lists}.
*
* @author Kevin Bourrillion
* @author Mike Bostock
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class ListsTest extends TestCase {
private static final Collection<Integer> SOME_COLLECTION
= asList(0, 1, 1);
private static final Iterable<Integer> SOME_ITERABLE = new SomeIterable();
private static final class RemoveFirstFunction
implements Function<String, String>, Serializable {
@Override
public String apply(String from) {
return (from.length() == 0) ? from : from.substring(1);
}
}
private static class SomeIterable implements Iterable<Integer>, Serializable {
@Override
public Iterator<Integer> iterator() {
return SOME_COLLECTION.iterator();
}
private static final long serialVersionUID = 0;
}
private static final List<Integer> SOME_LIST
= Lists.newArrayList(1, 2, 3, 4);
private static final List<Integer> SOME_SEQUENTIAL_LIST
= Lists.newLinkedList(asList(1, 2, 3, 4));
private static final List<String> SOME_STRING_LIST
= asList("1", "2", "3", "4");
private static final Function<Number, String> SOME_FUNCTION
= new SomeFunction();
private static class SomeFunction
implements Function<Number, String>, Serializable {
@Override
public String apply(Number n) {
return String.valueOf(n);
}
private static final long serialVersionUID = 0;
}
public void testCharactersOfIsView() {
StringBuilder builder = new StringBuilder("abc");
List<Character> chars = Lists.charactersOf(builder);
assertEquals(asList('a', 'b', 'c'), chars);
builder.append("def");
assertEquals(
asList('a', 'b', 'c', 'd', 'e', 'f'), chars);
builder.deleteCharAt(5);
assertEquals(
asList('a', 'b', 'c', 'd', 'e'), chars);
}
public void testNewArrayListEmpty() {
ArrayList<Integer> list = Lists.newArrayList();
assertEquals(Collections.emptyList(), list);
}
public void testNewArrayListWithCapacity() {
ArrayList<Integer> list = Lists.newArrayListWithCapacity(0);
assertEquals(Collections.emptyList(), list);
ArrayList<Integer> bigger = Lists.newArrayListWithCapacity(256);
assertEquals(Collections.emptyList(), bigger);
}
public void testNewArrayListWithCapacity_negative() {
try {
Lists.newArrayListWithCapacity(-1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testNewArrayListWithExpectedSize() {
ArrayList<Integer> list = Lists.newArrayListWithExpectedSize(0);
assertEquals(Collections.emptyList(), list);
ArrayList<Integer> bigger = Lists.newArrayListWithExpectedSize(256);
assertEquals(Collections.emptyList(), bigger);
}
public void testNewArrayListWithExpectedSize_negative() {
try {
Lists.newArrayListWithExpectedSize(-1);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testNewArrayListVarArgs() {
ArrayList<Integer> list = Lists.newArrayList(0, 1, 1);
assertEquals(SOME_COLLECTION, list);
}
public void testComputeArrayListCapacity() {
assertEquals(5, Lists.computeArrayListCapacity(0));
assertEquals(13, Lists.computeArrayListCapacity(8));
assertEquals(89, Lists.computeArrayListCapacity(77));
assertEquals(22000005, Lists.computeArrayListCapacity(20000000));
assertEquals(Integer.MAX_VALUE,
Lists.computeArrayListCapacity(Integer.MAX_VALUE - 1000));
}
public void testNewArrayListFromCollection() {
ArrayList<Integer> list = Lists.newArrayList(SOME_COLLECTION);
assertEquals(SOME_COLLECTION, list);
}
public void testNewArrayListFromIterable() {
ArrayList<Integer> list = Lists.newArrayList(SOME_ITERABLE);
assertEquals(SOME_COLLECTION, list);
}
public void testNewArrayListFromIterator() {
ArrayList<Integer> list = Lists.newArrayList(SOME_COLLECTION.iterator());
assertEquals(SOME_COLLECTION, list);
}
public void testNewLinkedListEmpty() {
LinkedList<Integer> list = Lists.newLinkedList();
assertEquals(Collections.emptyList(), list);
}
public void testNewLinkedListFromCollection() {
LinkedList<Integer> list = Lists.newLinkedList(SOME_COLLECTION);
assertEquals(SOME_COLLECTION, list);
}
public void testNewLinkedListFromIterable() {
LinkedList<Integer> list = Lists.newLinkedList(SOME_ITERABLE);
assertEquals(SOME_COLLECTION, list);
}
/**
* This is just here to illustrate how {@code Arrays#asList} differs from
* {@code Lists#newArrayList}.
*/
public void testArraysAsList() {
List<String> ourWay = Lists.newArrayList("foo", "bar", "baz");
List<String> otherWay = asList("foo", "bar", "baz");
// They're logically equal
assertEquals(ourWay, otherWay);
// The result of Arrays.asList() is mutable
otherWay.set(0, "FOO");
assertEquals("FOO", otherWay.get(0));
// But it can't grow
try {
otherWay.add("nope");
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
// And it can't shrink
try {
otherWay.remove(2);
fail("no exception thrown");
} catch (UnsupportedOperationException expected) {
}
}
private void checkFooBarBazList(List<String> list) {
ASSERT.that(list).has().exactly("foo", "bar", "baz").inOrder();
assertEquals(3, list.size());
assertIndexIsOutOfBounds(list, -1);
assertEquals("foo", list.get(0));
assertEquals("bar", list.get(1));
assertEquals("baz", list.get(2));
assertIndexIsOutOfBounds(list, 3);
}
public void testAsList1Small() {
List<String> list = Lists.asList("foo", new String[0]);
ASSERT.that(list).has().item("foo");
assertEquals(1, list.size());
assertIndexIsOutOfBounds(list, -1);
assertEquals("foo", list.get(0));
assertIndexIsOutOfBounds(list, 1);
assertTrue(list instanceof RandomAccess);
new IteratorTester<String>(3, UNMODIFIABLE, singletonList("foo"),
IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override protected Iterator<String> newTargetIterator() {
return Lists.asList("foo", new String[0]).iterator();
}
}.test();
}
public void testAsList2() {
List<String> list = Lists.asList("foo", "bar", new String[] { "baz" });
checkFooBarBazList(list);
assertTrue(list instanceof RandomAccess);
new IteratorTester<String>(5, UNMODIFIABLE, asList("foo", "bar",
"baz"), IteratorTester.KnownOrder.KNOWN_ORDER) {
@Override protected Iterator<String> newTargetIterator() {
return Lists.asList("foo", "bar", new String[] {"baz"}).iterator();
}
}.test();
}
private static void assertIndexIsOutOfBounds(List<String> list, int index) {
try {
list.get(index);
fail();
} catch (IndexOutOfBoundsException expected) {
}
}
public void testReverseViewRandomAccess() {
List<Integer> fromList = Lists.newArrayList(SOME_LIST);
List<Integer> toList = Lists.reverse(fromList);
assertReverseView(fromList, toList);
}
public void testReverseViewSequential() {
List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST);
List<Integer> toList = Lists.reverse(fromList);
assertReverseView(fromList, toList);
}
private static void assertReverseView(List<Integer> fromList,
List<Integer> toList) {
/* fromList modifications reflected in toList */
fromList.set(0, 5);
assertEquals(asList(4, 3, 2, 5), toList);
fromList.add(6);
assertEquals(asList(6, 4, 3, 2, 5), toList);
fromList.add(2, 9);
assertEquals(asList(6, 4, 3, 9, 2, 5), toList);
fromList.remove(Integer.valueOf(2));
assertEquals(asList(6, 4, 3, 9, 5), toList);
fromList.remove(3);
assertEquals(asList(6, 3, 9, 5), toList);
/* toList modifications reflected in fromList */
toList.remove(0);
assertEquals(asList(5, 9, 3), fromList);
toList.add(7);
assertEquals(asList(7, 5, 9, 3), fromList);
toList.add(5);
assertEquals(asList(5, 7, 5, 9, 3), fromList);
toList.remove(Integer.valueOf(5));
assertEquals(asList(5, 7, 9, 3), fromList);
toList.set(1, 8);
assertEquals(asList(5, 7, 8, 3), fromList);
toList.clear();
assertEquals(Collections.emptyList(), fromList);
}
private static <E> List<E> list(E... elements) {
return ImmutableList.copyOf(elements);
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProduct_binary1x1() {
ASSERT.that(Lists.cartesianProduct(list(1), list(2))).has().item(list(1, 2));
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProduct_binary1x2() {
ASSERT.that(Lists.cartesianProduct(list(1), list(2, 3)))
.has().exactly(list(1, 2), list(1, 3)).inOrder();
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProduct_binary2x2() {
ASSERT.that(Lists.cartesianProduct(list(1, 2), list(3, 4)))
.has().exactly(list(1, 3), list(1, 4), list(2, 3), list(2, 4)).inOrder();
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProduct_2x2x2() {
ASSERT.that(Lists.cartesianProduct(list(0, 1), list(0, 1), list(0, 1))).has().exactly(
list(0, 0, 0), list(0, 0, 1), list(0, 1, 0), list(0, 1, 1),
list(1, 0, 0), list(1, 0, 1), list(1, 1, 0), list(1, 1, 1)).inOrder();
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProduct_contains() {
List<List<Integer>> actual = Lists.cartesianProduct(list(1, 2), list(3, 4));
assertTrue(actual.contains(list(1, 3)));
assertTrue(actual.contains(list(1, 4)));
assertTrue(actual.contains(list(2, 3)));
assertTrue(actual.contains(list(2, 4)));
assertFalse(actual.contains(list(3, 1)));
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProduct_unrelatedTypes() {
List<Integer> x = list(1, 2);
List<String> y = list("3", "4");
List<Object> exp1 = list((Object) 1, "3");
List<Object> exp2 = list((Object) 1, "4");
List<Object> exp3 = list((Object) 2, "3");
List<Object> exp4 = list((Object) 2, "4");
ASSERT.that(Lists.<Object>cartesianProduct(x, y))
.has().exactly(exp1, exp2, exp3, exp4).inOrder();
}
@SuppressWarnings("unchecked") // varargs!
public void testCartesianProductTooBig() {
List<String> list = Collections.nCopies(10000, "foo");
try {
Lists.cartesianProduct(list, list, list, list, list);
fail("Expected IAE");
} catch (IllegalArgumentException expected) {}
}
public void testTransformHashCodeRandomAccess() {
List<String> list = Lists.transform(SOME_LIST, SOME_FUNCTION);
assertEquals(SOME_STRING_LIST.hashCode(), list.hashCode());
}
public void testTransformHashCodeSequential() {
List<String> list = Lists.transform(SOME_SEQUENTIAL_LIST, SOME_FUNCTION);
assertEquals(SOME_STRING_LIST.hashCode(), list.hashCode());
}
public void testTransformModifiableRandomAccess() {
List<Integer> fromList = Lists.newArrayList(SOME_LIST);
List<String> list = Lists.transform(fromList, SOME_FUNCTION);
assertTransformModifiable(list);
}
public void testTransformModifiableSequential() {
List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST);
List<String> list = Lists.transform(fromList, SOME_FUNCTION);
assertTransformModifiable(list);
}
private static void assertTransformModifiable(List<String> list) {
try {
list.add("5");
fail("transformed list is addable");
} catch (UnsupportedOperationException expected) {}
list.remove(0);
assertEquals(asList("2", "3", "4"), list);
list.remove("3");
assertEquals(asList("2", "4"), list);
try {
list.set(0, "5");
fail("transformed list is setable");
} catch (UnsupportedOperationException expected) {}
list.clear();
assertEquals(Collections.emptyList(), list);
}
public void testTransformViewRandomAccess() {
List<Integer> fromList = Lists.newArrayList(SOME_LIST);
List<String> toList = Lists.transform(fromList, SOME_FUNCTION);
assertTransformView(fromList, toList);
}
public void testTransformViewSequential() {
List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST);
List<String> toList = Lists.transform(fromList, SOME_FUNCTION);
assertTransformView(fromList, toList);
}
private static void assertTransformView(List<Integer> fromList,
List<String> toList) {
/* fromList modifications reflected in toList */
fromList.set(0, 5);
assertEquals(asList("5", "2", "3", "4"), toList);
fromList.add(6);
assertEquals(asList("5", "2", "3", "4", "6"), toList);
fromList.remove(Integer.valueOf(2));
assertEquals(asList("5", "3", "4", "6"), toList);
fromList.remove(2);
assertEquals(asList("5", "3", "6"), toList);
/* toList modifications reflected in fromList */
toList.remove(2);
assertEquals(asList(5, 3), fromList);
toList.remove("5");
assertEquals(asList(3), fromList);
toList.clear();
assertEquals(Collections.emptyList(), fromList);
}
public void testTransformRandomAccess() {
List<String> list = Lists.transform(SOME_LIST, SOME_FUNCTION);
assertTrue(list instanceof RandomAccess);
}
public void testTransformSequential() {
List<String> list = Lists.transform(SOME_SEQUENTIAL_LIST, SOME_FUNCTION);
assertFalse(list instanceof RandomAccess);
}
public void testTransformListIteratorRandomAccess() {
List<Integer> fromList = Lists.newArrayList(SOME_LIST);
List<String> list = Lists.transform(fromList, SOME_FUNCTION);
assertTransformListIterator(list);
}
public void testTransformListIteratorSequential() {
List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST);
List<String> list = Lists.transform(fromList, SOME_FUNCTION);
assertTransformListIterator(list);
}
public void testTransformPreservesIOOBEsThrownByFunction() {
try {
Lists.transform(ImmutableList.of("foo", "bar"), new Function<String, String>() {
@Override
public String apply(String input) {
throw new IndexOutOfBoundsException();
}
}).toArray();
fail();
} catch (IndexOutOfBoundsException expected) {
// success
}
}
private static void assertTransformListIterator(List<String> list) {
ListIterator<String> iterator = list.listIterator(1);
assertEquals(1, iterator.nextIndex());
assertEquals("2", iterator.next());
assertEquals("3", iterator.next());
assertEquals("4", iterator.next());
assertEquals(4, iterator.nextIndex());
try {
iterator.next();
fail("did not detect end of list");
} catch (NoSuchElementException expected) {}
assertEquals(3, iterator.previousIndex());
assertEquals("4", iterator.previous());
assertEquals("3", iterator.previous());
assertEquals("2", iterator.previous());
assertTrue(iterator.hasPrevious());
assertEquals("1", iterator.previous());
assertFalse(iterator.hasPrevious());
assertEquals(-1, iterator.previousIndex());
try {
iterator.previous();
fail("did not detect beginning of list");
} catch (NoSuchElementException expected) {}
iterator.remove();
assertEquals(asList("2", "3", "4"), list);
assertFalse(list.isEmpty());
// An UnsupportedOperationException or IllegalStateException may occur.
try {
iterator.add("1");
fail("transformed list iterator is addable");
} catch (UnsupportedOperationException expected) {
} catch (IllegalStateException expected) {}
try {
iterator.set("1");
fail("transformed list iterator is settable");
} catch (UnsupportedOperationException expected) {
} catch (IllegalStateException expected) {}
}
public void testTransformIteratorRandomAccess() {
List<Integer> fromList = Lists.newArrayList(SOME_LIST);
List<String> list = Lists.transform(fromList, SOME_FUNCTION);
assertTransformIterator(list);
}
public void testTransformIteratorSequential() {
List<Integer> fromList = Lists.newLinkedList(SOME_SEQUENTIAL_LIST);
List<String> list = Lists.transform(fromList, SOME_FUNCTION);
assertTransformIterator(list);
}
/**
* We use this class to avoid the need to suppress generics checks with
* easy mock.
*/
private interface IntegerList extends List<Integer> {}
private static void assertTransformIterator(List<String> list) {
Iterator<String> iterator = list.iterator();
assertTrue(iterator.hasNext());
assertEquals("1", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("2", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("3", iterator.next());
assertTrue(iterator.hasNext());
assertEquals("4", iterator.next());
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("did not detect end of list");
} catch (NoSuchElementException expected) {}
iterator.remove();
assertEquals(asList("1", "2", "3"), list);
assertFalse(iterator.hasNext());
}
public void testPartition_badSize() {
List<Integer> source = Collections.singletonList(1);
try {
Lists.partition(source, 0);
fail();
} catch (IllegalArgumentException expected) {
}
}
public void testPartition_empty() {
List<Integer> source = Collections.emptyList();
List<List<Integer>> partitions = Lists.partition(source, 1);
assertTrue(partitions.isEmpty());
assertEquals(0, partitions.size());
}
public void testPartition_1_1() {
List<Integer> source = Collections.singletonList(1);
List<List<Integer>> partitions = Lists.partition(source, 1);
assertEquals(1, partitions.size());
assertEquals(Collections.singletonList(1), partitions.get(0));
}
public void testPartition_1_2() {
List<Integer> source = Collections.singletonList(1);
List<List<Integer>> partitions = Lists.partition(source, 2);
assertEquals(1, partitions.size());
assertEquals(Collections.singletonList(1), partitions.get(0));
}
public void testPartition_2_1() {
List<Integer> source = asList(1, 2);
List<List<Integer>> partitions = Lists.partition(source, 1);
assertEquals(2, partitions.size());
assertEquals(Collections.singletonList(1), partitions.get(0));
assertEquals(Collections.singletonList(2), partitions.get(1));
}
public void testPartition_3_2() {
List<Integer> source = asList(1, 2, 3);
List<List<Integer>> partitions = Lists.partition(source, 2);
assertEquals(2, partitions.size());
assertEquals(asList(1, 2), partitions.get(0));
assertEquals(asList(3), partitions.get(1));
}
public void testPartitionRandomAccessFalse() {
List<Integer> source = Lists.newLinkedList(asList(1, 2, 3));
List<List<Integer>> partitions = Lists.partition(source, 2);
assertFalse(partitions instanceof RandomAccess);
assertFalse(partitions.get(0) instanceof RandomAccess);
assertFalse(partitions.get(1) instanceof RandomAccess);
}
// TODO: use the ListTestSuiteBuilder
public void testPartition_view() {
List<Integer> list = asList(1, 2, 3);
List<List<Integer>> partitions = Lists.partition(list, 3);
// Changes before the partition is retrieved are reflected
list.set(0, 3);
Iterator<List<Integer>> iterator = partitions.iterator();
// Changes before the partition is retrieved are reflected
list.set(1, 4);
List<Integer> first = iterator.next();
// Changes after are too (unlike Iterables.partition)
list.set(2, 5);
assertEquals(asList(3, 4, 5), first);
// Changes to a sublist also write through to the original list
first.set(1, 6);
assertEquals(asList(3, 6, 5), list);
}
public void testPartitionSize_1() {
List<Integer> list = asList(1, 2, 3);
assertEquals(1, Lists.partition(list, Integer.MAX_VALUE).size());
assertEquals(1, Lists.partition(list, Integer.MAX_VALUE - 1).size());
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ListsTest.java | Java | asf20 | 21,376 |
/*
* Copyright (C) 2008 The Guava 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.common.collect;
import static org.truth0.Truth.ASSERT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableBiMap.Builder;
import com.google.common.collect.testing.MapInterfaceTest;
import junit.framework.TestCase;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Tests for {@link ImmutableBiMap}.
*
* @author Jared Levy
*/
@GwtCompatible(emulated = true)
public class ImmutableBiMapTest extends TestCase {
// TODO: Reduce duplication of ImmutableMapTest code
public static abstract class AbstractMapTests<K, V>
extends MapInterfaceTest<K, V> {
public AbstractMapTests() {
super(false, false, false, false, false);
}
@Override protected Map<K, V> makeEmptyMap() {
throw new UnsupportedOperationException();
}
private static final Joiner joiner = Joiner.on(", ");
@Override protected void assertMoreInvariants(Map<K, V> map) {
BiMap<K, V> bimap = (BiMap<K, V>) map;
for (Entry<K, V> entry : map.entrySet()) {
assertEquals(entry.getKey() + "=" + entry.getValue(),
entry.toString());
assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue()));
}
assertEquals("{" + joiner.join(map.entrySet()) + "}",
map.toString());
assertEquals("[" + joiner.join(map.entrySet()) + "]",
map.entrySet().toString());
assertEquals("[" + joiner.join(map.keySet()) + "]",
map.keySet().toString());
assertEquals("[" + joiner.join(map.values()) + "]",
map.values().toString());
assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
}
}
public static class MapTests extends AbstractMapTests<String, Integer> {
@Override protected Map<String, Integer> makeEmptyMap() {
return ImmutableBiMap.of();
}
@Override protected Map<String, Integer> makePopulatedMap() {
return ImmutableBiMap.of("one", 1, "two", 2, "three", 3);
}
@Override protected String getKeyNotInPopulatedMap() {
return "minus one";
}
@Override protected Integer getValueNotInPopulatedMap() {
return -1;
}
}
public static class InverseMapTests
extends AbstractMapTests<String, Integer> {
@Override protected Map<String, Integer> makeEmptyMap() {
return ImmutableBiMap.of();
}
@Override protected Map<String, Integer> makePopulatedMap() {
return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse();
}
@Override protected String getKeyNotInPopulatedMap() {
return "minus one";
}
@Override protected Integer getValueNotInPopulatedMap() {
return -1;
}
}
public static class CreationTests extends TestCase {
public void testEmptyBuilder() {
ImmutableBiMap<String, Integer> map
= new Builder<String, Integer>().build();
assertEquals(Collections.<String, Integer>emptyMap(), map);
assertEquals(Collections.<Integer, String>emptyMap(), map.inverse());
assertSame(ImmutableBiMap.of(), map);
}
public void testSingletonBuilder() {
ImmutableBiMap<String, Integer> map = new Builder<String, Integer>()
.put("one", 1)
.build();
assertMapEquals(map, "one", 1);
assertMapEquals(map.inverse(), 1, "one");
}
public void testBuilder() {
ImmutableBiMap<String, Integer> map
= ImmutableBiMap.<String, Integer>builder()
.put("one", 1)
.put("two", 2)
.put("three", 3)
.put("four", 4)
.put("five", 5)
.build();
assertMapEquals(map,
"one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
assertMapEquals(map.inverse(),
1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
}
public void testBuilderPutAllWithEmptyMap() {
ImmutableBiMap<String, Integer> map = new Builder<String, Integer>()
.putAll(Collections.<String, Integer>emptyMap())
.build();
assertEquals(Collections.<String, Integer>emptyMap(), map);
}
public void testBuilderPutAll() {
Map<String, Integer> toPut = new LinkedHashMap<String, Integer>();
toPut.put("one", 1);
toPut.put("two", 2);
toPut.put("three", 3);
Map<String, Integer> moreToPut = new LinkedHashMap<String, Integer>();
moreToPut.put("four", 4);
moreToPut.put("five", 5);
ImmutableBiMap<String, Integer> map = new Builder<String, Integer>()
.putAll(toPut)
.putAll(moreToPut)
.build();
assertMapEquals(map,
"one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
assertMapEquals(map.inverse(),
1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
}
public void testBuilderReuse() {
Builder<String, Integer> builder = new Builder<String, Integer>();
ImmutableBiMap<String, Integer> mapOne = builder
.put("one", 1)
.put("two", 2)
.build();
ImmutableBiMap<String, Integer> mapTwo = builder
.put("three", 3)
.put("four", 4)
.build();
assertMapEquals(mapOne, "one", 1, "two", 2);
assertMapEquals(mapOne.inverse(), 1, "one", 2, "two");
assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
assertMapEquals(mapTwo.inverse(),
1, "one", 2, "two", 3, "three", 4, "four");
}
public void testBuilderPutNullKey() {
Builder<String, Integer> builder = new Builder<String, Integer>();
try {
builder.put(null, 1);
fail();
} catch (NullPointerException expected) {
}
}
public void testBuilderPutNullValue() {
Builder<String, Integer> builder = new Builder<String, Integer>();
try {
builder.put("one", null);
fail();
} catch (NullPointerException expected) {
}
}
public void testBuilderPutNullKeyViaPutAll() {
Builder<String, Integer> builder = new Builder<String, Integer>();
try {
builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
fail();
} catch (NullPointerException expected) {
}
}
public void testBuilderPutNullValueViaPutAll() {
Builder<String, Integer> builder = new Builder<String, Integer>();
try {
builder.putAll(Collections.<String, Integer>singletonMap("one", null));
fail();
} catch (NullPointerException expected) {
}
}
public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
Builder<String, Integer> builder = new Builder<String, Integer>()
.put("one", 1)
.put("one", 1); // throwing on this line would be even better
try {
builder.build();
fail();
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage().contains("one"));
}
}
public void testOf() {
assertMapEquals(
ImmutableBiMap.of("one", 1),
"one", 1);
assertMapEquals(
ImmutableBiMap.of("one", 1).inverse(),
1, "one");
assertMapEquals(
ImmutableBiMap.of("one", 1, "two", 2),
"one", 1, "two", 2);
assertMapEquals(
ImmutableBiMap.of("one", 1, "two", 2).inverse(),
1, "one", 2, "two");
assertMapEquals(
ImmutableBiMap.of("one", 1, "two", 2, "three", 3),
"one", 1, "two", 2, "three", 3);
assertMapEquals(
ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(),
1, "one", 2, "two", 3, "three");
assertMapEquals(
ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4),
"one", 1, "two", 2, "three", 3, "four", 4);
assertMapEquals(
ImmutableBiMap.of(
"one", 1, "two", 2, "three", 3, "four", 4).inverse(),
1, "one", 2, "two", 3, "three", 4, "four");
assertMapEquals(
ImmutableBiMap.of(
"one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
"one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
assertMapEquals(
ImmutableBiMap.of(
"one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(),
1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
}
public void testOfNullKey() {
try {
ImmutableBiMap.of(null, 1);
fail();
} catch (NullPointerException expected) {
}
try {
ImmutableBiMap.of("one", 1, null, 2);
fail();
} catch (NullPointerException expected) {
}
}
public void testOfNullValue() {
try {
ImmutableBiMap.of("one", null);
fail();
} catch (NullPointerException expected) {
}
try {
ImmutableBiMap.of("one", 1, "two", null);
fail();
} catch (NullPointerException expected) {
}
}
public void testOfWithDuplicateKey() {
try {
ImmutableBiMap.of("one", 1, "one", 1);
fail();
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage().contains("one"));
}
}
public void testCopyOfEmptyMap() {
ImmutableBiMap<String, Integer> copy
= ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
assertEquals(Collections.<String, Integer>emptyMap(), copy);
assertSame(copy, ImmutableBiMap.copyOf(copy));
assertSame(ImmutableBiMap.of(), copy);
}
public void testCopyOfSingletonMap() {
ImmutableBiMap<String, Integer> copy
= ImmutableBiMap.copyOf(Collections.singletonMap("one", 1));
assertMapEquals(copy, "one", 1);
assertSame(copy, ImmutableBiMap.copyOf(copy));
}
public void testCopyOf() {
Map<String, Integer> original = new LinkedHashMap<String, Integer>();
original.put("one", 1);
original.put("two", 2);
original.put("three", 3);
ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
assertSame(copy, ImmutableBiMap.copyOf(copy));
}
public void testEmpty() {
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
assertEquals(Collections.<String, Integer>emptyMap(), bimap);
assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse());
}
public void testFromHashMap() {
Map<String, Integer> hashMap = Maps.newLinkedHashMap();
hashMap.put("one", 1);
hashMap.put("two", 2);
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(
ImmutableMap.of("one", 1, "two", 2));
assertMapEquals(bimap, "one", 1, "two", 2);
assertMapEquals(bimap.inverse(), 1, "one", 2, "two");
}
public void testFromImmutableMap() {
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(
new ImmutableMap.Builder<String, Integer>()
.put("one", 1)
.put("two", 2)
.put("three", 3)
.put("four", 4)
.put("five", 5)
.build());
assertMapEquals(bimap,
"one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
assertMapEquals(bimap.inverse(),
1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
}
public void testDuplicateValues() {
ImmutableMap<String, Integer> map
= new ImmutableMap.Builder<String, Integer>()
.put("one", 1)
.put("two", 2)
.put("uno", 1)
.put("dos", 2)
.build();
try {
ImmutableBiMap.copyOf(map);
fail();
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage().contains("1"));
}
}
}
public static class BiMapSpecificTests extends TestCase {
@SuppressWarnings("deprecation")
public void testForcePut() {
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(
ImmutableMap.of("one", 1, "two", 2));
try {
bimap.forcePut("three", 3);
fail();
} catch (UnsupportedOperationException expected) {}
}
public void testKeySet() {
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(
ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
Set<String> keys = bimap.keySet();
assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys);
ASSERT.that(keys).has().exactly("one", "two", "three", "four").inOrder();
}
public void testValues() {
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(
ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
Set<Integer> values = bimap.values();
assertEquals(Sets.newHashSet(1, 2, 3, 4), values);
ASSERT.that(values).has().exactly(1, 2, 3, 4).inOrder();
}
public void testDoubleInverse() {
ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(
ImmutableMap.of("one", 1, "two", 2));
assertSame(bimap, bimap.inverse().inverse());
}
}
private static <K, V> void assertMapEquals(Map<K, V> map,
Object... alternatingKeysAndValues) {
int i = 0;
for (Entry<K, V> entry : map.entrySet()) {
assertEquals(alternatingKeysAndValues[i++], entry.getKey());
assertEquals(alternatingKeysAndValues[i++], entry.getValue());
}
}
}
| zzhhhhh-aw4rwer | guava-gwt/test-super/com/google/common/collect/super/com/google/common/collect/ImmutableBiMapTest.java | Java | asf20 | 14,195 |