() {
57 | public Boolean call(A1 a1, A2 a2) {
58 | return isFalseOrNull(Fn2.this.call(a1, a2));
59 | }
60 | };
61 | }
62 |
63 | public int arity() {
64 | return 2;
65 | }
66 | }
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/Parameters.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda;
2 |
3 | import java.util.Collection;
4 |
5 | import org.enumerable.lambda.annotation.LambdaParameter;
6 |
7 |
8 | /**
9 | * A set of default parameters to use in Lambda definitions.
10 | *
11 | * @see LambdaParameter
12 | */
13 | public class Parameters {
14 | @LambdaParameter
15 | public static int n;
16 | @LambdaParameter
17 | public static int m;
18 | @LambdaParameter
19 | public static int i;
20 | @LambdaParameter
21 | public static int idx;
22 | @LambdaParameter
23 | public static long k;
24 | @LambdaParameter
25 | public static long l;
26 | @LambdaParameter
27 | public static double d;
28 | @LambdaParameter
29 | public static double x;
30 | @LambdaParameter
31 | public static double y;
32 | @LambdaParameter
33 | public static char c;
34 | @LambdaParameter
35 | public static boolean b;
36 | @LambdaParameter
37 | public static String s;
38 | @LambdaParameter
39 | public static String t;
40 | @LambdaParameter
41 | public static Collection> col;
42 | @LambdaParameter
43 | public static Object obj;
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/annotation/LambdaLocal.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.annotation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * This annotation is used to mark fields added to a lambda holding captured
10 | * local variables.
11 | */
12 | @Retention(RetentionPolicy.RUNTIME)
13 | @Target({ ElementType.FIELD, ElementType.PARAMETER })
14 | public @interface LambdaLocal {
15 | boolean isReadOnly();
16 |
17 | String name();
18 |
19 | String parameterClass();
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/annotation/LambdaParameter.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.annotation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Target;
5 |
6 | /**
7 | * This annotation is used to mark static fields which can then be used in a
8 | * lambda to define parameters and access it's arguments.
9 | *
10 | * Example:
11 | *
12 | *
13 | * @LambdaParameter
14 | * public static Integer n;
15 | *
16 | * fn(n, n * n);
17 | *
18 | *
19 | * Here, the first reference to n
is treated as defining a
20 | * parameter for the lambda. The next two references refer to the first argument
21 | * of the lambda when called.
22 | *
23 | * All access to the actual field will be redirected, so once marked, the field
24 | * cannot be used as a normal field, and doing so will fail in undefined ways.
25 | */
26 | @Target(ElementType.FIELD)
27 | public @interface LambdaParameter {
28 | }
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/annotation/NewLambda.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.annotation;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Target;
5 |
6 | import org.enumerable.lambda.Fn0;
7 | import org.enumerable.lambda.exception.LambdaWeavingNotEnabledException;
8 |
9 |
10 | /**
11 | * This annotation is used to mark static methods that returns a {@link Fn0} or
12 | * one of it's subclasses so calls to it will be transformed at load time into
13 | * code that instantiates the new lambda as a {@link Fn0}.
14 | *
15 | * The last argument to the method is the actual block expression. The other
16 | * arguments have to be {@link LambdaParameter} marking the blocks signature.
17 | *
18 | * The return type of the block is the type of the block expression parameter.
19 | *
20 | *
21 | * This method can also be used to create anonymous subclasses implementing
22 | * other interfaces, but several restrictions apply. Example:
23 | *
24 | *
25 | * @NewLambda
26 | * public static Runnable runnable(Object none, Object block) {
27 | * throw new LambdaWeavingNotEnabledException();
28 | * }
29 | *
30 | * String hello = "";
31 | * Runnable runnable = runnable(hello = "hello");
32 | * runnable.run();
33 | *
34 | *
35 | * It also supports creation using generics, like this:
36 | *
37 | *
38 | * @NewLambda
39 | * public static <I> I delegate(Object o, Object block) {
40 | * throw new LambdaWeavingNotEnabledException();
41 | * }
42 | *
43 | * String hello = ""; Runnable runnable = delegate(hello = "hello");
44 | * runnable.run();
45 | *
46 | *
47 | * Methods marked with this annotation should throw
48 | * {@link LambdaWeavingNotEnabledException} when the code is run without
49 | * transformation.
50 | */
51 | @Target(ElementType.METHOD)
52 | public @interface NewLambda {
53 | }
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/enumerable/collection/EIterable.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.enumerable.collection;
2 |
3 | import java.util.Iterator;
4 |
5 | import org.enumerable.lambda.Fn1;
6 | import org.enumerable.lambda.Fn2;
7 |
8 |
9 | /**
10 | * A decorator for {@link Iterable} which includes the {@link EnumerableModule}
11 | * by extension.
12 | */
13 | public class EIterable extends EnumerableModule {
14 | protected final Iterable iterable;
15 |
16 | public EIterable(Iterable iterable) {
17 | this.iterable = iterable;
18 | }
19 |
20 | public EIterable each(Fn1 super E, R> block) {
21 | return (EIterable) super.each(block);
22 | }
23 |
24 | public EIterable eachWithIndex(Fn2 super E, Integer, R> block) {
25 | return (EIterable) super.eachWithIndex(block);
26 | }
27 |
28 | public EIterable reverseEach(Fn1 super E, R> block) {
29 | return (EIterable) super.reverseEach(block);
30 | }
31 |
32 | public boolean equals(Object obj) {
33 | if (obj instanceof EIterable>)
34 | return this.iterable.equals(((EIterable>) obj).iterable);
35 | if (obj instanceof Iterable>)
36 | return this.iterable.equals(obj);
37 | return false;
38 | }
39 |
40 | public int hashCode() {
41 | return iterable.hashCode();
42 | }
43 |
44 | public Iterator iterator() {
45 | return iterable.iterator();
46 | }
47 |
48 | public Iterable delegate() {
49 | return iterable;
50 | }
51 |
52 | public String toString() {
53 | return iterable.toString();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/enumerable/collection/ESet.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.enumerable.collection;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | import org.enumerable.lambda.Fn1;
7 | import org.enumerable.lambda.Fn2;
8 |
9 |
10 | /**
11 | * A decorator for {@link Set}, which includes the {@link EnumerableModule} via
12 | * {@link EIterable}.
13 | */
14 | public class ESet extends ECollection implements Set {
15 | public ESet() {
16 | this(new HashSet());
17 | }
18 |
19 | public ESet(Set set) {
20 | super(set);
21 | }
22 |
23 | public ESet each(Fn1 super E, R> block) {
24 | return (ESet) super.each(block);
25 | }
26 |
27 | public ESet eachWithIndex(Fn2 super E, Integer, R> block) {
28 | return (ESet) super.eachWithIndex(block);
29 | }
30 |
31 | public ESet reverseEach(Fn1 super E, R> block) {
32 | return (ESet) super.reverseEach(block);
33 | }
34 |
35 | public Set delegate() {
36 | return (Set) iterable;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/exception/LambdaWeavingNotEnabledException.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.exception;
2 |
3 | import org.enumerable.lambda.annotation.NewLambda;
4 | import org.enumerable.lambda.weaving.LambdaLoader;
5 |
6 | /**
7 | * Exception to be thrown by methods marked with {@link NewLambda} if
8 | * transformation hasn't taken place.
9 | */
10 | @SuppressWarnings("serial")
11 | public class LambdaWeavingNotEnabledException extends UnsupportedOperationException {
12 | public LambdaWeavingNotEnabledException() {
13 | super(LambdaLoader.getNotEnabledMessage());
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1BtoB.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1BtoB extends Fn1 {
7 | public abstract boolean call(boolean a1);
8 |
9 | public Boolean call(Boolean a1) {
10 | return call(a1.booleanValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1DtoB.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1DtoB extends Fn1 {
7 | public abstract boolean call(double a1);
8 |
9 | public Boolean call(Double a1) {
10 | return call(a1.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1DtoD.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1DtoD extends Fn1 {
7 | public abstract double call(double a1);
8 |
9 | public Double call(Double a1) {
10 | return call(a1.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1DtoI.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1DtoI extends Fn1 {
7 | public abstract int call(double a1);
8 |
9 | public Integer call(Double a1) {
10 | return call(a1.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1DtoL.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1DtoL extends Fn1 {
7 | public abstract long call(double a1);
8 |
9 | public Long call(Double a1) {
10 | return call(a1.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1DtoO.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1DtoO extends Fn1 {
7 | public abstract R call(double a1);
8 |
9 | public R call(Double a1) {
10 | return call(a1.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1ItoB.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1ItoB extends Fn1 {
7 | public abstract boolean call(int a1);
8 |
9 | public Boolean call(Integer a1) {
10 | return call(a1.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1ItoD.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1ItoD extends Fn1 {
7 | public abstract double call(int a1);
8 |
9 | public Double call(Integer a1) {
10 | return call(a1.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1ItoI.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1ItoI extends Fn1 {
7 | public abstract int call(int a1);
8 |
9 | public Integer call(Integer a1) {
10 | return call(a1.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1ItoL.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1ItoL extends Fn1 {
7 | public abstract long call(int a1);
8 |
9 | public Long call(Integer a1) {
10 | return call(a1.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1ItoO.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1ItoO extends Fn1 {
7 | public abstract R call(int a1);
8 |
9 | public R call(Integer a1) {
10 | return call(a1.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1LtoB.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1LtoB extends Fn1 {
7 | public abstract boolean call(long a1);
8 |
9 | public Boolean call(Long a1) {
10 | return call(a1.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1LtoD.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1LtoD extends Fn1 {
7 | public abstract double call(long a1);
8 |
9 | public Double call(Long a1) {
10 | return call(a1.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1LtoI.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1LtoI extends Fn1 {
7 | public abstract int call(long a1);
8 |
9 | public Integer call(Long a1) {
10 | return call(a1.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1LtoL.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1LtoL extends Fn1 {
7 | public abstract long call(long a1);
8 |
9 | public Long call(Long a1) {
10 | return call(a1.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn1LtoO.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn1;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn1LtoO extends Fn1 {
7 | public abstract R call(long a1);
8 |
9 | public R call(Long a1) {
10 | return call(a1.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2BBtoB.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2BBtoB extends Fn2 {
7 | public abstract boolean call(boolean a1, boolean a2);
8 |
9 | public Boolean call(Boolean a1, Boolean a2) {
10 | return call(a1.booleanValue(), a2.booleanValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2DDtoD.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2DDtoD extends Fn2 {
7 | public abstract double call(double a1, double a2);
8 |
9 | public Double call(Double a1, Double a2) {
10 | return call(a1.doubleValue(), a2.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2DDtoO.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2DDtoO extends Fn2 {
7 | public abstract R call(double a1, double a2);
8 |
9 | public R call(Double a1, Double a2) {
10 | return call(a1.doubleValue(), a2.doubleValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2IItoI.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2IItoI extends Fn2 {
7 | public abstract int call(int a1, int a2);
8 |
9 | public Integer call(Integer a1, Integer a2) {
10 | return call(a1.intValue(), a2.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2IItoO.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2IItoO extends Fn2 {
7 | public abstract R call(int a1, int a2);
8 |
9 | public R call(Integer a1, Integer a2) {
10 | return call(a1.intValue(), a2.intValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2LLtoL.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2LLtoL extends Fn2 {
7 | public abstract long call(long a1, long a2);
8 |
9 | public Long call(Long a1, Long a2) {
10 | return call(a1.longValue(), a2.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/primitives/Fn2LLtoO.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.primitives;
2 |
3 | import org.enumerable.lambda.Fn2;
4 |
5 | @SuppressWarnings("serial")
6 | public abstract class Fn2LLtoO extends Fn2 {
7 | public abstract R call(long a1, long a2);
8 |
9 | public R call(Long a1, Long a2) {
10 | return call(a1.longValue(), a2.longValue());
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/support/methodhandle/LambdaMethodHandle.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.methodhandle;
2 |
3 | import org.enumerable.lambda.Fn0;
4 |
5 | import java.lang.invoke.MethodHandle;
6 | import java.lang.invoke.MethodHandles;
7 | import java.lang.invoke.MethodType;
8 |
9 | import static org.enumerable.lambda.exception.UncheckedException.uncheck;
10 |
11 | /**
12 | * This class converts lambdas created by {@link org.enumerable.lambda.weaving.LambdaLoader} to {@link java.lang.invoke.MethodHandle}
13 | *
14 | * It lives under support instead of being an instance method as it requires Java 7.
15 | */
16 | public class LambdaMethodHandle {
17 | public static MethodHandle bind(Object fn) {
18 | try {
19 | return MethodHandles.lookup().unreflect(Fn0.getLambdaMethod(fn.getClass())).bindTo(fn);
20 | } catch (Exception e) {
21 | throw uncheck(e);
22 | }
23 | }
24 |
25 | public static MethodHandle bind(Fn0> fn) {
26 | try {
27 | return MethodHandles.lookup().bind(fn, "call", MethodType.genericMethodType(fn.arity()));
28 | } catch (Exception e) {
29 | throw uncheck(e);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/support/osgi/LambdaWeavingActivator.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.osgi;
2 |
3 | import org.enumerable.lambda.weaving.Version;
4 | import org.enumerable.lambda.weaving.LambdaLoader;
5 | import org.osgi.framework.BundleActivator;
6 | import org.osgi.framework.BundleContext;
7 | import org.osgi.framework.ServiceRegistration;
8 | import org.osgi.framework.hooks.weaving.WeavingHook;
9 | import org.osgi.framework.hooks.weaving.WovenClass;
10 | import org.osgi.framework.wiring.BundleWiring;
11 |
12 | import java.io.ByteArrayInputStream;
13 | import java.util.Hashtable;
14 |
15 | import static org.enumerable.lambda.weaving.Debug.debug;
16 |
17 | public class LambdaWeavingActivator implements BundleActivator, WeavingHook {
18 | private LambdaLoader loader;
19 | private ServiceRegistration weavingHook;
20 |
21 | public void start(BundleContext bundleContext) throws Exception {
22 | debug("[osgi] " + Version.getVersionString());
23 |
24 | loader = new LambdaLoader();
25 | weavingHook = bundleContext.registerService(WeavingHook.class, this, new Hashtable());
26 | }
27 |
28 | public void stop(BundleContext bundleContext) throws Exception {
29 | if (weavingHook != null) weavingHook.unregister();
30 | }
31 |
32 | public void weave(WovenClass wovenClass) {
33 | BundleWiring wiring = wovenClass.getBundleWiring();
34 | ByteArrayInputStream in = new ByteArrayInputStream(wovenClass.getBytes());
35 | byte[] newBytes = loader.transformClass(wiring.getClassLoader(), wovenClass.getClassName(), in);
36 | if (newBytes != null) wovenClass.setBytes(newBytes);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/weaving/Debug.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.weaving;
2 |
3 | import static java.lang.System.*;
4 |
5 | public class Debug {
6 | public static boolean debug = Boolean.valueOf(getProperty("lambda.weaving.debug"));
7 | public static boolean devDebug = Boolean.valueOf(getProperty("lambda.weaving.debug.dev"));
8 |
9 | static String debugIndentation = "";
10 |
11 | public static void debugIndent() {
12 | debugIndentation += " ";
13 | }
14 |
15 | public static void debugDedent() {
16 | debugIndentation = debugIndentation.substring(0, debugIndentation.length() - 1);
17 | }
18 |
19 | public static void debug(String msg) {
20 | if (debug)
21 | out.println(debugIndentation + msg);
22 | }
23 |
24 | public static void devDebug(String msg) {
25 | if (devDebug)
26 | out.println(debugIndentation + msg);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/weaving/Version.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.weaving;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.util.Properties;
6 |
7 | import static org.enumerable.lambda.exception.UncheckedException.uncheck;
8 |
9 | public class Version {
10 | public static Properties buildProperties = new Properties();
11 | static {
12 | ClassLoader loader = Version.class.getClassLoader();
13 | InputStream in = loader.getResourceAsStream(Version.class.getName().toLowerCase().replace('.', '/')
14 | + ".properties");
15 | try {
16 | if (in != null)
17 | buildProperties.load(in);
18 | } catch (IOException e) {
19 | throw uncheck(e);
20 | } finally {
21 | try {
22 | if (in != null)
23 | in.close();
24 | } catch (IOException silent) {
25 | }
26 | }
27 | }
28 |
29 | public static String getVersion() {
30 | return (String) buildProperties.get("enumerable.version");
31 | }
32 |
33 | public static String getBuildDate() {
34 | return buildProperties.getProperty("enumerable.build.date");
35 | }
36 |
37 | public static String getGitCommit() {
38 | return buildProperties.getProperty("enumerable.git.commit");
39 | }
40 |
41 | public static String getVersionString() {
42 | return "Enumerable.java version " + getVersion() + " (built on " + getBuildDate() + " from "
43 | + getGitCommit() + ")";
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/org/enumerable/lambda/weaving/lambda.weaving.properties:
--------------------------------------------------------------------------------
1 | lambda.weaving.annotation.newlambda=org.enumerable.lambda.annotation.NewLambda
2 | lambda.weaving.annotation.lambdaparameter=org.enumerable.lambda.annotation.LambdaParameter
3 | lambda.weaving.annotation.lambdalocal=org.enumerable.lambda.annotation.LambdaLocal
4 |
--------------------------------------------------------------------------------
/src/main/scala/org/enumerable/lambda/support/scala/LambdaScala.scala:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.scala
2 |
3 | import org.enumerable.lambda.{Fn0, Fn1, Fn2, Fn3}
4 |
5 | abstract class FunctionFn0[R] extends (() => R) {
6 | def apply():R
7 | }
8 |
9 | abstract class FunctionFn1[A1, R] extends ((A1) => R) {
10 | def apply(a1: A1):R
11 | }
12 |
13 | abstract class FunctionFn2[A1, A2, R] extends ((A1, A2) => R) {
14 | def apply(a1: A1, a2: A2):R
15 | }
16 |
17 | abstract class FunctionFn3[A1, A2, A3, R] extends ((A1, A2, A3) => R) {
18 | def apply(a1: A1, a2: A2, a3: A3):R
19 | }
20 |
21 | object ScalaLambdaFactory {
22 | def toFunction[R](fn: Fn0[R]) = {
23 | () => { fn.call() }
24 | }
25 |
26 | def toFunction[A1, R](fn: Fn1[A1, R]) = {
27 | (a1: A1) => { fn.call(a1) }
28 | }
29 |
30 | def toFunction[A1, A2, R](fn: Fn2[A1, A2, R]) = {
31 | (a1: A1, a2: A2) => { fn.call(a1, a2) }
32 | }
33 |
34 | def toFunction[A1, A2, A3, R](fn: Fn3[A1, A2, A3, R]) = {
35 | (a1: A1, a2: A2, a3: A3) => { fn.call(a1, a2, a3) }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/enumerable/jruby/CoreEnumerableRubySpecSuiteTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.enumerable.jruby;
2 |
3 | import static java.lang.Thread.*;
4 |
5 | import java.io.File;
6 | import java.util.ArrayList;
7 | import java.util.List;
8 |
9 | import org.junit.Test;
10 |
11 | public class CoreEnumerableRubySpecSuiteTest extends RubySpecTestBase {
12 | @Test
13 | public void core_enumerable() throws Exception {
14 | disableOutputInEclipse();
15 |
16 | File specDir = new File(getClass().getResource("/core/enumerable").toURI());
17 | List specs = new ArrayList();
18 | for (String file : specDir.list()) {
19 | if (file.endsWith(".rb"))
20 | specs.add("\"core/enumerable/" + file + "\"");
21 | }
22 | mspec(specs);
23 | }
24 |
25 | void disableOutputInEclipse() {
26 | for (StackTraceElement e : currentThread().getStackTrace())
27 | if (e.getClassName().startsWith("org.eclipse.jdt.internal.")) {
28 | specdoc = false;
29 | return;
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/enumerable/jruby/EnumerableJRubyTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.enumerable.jruby;
2 |
3 | import static org.junit.Assert.*;
4 |
5 | import org.junit.Test;
6 |
7 | public class EnumerableJRubyTest extends JRubyTestBase {
8 | @Test
9 | public void sanityCheckMonkeyPatch() throws Exception {
10 | assertEquals(eval("[1, 2, 3]"),
11 | eval("[1, 2 ,3].each {|n| Java::OrgEnumerableLambdaEnumerableJRuby::JRubyTestBase.debug n.to_s}"));
12 | assertEquals("a", eval("[\"b\", \"a\", \"c\"].min"));
13 | assertTrue((Boolean) eval("%w{ ant bear cat}.all? {|word| word.length >= 3}"));
14 | assertEquals("11", eval("[\"2\",\"33\",\"4\",\"11\"].min {|a,b| a <=> b }"));
15 | eval("test1 = [1,3,5,7,0, 2,43,53,6352,44,221,5]");
16 | assertEquals(eval("test1"), eval("test1.to_a"));
17 | assertEquals(eval("test1"), eval("test1.entries"));
18 | eval("test4 = (1..10)");
19 | assertEquals(eval("[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]"), eval("test4.sort { |a,b| b<=>a }"));
20 | assertEquals(37L, eval("(1..10).detect(lambda { 37 }) {|i| i % 5 == 0 and i % 7 == 0 }"));
21 | assertEquals(eval("[[2, 4, 6], [1, 3, 5]]"), eval("(1..6).partition {|i| (i&1).zero?}"));
22 | assertTrue((Boolean) eval("(1..10).include?(5)"));
23 | assertEquals(eval("[[1], [2], [3]]"), eval("(1..3).zip"));
24 | assertEquals(eval("[Array]"), eval("[['foo']].map {|a|a.class}"));
25 | }
26 |
27 | @Test
28 | public void testEnumerable() throws Exception {
29 | require("test/testEnumerable");
30 | }
31 |
32 | @Test
33 | public void testEnumerable_1_9() throws Exception {
34 | require("test/testEnumerable_1_9");
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/enumerable/jruby/EnumerableRubiconTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.enumerable.jruby;
2 |
3 | import org.junit.Test;
4 |
5 | public class EnumerableRubiconTest extends JRubyTestBase {
6 | @Test
7 | public void test_enumerable() throws Exception {
8 | testUnit("test/rubicon/test_enumerable", "TestEnumerableRubicon");
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/exception/UncheckedExceptionTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.exception;
2 |
3 | import static org.enumerable.lambda.exception.UncheckedException.*;
4 | import static org.junit.Assert.*;
5 |
6 | import java.io.FileInputStream;
7 |
8 | import org.enumerable.lambda.exception.UncheckedException;
9 | import org.junit.Test;
10 |
11 | public class UncheckedExceptionTest {
12 | @Test(expected = UncheckedException.class)
13 | public void wrapsCheckedExcetion() throws Exception {
14 | try {
15 | new FileInputStream("file not found");
16 | } catch (Exception e) {
17 | UncheckedException uncheck = (UncheckedException) uncheck(e);
18 | assertEquals(e.getMessage(), uncheck.getMessage());
19 | assertEquals(e.toString(), uncheck.toString());
20 | assertNull(uncheck.getCause());
21 | throw uncheck;
22 | }
23 | }
24 |
25 | @Test(expected = ArithmeticException.class)
26 | public void doesNotWrapUncheckedException() throws Exception {
27 | try {
28 | System.out.println(2 / 0);
29 | } catch (Exception e) {
30 | RuntimeException uncheck = uncheck(e);
31 | assertNull(uncheck.getCause());
32 | throw uncheck;
33 | }
34 | }
35 |
36 | @Test(expected = ArithmeticException.class)
37 | public void dropsNestedExceptions() throws Exception {
38 | try {
39 | try {
40 | getClass().getMethod("throwsAnException").invoke(this);
41 | } catch (Exception e) {
42 | throw new RuntimeException(e);
43 | }
44 | } catch (Exception e) {
45 | RuntimeException uncheck = uncheck(e);
46 | assertNull(uncheck.getCause());
47 | throw uncheck;
48 | }
49 | }
50 |
51 | public void throwsAnException() {
52 | System.out.println(2 / 0);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/extra166y/ParallelArrayToLowerCaseTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.extra166y;
2 |
3 | import static extra166y.ParallelLongArray.*;
4 | import static org.enumerable.lambda.Parameters.*;
5 | import static org.enumerable.lambda.support.extra166y.LambdaOps.*;
6 | import static org.junit.Assert.*;
7 |
8 | import org.junit.Test;
9 |
10 | import extra166y.ParallelArray;
11 | import extra166y.Ops.Op;
12 |
13 | /*
14 | * This test was adapted from the 'Examples from Jacques DeFarge' on the Java
15 | * Concurrency Wiki at
16 | * http://artisans-serverintellect-com.si-eioswww6.com/default.asp?W7
17 | */
18 | public class ParallelArrayToLowerCaseTest {
19 | @Test
20 | public void parallelToLowerCase() {
21 | final String[] list = new String[] { "AB", "CD", "EF", "GH", "MN", "RM", "JP", "LS", "QP", "TX", "ST",
22 | "SZ", "AA", "PQ", "RS", "RM", "JP", "LS", "QP", "TX", "ST", "SZ", "AA", "PQ", "RS", "RM", "JP",
23 | "LS", "QP", "TX", "ST", "SZ", "AA", "PQ", "RS", "RM", "JP", "LS", "QP", "TX", "CO", "BA", "MP",
24 | "AM", "FF" };
25 |
26 | ParallelArray lambdaPArray = ParallelArray.createFromCopy(list, defaultExecutor());
27 | ParallelArray pArray = ParallelArray.createFromCopy(list, defaultExecutor());
28 |
29 | class ToLowerMapping implements Op {
30 | public String op(String input) {
31 | return input.toLowerCase();
32 | }
33 | }
34 | ToLowerMapping toLowerMapping = new ToLowerMapping();
35 | pArray.replaceWithMapping(toLowerMapping);
36 |
37 | Op op = op(s, s.toLowerCase());
38 | lambdaPArray.replaceWithMapping(op);
39 |
40 | assertEquals(pArray.asList(), lambdaPArray.asList());
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Array_bind.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.Array.*;
5 | import static junit.framework.Assert.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 |
8 | import org.enumerable.lambda.annotation.LambdaParameter;
9 | import org.junit.Test;
10 |
11 | import fj.Show;
12 | import fj.data.Array;
13 | import fj.data.Stream;
14 |
15 | public final class Array_bind {
16 | @LambdaParameter
17 | static Integer i;
18 |
19 | @LambdaParameter
20 | static Object any;
21 |
22 | @Test
23 | public void test() {
24 | final Array a = array(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
25 | final Array b = a.bind(λ(i, array(500, i)));
26 |
27 | assertEquals("{500,97,500,44,500,67,500,3,500,22,500,90,500,1,500,77,500,98,500,1078,500,6,500,64,500,6,500,79,500,42}", arrayShow(intShow()).showS(b));
28 | // {500,97,500,44,500,67,500,3,500,22,500,90,500,1,500,77,500,98,500,1078,500,6,500,64,500,6,500,79,500,42}
29 | }
30 |
31 | public static final Show intShow() {
32 | return anyShow();
33 | }
34 |
35 | @SuppressWarnings("unchecked")
36 | public static Show anyShow() {
37 | return (Show) show(λ(any, Stream.fromString(any.toString())));
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Array_exists.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.data.Array.*;
4 | import static fj.data.List.*;
5 | import static junit.framework.Assert.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 |
8 | import org.enumerable.lambda.annotation.LambdaParameter;
9 | import org.junit.Test;
10 |
11 | import fj.data.Array;
12 |
13 | public final class Array_exists {
14 | @LambdaParameter
15 | static String s;
16 | @LambdaParameter
17 | static Character ch;
18 |
19 | @Test
20 | public void test() {
21 | final Array a = array("Hello", "There", "what", "DAY", "iS", "iT");
22 | final boolean b = a.exists(λ(s, fromString(s).forall(λ(ch, Character.isLowerCase(ch)))));
23 |
24 | assertTrue(b); // true ("what" provides the only example; try
25 | // removing it)
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Array_filter.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.Array.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.data.Array;
13 |
14 | public final class Array_filter {
15 | @LambdaParameter
16 | static Integer i;
17 |
18 | @Test
19 | public void test() {
20 | final Array a = array(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
21 | final Array b = a.filter(λ(i, i % 2 == 0));
22 | assertEquals("{44,22,90,98,1078,6,64,6,42}", arrayShow(intShow()).showS(b)); // {44,22,90,98,1078,6,64,6,42}
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Array_foldLeft.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.data.Array.*;
4 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
5 | import static org.junit.Assert.*;
6 |
7 | import org.enumerable.lambda.annotation.LambdaParameter;
8 | import org.junit.Test;
9 |
10 | import fj.data.Array;
11 |
12 | public final class Array_foldLeft {
13 | @LambdaParameter
14 | static Integer i1, i2;
15 |
16 | @Test
17 | public void test() {
18 | final Array a = array(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
19 | final int b = a.foldLeft(λ(i1, i2, i1 + i2), 0);
20 | assertEquals(1774, b); // 1774
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Array_forall.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.data.Array.*;
4 | import static fj.data.List.*;
5 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
6 | import static org.junit.Assert.*;
7 |
8 | import org.enumerable.lambda.annotation.LambdaParameter;
9 | import org.junit.Test;
10 |
11 | import fj.data.Array;
12 |
13 | public final class Array_forall {
14 | @LambdaParameter
15 | static String s;
16 | @LambdaParameter
17 | static Character ch;
18 |
19 | @Test
20 | public void test() {
21 | final Array a = array("hello", "There", "what", "day", "is", "it");
22 | final boolean b = a.forall(λ(s, fromString(s).forall(λ(ch, Character.isLowerCase(ch)))));
23 | assertFalse(b); // false ("There" is a counter-example; try
24 | // removing it)
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Array_map.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.Array.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.data.Array;
13 |
14 | public final class Array_map {
15 | @LambdaParameter
16 | static Integer i1, i2;
17 |
18 | @Test
19 | public void test() {
20 | final Array a = array(1, 2, 3);
21 | final Array b = a.map(λ(i1, i2, i1 + i2).f(42));
22 | assertEquals("{43,44,45}", arrayShow(intShow()).showS(b)); // {43,44,45}
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/List_apply.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.List.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.F;
13 | import fj.data.List;
14 |
15 | public class List_apply {
16 | @LambdaParameter
17 | static Integer i1, i2;
18 |
19 | @Test
20 | public void test() {
21 | final List> fs = single(λ(i1, i2, i1 - i2).f(2)).cons(λ(i1, i2, i1 * i2).f(2)).cons(λ(i1, i2, i1 + i2).f(2));
22 | final List three = list(3);
23 | assertEquals("<5,6,-1>", listShow(intShow()).showS(three.apply(fs))); // Prints out: <5,6,-1>
24 | }
25 | }
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/List_map.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.List.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.data.List;
13 |
14 | public final class List_map {
15 | @LambdaParameter
16 | static Integer i1, i2;
17 |
18 | @Test
19 | public void test() {
20 | final List a = list(1, 2, 3);
21 | final List b = a.map(λ(i1, i2, i1 + i2).f(42));
22 | assertEquals("<43,44,45>", listShow(intShow()).showS(b)); // [43,44,45]
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/List_sort.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Ord.*;
4 | import static fj.Show.*;
5 | import static fj.data.List.*;
6 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
7 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
8 | import static org.junit.Assert.*;
9 |
10 | import org.enumerable.lambda.annotation.LambdaParameter;
11 | import org.junit.Test;
12 |
13 | import fj.Ordering;
14 | import fj.data.List;
15 |
16 | public final class List_sort {
17 | @LambdaParameter
18 | static Integer a1, a2;
19 |
20 | @Test
21 | public void test() {
22 | final List a = list(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
23 | final List b = a.sort(ord(λ(a1, λ(a2, a1.compareTo(a2) < 0 ? Ordering.LT : a1.compareTo(a2) == 0 ? Ordering.EQ : Ordering.GT))));
24 | assertEquals("<1,3,6,6,22,42,44,64,67,77,79,90,97,98,1078>", listShow(intShow()).showS(b)); // [1,3,6,6,22,42,44,64,67,77,79,90,97,98,1078]
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Option_bind.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.Option.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.data.Option;
13 |
14 | public final class Option_bind {
15 | @LambdaParameter
16 | static Integer i;
17 |
18 | @Test
19 | public void test() {
20 | final Option o1 = some(7);
21 | final Option o2 = some(8);
22 | final Option o3 = none();
23 |
24 | final Option p1 = o1.bind(λ(i, i % 2 == 0 ? some(i * 3) : Option. none()));
25 | final Option p2 = o2.bind(λ(i, i % 2 == 0 ? some(i * 3) : Option. none()));
26 | final Option p3 = o3.bind(λ(i, i % 2 == 0 ? some(i * 3) : Option. none()));
27 |
28 | assertEquals("None", optionShow(intShow()).showS(p1)); // None
29 | assertEquals("Some(24)", optionShow(intShow()).showS(p2)); // Some(24)
30 | assertEquals("None", optionShow(intShow()).showS(p3)); // None
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Option_filter.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.Option.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.data.Option;
13 |
14 | public final class Option_filter {
15 | @LambdaParameter
16 | static Integer i;
17 |
18 | @Test
19 | public void test() {
20 | final Option o1 = some(7);
21 | final Option o2 = none();
22 | final Option o3 = some(8);
23 |
24 | final Option p1 = o1.filter(λ(i, i % 2 == 0));
25 | final Option p2 = o2.filter(λ(i, i % 2 == 0));
26 | final Option p3 = o3.filter(λ(i, i % 2 == 0));
27 |
28 | assertEquals("None", optionShow(intShow()).showS(p1)); // None
29 | assertEquals("None", optionShow(intShow()).showS(p2)); // None
30 | assertEquals("Some(8)", optionShow(intShow()).showS(p3)); // Some(8)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Option_map.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Show.*;
4 | import static fj.data.Option.*;
5 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
6 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
7 | import static org.junit.Assert.*;
8 |
9 | import org.enumerable.lambda.annotation.LambdaParameter;
10 | import org.junit.Test;
11 |
12 | import fj.data.Option;
13 |
14 | public final class Option_map {
15 | @LambdaParameter
16 | static Integer i1, i2;
17 |
18 | @Test
19 | public void test() {
20 | final Option o1 = some(7);
21 | final Option o2 = none();
22 | final Option p1 = o1.map(λ(i1, i2, i1 + i2).f(42));
23 | final Option p2 = o2.map(λ(i1, i2, i1 + i2).f(42));
24 | assertEquals("Some(49)", optionShow(intShow()).showS(p1)); // Some(49)
25 | assertEquals("None", optionShow(intShow()).showS(p2)); // None
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/Set_map.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Ord.*;
4 | import static fj.Show.*;
5 | import static fj.data.Set.*;
6 | import static org.enumerable.lambda.support.functionaljava.Array_bind.*;
7 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
8 | import static org.junit.Assert.*;
9 |
10 | import org.enumerable.lambda.annotation.LambdaParameter;
11 | import org.junit.Test;
12 |
13 | import fj.Ord;
14 | import fj.Ordering;
15 | import fj.data.Set;
16 |
17 | public final class Set_map {
18 | @LambdaParameter
19 | static Integer i;
20 |
21 | @LambdaParameter
22 | static Integer a1, a2;
23 |
24 | @Test
25 | public void test() {
26 | final Set a = empty(intOrd()).insert(1).insert(2).insert(3).insert(4).insert(5).insert(6);
27 | final Set b = a.map(intOrd(), λ(i, i / 2));
28 | assertEquals("<3,2,1,0>", listShow(intShow()).showS(b.toList())); // [3,2,1,0]
29 | }
30 |
31 | public static Ord intOrd() {
32 | return ord(λ(a1, λ(a2, a1.compareTo(a2) < 0 ? Ordering.LT : a1.compareTo(a2) == 0 ? Ordering.EQ : Ordering.GT)));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/functionaljava/TreeMap_Update.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.functionaljava;
2 |
3 | import static fj.Ord.*;
4 | import static fj.data.TreeMap.*;
5 | import static org.enumerable.lambda.support.functionaljava.LambdaFunctionalJava.*;
6 | import static org.junit.Assert.*;
7 |
8 | import org.enumerable.lambda.annotation.LambdaParameter;
9 | import org.junit.Test;
10 |
11 | import fj.Ord;
12 | import fj.Ordering;
13 | import fj.data.TreeMap;
14 |
15 | /**
16 | * Queries and updates an entry in a TreeMap in one go.
17 | */
18 | public class TreeMap_Update {
19 | @LambdaParameter
20 | static Integer i;
21 |
22 | @LambdaParameter
23 | static String a1, a2;
24 |
25 | @Test
26 | public void test() {
27 | TreeMap map = empty(stringOrd());
28 | map = map.set("foo", 2);
29 | map = map.update("foo", λ(i, i + 3))._2();
30 | assertEquals(5, (int) (map.get("foo").some())); // 5
31 | }
32 |
33 | public static Ord stringOrd() {
34 | return ord(λ(a1, λ(a2, a1.compareTo(a2) < 0 ? Ordering.LT : a1.compareTo(a2) == 0 ? Ordering.EQ : Ordering.GT)));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/support/methodhandle/LambdaMethodHandleTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.methodhandle;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.enumerable.lambda.Lambda.λ;
6 | import static org.enumerable.lambda.Parameters.s;
7 | import static org.enumerable.lambda.support.methodhandle.LambdaMethodHandle.bind;
8 | import static org.junit.Assert.assertEquals;
9 |
10 | public class LambdaMethodHandleTest {
11 | @Test
12 | public void createMethodHandleFromLambda() throws Throwable {
13 | assertEquals("hello world", bind(λ(s, s + " world")).invokeWithArguments("hello"));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/weaving/AgentMainTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.weaving;
2 |
3 | import org.enumerable.lambda.enumerable.EnumerableRegressionTest;
4 | import org.junit.Test;
5 |
6 | import static org.junit.Assert.assertFalse;
7 |
8 | public class AgentMainTest {
9 | @Test
10 | public void canAttachAgentToRunningProcess() {
11 | assertFalse("The agent should not be running", LambdaLoader.isEnabled());
12 | LambdaAgentAttach.attachAgent();
13 | new EnumerableRegressionTest().regression();
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/org/enumerable/lambda/weaving/ClassFilterTest.java:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.weaving;
2 |
3 | import org.junit.Test;
4 |
5 | import static junit.framework.Assert.assertFalse;
6 | import static junit.framework.Assert.assertTrue;
7 |
8 | public class ClassFilterTest {
9 | @Test
10 | public void testExcludedPackages(){
11 | ClassFilter filter = new ClassFilter("packagetoingnore", "", "");
12 | assertFalse(filter.isToBeInstrumented("packagetoingnore.MyClass"));
13 | assertFalse(filter.isToBeInstrumented("java.util.Map"));
14 | assertTrue(filter.isToBeInstrumented("newpackage.AnotherClass"));
15 | }
16 |
17 | @Test
18 | public void testIncludePackages(){
19 | ClassFilter filter = new ClassFilter("", "mypackage", "");
20 | assertTrue(filter.isToBeInstrumented("mypackage.AnotherClass"));
21 | assertFalse(filter.isToBeInstrumented("packagetoingnore.MyClass"));
22 | assertFalse(filter.isToBeInstrumented("java.util.Map"));
23 | }
24 |
25 | @Test
26 | public void testIncludeExcludePattern(){
27 | ClassFilter filter = new ClassFilter("", "mypackage", "UUAARGH");
28 | assertTrue(filter.isToBeInstrumented("mypackage.AnotherClass"));
29 | assertFalse(filter.isToBeInstrumented("mypackage.AnotherUUAARGHClass"));
30 | assertFalse(filter.isToBeInstrumented("packagetoingnore.MyClass"));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_all.rb:
--------------------------------------------------------------------------------
1 | ######################################################################
2 | # tc_all.rb
3 | #
4 | # Test case for the Enumerable#all? instance method.
5 | ######################################################################
6 | require 'test/unit'
7 |
8 | class TC_Enumerable_All_InstanceMethod < Test::Unit::TestCase
9 | def setup
10 | @enum = ['a', 'b', 'c']
11 | end
12 |
13 | def test_all_basic
14 | assert_respond_to(@enum, :all?)
15 | assert_nothing_raised{ @enum.all? }
16 | assert_nothing_raised{ @enum.all?{ } }
17 | end
18 |
19 | def test_all_no_block
20 | assert_equal(true, [1, 2, 3].all?)
21 | assert_equal(false, [nil, false, true].all?)
22 | assert_equal(false, [nil, false].all?)
23 | end
24 |
25 | def test_all_with_block
26 | assert_equal(false, [1, 2, 3].all?{ |e| e > 1 })
27 | assert_equal(true, [1, 2, 3].all?{ |e| e > 0 })
28 | end
29 |
30 | def test_all_with_explicit_false_and_nil
31 | assert_equal(true, [nil].all?{ |e| e.nil? })
32 | assert_equal(true, [false].all?{ |e| e == false })
33 | end
34 |
35 | def test_all_edge_cases
36 | assert_equal(true, [].all?)
37 | assert_equal(true, [0].all?)
38 | assert_equal(true, [true].all?)
39 | end
40 |
41 | def test_all_expected_errors
42 | assert_raise(ArgumentError){ [1, 2, 3].all?(1) }
43 | end
44 |
45 | def teardown
46 | @enum = nil
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_any.rb:
--------------------------------------------------------------------------------
1 | ######################################################################
2 | # tc_any.rb
3 | #
4 | # Test case for the Enumerable#any? instance method.
5 | ######################################################################
6 | require 'test/unit'
7 |
8 | class TC_Enumerable_Any_InstanceMethod < Test::Unit::TestCase
9 | def setup
10 | @enum = ['a', 'b', 'c']
11 | end
12 |
13 | def test_any_basic
14 | assert_respond_to(@enum, :any?)
15 | assert_nothing_raised{ @enum.any? }
16 | assert_nothing_raised{ @enum.any?{ } }
17 | end
18 |
19 | def test_any_no_block
20 | assert_equal(true, [1, 2, 3].any?)
21 | assert_equal(true, [nil, false, true].any?)
22 | assert_equal(false, [nil, false].any?)
23 | end
24 |
25 | def test_any_with_block
26 | assert_equal(true, [1, 2, 3].any?{ |e| e > 1 })
27 | assert_equal(false, [1, 2, 3].any?{ |e| e > 7 })
28 | end
29 |
30 | def test_any_with_explicit_false_and_nil
31 | assert_equal(true, [false, nil].any?{ |e| e.nil? })
32 | assert_equal(true, [false, nil].any?{ |e| e == false })
33 | end
34 |
35 | def test_any_edge_cases
36 | assert_equal(false, [].any?)
37 | assert_equal(true, [0].any?)
38 | assert_equal(true, [true].any?)
39 | end
40 |
41 | def test_any_expected_errors
42 | assert_raise(ArgumentError){ [1, 2, 3].any?(1) }
43 | end
44 |
45 | def teardown
46 | @enum = nil
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_each_with_index.rb:
--------------------------------------------------------------------------------
1 | #########################################################################
2 | # tc_each_with_index.rb
3 | #
4 | # Test suite for the Enumerable#each_with_index instance method.
5 | #
6 | # Note: We use a custom object here because Array and Hash have custom
7 | # implementations.
8 | #########################################################################
9 | require 'test/unit'
10 |
11 | class MyEnumEachWithIndex
12 | include Enumerable
13 |
14 | attr_accessor :arg1, :arg2, :arg3
15 |
16 | def initialize(arg1='a', arg2='b', arg3='c')
17 | @arg1 = arg1
18 | @arg2 = arg2
19 | @arg3 = arg3
20 | end
21 |
22 | def each
23 | yield @arg1
24 | yield @arg2
25 | yield @arg3
26 | end
27 | end
28 |
29 | class TC_Enumerable_EachWithIndex_InstanceMethod < Test::Unit::TestCase
30 | def setup
31 | @enum = MyEnumEachWithIndex.new
32 | @array = []
33 | end
34 |
35 | def test_each_with_index_basic
36 | assert_respond_to(@enum, :each_with_index)
37 | # Enumerable.java is strict about the number of arguments a block takes.
38 | # assert_nothing_raised{ @enum.each_with_index{} }
39 | assert_nothing_raised{ @enum.each_with_index{|e, i|} }
40 | end
41 |
42 | def test_each_with_index
43 | assert_nothing_raised{ @enum.each_with_index{ |e, i| @array[i] = e } }
44 | assert_equal(['a', 'b', 'c'], @array)
45 | end
46 |
47 | def test_expected_errors
48 | # No longer a valid test in 1.8.7
49 | =begin
50 | assert_raise(LocalJumpError){ @enum.each_with_index }
51 | =end
52 | assert_raise(ArgumentError){ @enum.each_with_index(true) }
53 | end
54 |
55 | def teardown
56 | @enum = nil
57 | @array = nil
58 | end
59 | end
60 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_inject.rb:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # tc_inject.rb
3 | #
4 | # Test case for the Enumerable#inject instance method.
5 | ########################################################################
6 | require 'test/unit'
7 |
8 | class TC_Enumerable_Inject_InstanceMethod < Test::Unit::TestCase
9 | def setup
10 | @memo = nil
11 | @enum_nums = [1, 2, 3]
12 | @enum_alpha = ['a', 'b', 'c']
13 | end
14 |
15 | def test_inject_basic
16 | assert_respond_to(@enum_nums, :inject)
17 | # Enumerable.java is strict about the number of arguments a block takes.
18 | # assert_nothing_raised{ @enum_nums.inject{} }
19 | assert_nothing_raised{ @enum_nums.inject{|n, m|} }
20 | end
21 |
22 | def test_inject
23 | assert_equal(6, @enum_nums.inject{ |m, n| m + n })
24 | assert_equal('abc', @enum_alpha.inject{ |m, n| m + n })
25 | end
26 |
27 | def test_inject_with_initial_value
28 | assert_equal(10, @enum_nums.inject(4){ |m, n| m + n })
29 | assert_equal('xxxabc', @enum_alpha.inject('xxx'){ |m, n| m + n })
30 | end
31 |
32 | def test_inject_edge_cases
33 | assert_equal(nil, [].inject{ |m,n| m + n })
34 | assert_equal(0, [0].inject{ |m,n| m + n })
35 | end
36 |
37 | # Breaks with different exceptions after upgrading to JRuby 1.6.5
38 | # def test_inject_expected_errors
39 | # assert_raise(LocalJumpError){ @enum_nums.inject }
40 | # assert_raise(ArgumentError){ @enum_nums.inject(1,2){} }
41 | # end
42 |
43 | def teardown
44 | @memo = nil
45 | @enum_nums = nil
46 | @enum_alpha = nil
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_max.rb:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # tc_max.rb
3 | #
4 | # Test case for the Enumerable#max instance method.
5 | #
6 | # Note: I use arrays here because I know that array.c doesn't implement
7 | # its own version.
8 | ########################################################################
9 | require 'test/unit'
10 |
11 | class TC_Enumerable_Max_InstanceMethod < Test::Unit::TestCase
12 | def setup
13 | @enum_nums = [1, 2, 3]
14 | @enum_alpha = ['alpha', 'beetlejuice', 'gamma']
15 | end
16 |
17 | def test_max_basic
18 | assert_equal(true, @enum_nums.respond_to?(:max))
19 | assert_nothing_raised{ @enum_nums.max }
20 | assert_nothing_raised{ @enum_nums.max{ |a,b| a <=> b } }
21 | end
22 |
23 | def test_max
24 | assert_equal(3, @enum_nums.max)
25 | assert_equal('gamma', @enum_alpha.max)
26 | end
27 |
28 | def test_max_with_block
29 | assert_equal(1, @enum_nums.max{ |a,b| b <=> a} )
30 | assert_equal('alpha', @enum_alpha.max{ |a,b| b <=> a} )
31 | assert_equal('beetlejuice', @enum_alpha.max{ |a,b| a.length <=> b.length } )
32 | end
33 |
34 | def test_max_edge_cases
35 | assert_equal(nil, [].max)
36 | assert_equal(nil, [nil].max)
37 | end
38 |
39 | def test_max_expected_errors
40 | # Enumerable.java won't raise an exception here as null can be any class in Java
41 | # Should be tested with another object not implementing Comparable and has a Ruby counterpart.
42 | # assert_raise(NoMethodError){ [nil, nil].max }
43 | assert_equal(nil, [nil, nil].max)
44 | end
45 |
46 | def teardown
47 | @enum_nums = nil
48 | @enum_alpah = nil
49 | end
50 | end
51 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_min.rb:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # tc_min.rb
3 | #
4 | # Test case for the Enumerable#min instance method.
5 | #
6 | # Note: I use arrays here because I know that array.c doesn't implement
7 | # its own version.
8 | ########################################################################
9 | require 'test/unit'
10 |
11 | class TC_Enumerable_Min_InstanceMethod < Test::Unit::TestCase
12 | def setup
13 | @enum_nums = [1, 2, 3]
14 | @enum_alpha = ['alpha', 'beta', 'gamma']
15 | end
16 |
17 | def test_min_basic
18 | assert_equal(true, @enum_nums.respond_to?(:min))
19 | assert_nothing_raised{ @enum_nums.min }
20 | assert_nothing_raised{ @enum_nums.min{ |a,b| a <=> b } }
21 | end
22 |
23 | def test_min
24 | assert_equal(1, @enum_nums.min)
25 | assert_equal('alpha', @enum_alpha.min)
26 | end
27 |
28 | def test_min_with_block
29 | assert_equal(3, @enum_nums.min{ |a,b| b <=> a} )
30 | assert_equal('gamma', @enum_alpha.min{ |a,b| b <=> a} )
31 | assert_equal('beta', @enum_alpha.min{ |a,b| a.length <=> b.length } )
32 | end
33 |
34 | def test_min_edge_cases
35 | assert_equal(nil, [].min)
36 | assert_equal(nil, [nil].min)
37 | end
38 |
39 | def test_min_expected_errors
40 | # Enumerable.java won't raise an exception here as null can be any class in Java
41 | # Should be tested with another object not implementing Comparable and has a Ruby counterpart.
42 | # assert_raise(NoMethodError){ [nil, nil].min }
43 | assert_equal(nil, [nil, nil].min)
44 | end
45 |
46 | def teardown
47 | @enum_nums = nil
48 | @enum_alpah = nil
49 | end
50 | end
51 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_partition.rb:
--------------------------------------------------------------------------------
1 | ########################################################################
2 | # tc_partition.rb
3 | #
4 | # Test case for the Enumerable#partition instance method.
5 | ########################################################################
6 | require 'test/unit'
7 |
8 | class TC_Enumerable_Partition_InstanceMethod < Test::Unit::TestCase
9 | def setup
10 | @enum = [1,2,3,4,5]
11 | end
12 |
13 | def test_partition_basic
14 | assert_respond_to(@enum, :partition)
15 | assert_nothing_raised{ @enum.partition{} }
16 | assert_equal(2, @enum.partition{}.length)
17 | assert_kind_of(Array, @enum.partition{}[0])
18 | assert_kind_of(Array, @enum.partition{}[1])
19 | end
20 |
21 | def test_partition
22 | assert_equal([[1,3,5],[2,4]], @enum.partition{ |e| e % 2 != 0 })
23 | assert_equal([[1,2,3,4,5],[]], @enum.partition{ |e| e < 10 })
24 | assert_equal([[],[1,2,3,4,5]], @enum.partition{ |e| e > 10 })
25 | end
26 |
27 | def test_partition_edge_cases
28 | assert_equal([[],[]], [].partition{ |e| e > 10 })
29 | assert_equal([[nil],[false]], [nil,false].partition{ |e| e.nil? })
30 | assert_equal([[false],[nil]], [nil,false].partition{ |e| e == false })
31 | assert_equal([[],[nil, false]], [nil,false].partition{})
32 | end
33 |
34 | def test_partition_expected_errors
35 | # No longer a valid test in 1.8.7
36 | =begin
37 | assert_raise(LocalJumpError){ @enum.partition }
38 | =end
39 | # Enumerable.java will raise TypeError here, as true will fail to be coerced into a block
40 | # assert_raise(ArgumentError){ @enum.partition(true) }
41 | assert_raise(TypeError){ @enum.partition(true) }
42 | end
43 |
44 | def teardown
45 | @enum = nil
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_reject.rb:
--------------------------------------------------------------------------------
1 | #########################################################################
2 | # tc_reject.rb
3 | #
4 | # Test suite for the Enumerable#reject instance method.
5 | #########################################################################
6 | require 'test/unit'
7 |
8 | class MyEnumReject
9 | include Enumerable
10 |
11 | attr_accessor :arg1, :arg2, :arg3
12 |
13 | def initialize(arg1, arg2, arg3)
14 | @arg1 = arg1
15 | @arg2 = arg2
16 | @arg3 = arg3
17 | end
18 |
19 | def each
20 | yield @arg1
21 | yield @arg2
22 | yield @arg3
23 | end
24 | end
25 |
26 | class TC_Enumerable_Reject_InstanceMethod < Test::Unit::TestCase
27 | def setup
28 | @enum = MyEnumReject.new(1,2,3)
29 | end
30 |
31 | def test_reject_basic
32 | assert_respond_to(@enum, :reject)
33 | assert_nothing_raised{ @enum.reject{} }
34 | end
35 |
36 | def test_reject
37 | assert_equal([1,2,3], @enum.reject{ |e| e > 7 })
38 | assert_equal([1], @enum.reject{ |e| e > 1 })
39 | end
40 |
41 | def test_reject_explicit_false_and_nil
42 | @enum = MyEnumReject.new(nil, nil, false)
43 | assert_equal([false], @enum.reject{ |e| e.nil? })
44 | assert_equal([nil, nil], @enum.reject{ |e| e == false })
45 | assert_equal([nil, nil, false], @enum.reject{})
46 | end
47 |
48 | def test_reject_edge_cases
49 | assert_equal([], @enum.reject{ true })
50 | assert_equal([1,2,3], @enum.reject{})
51 | end
52 |
53 | def test_reject_expected_errors
54 | # No longer a valid test in 1.8.7
55 | =begin
56 | assert_raise(LocalJumpError){ @enum.reject }
57 | =end
58 | # Enumerable.java will raise TypeError here, as 5 will fail to be coerced into a block
59 | # assert_raise(ArgumentError){ @enum.reject(5) }
60 | assert_raise(TypeError){ @enum.reject(5) }
61 | end
62 |
63 | def teardown
64 | @enum = nil
65 | end
66 | end
67 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_sort_by.rb:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # tc_sort_by.rb
3 | #
4 | # Test case for the Enumerable#sort_by instance method.
5 | ###############################################################################
6 | require 'test/unit'
7 |
8 | class TC_Enumerable_SortBy_InstanceMethod < Test::Unit::TestCase
9 | def setup
10 | @words = ['apple', 'pear', 'fig']
11 | @nums = [1, 0, -1, 77, 15]
12 | @mixed = [Time.now, 0, nil, true, false, 'hello']
13 | end
14 |
15 | def test_sort_by_basic
16 | assert_respond_to(@words, :sort_by)
17 | assert_nothing_raised{ @words.sort_by{ |w| w.length } }
18 | end
19 |
20 | def test_sort_by
21 | assert_equal(['fig', 'pear', 'apple'], @words.sort_by{ |w| w.length })
22 | assert_equal([0, 1, -1, 15, 77], @nums.sort_by{ |n| n.abs })
23 | end
24 |
25 | def test_sort_by_edge_cases
26 | assert_equal([], [].sort_by{ |n| n.to_s })
27 | assert_equal([nil, nil], [nil, nil].sort_by{ |n| n.to_s })
28 | end
29 |
30 | def test_sort_by_expected_errors
31 | # No longer a valid test in 1.8.7
32 | =begin
33 | assert_raise(LocalJumpError){ @words.sort_by }
34 | =end
35 | # Enumerable.java will raise TypeError here, as 1 will fail to be coerced into a block
36 | # assert_raise(ArgumentError){ @words.sort_by(1) }
37 | assert_raise(TypeError){ @words.sort_by(1) }
38 | assert_raise(NoMethodError){ @words.sort_by{} }
39 | assert_raise(NoMethodError){ @mixed.sort_by{ |m| m.length } }
40 | end
41 |
42 | def teardown
43 | @words = nil
44 | @nums = nil
45 | @mixed = nil
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/src/test/jruby/test/externals/ruby_test/test/core/Enumerable/instance/tc_to_a.rb:
--------------------------------------------------------------------------------
1 | #########################################################################
2 | # tc_to_a.rb
3 | #
4 | # Test suite for the Enumerable#to_a instance method and the
5 | # Enumerable#entries alias.
6 | #########################################################################
7 | require 'test/unit'
8 |
9 | class MyEnumToA
10 | include Enumerable
11 |
12 | attr_accessor :arg1, :arg2, :arg3
13 |
14 | def initialize(arg1=1, arg2=2, arg3=3)
15 | @arg1 = arg1
16 | @arg2 = arg2
17 | @arg3 = arg3
18 | end
19 |
20 | def each
21 | yield @arg1
22 | yield @arg2
23 | yield @arg3
24 | end
25 | end
26 |
27 | class TC_Enumerable_ToA_InstanceMethod < Test::Unit::TestCase
28 | def setup
29 | @enum = MyEnumToA.new
30 | end
31 |
32 | def test_to_a_basic
33 | assert_respond_to(@enum, :to_a)
34 | assert_nothing_raised{ @enum.to_a }
35 | assert_kind_of(Array, @enum.to_a)
36 | end
37 |
38 | def test_to_a
39 | assert_equal([1, 2, 3], @enum.to_a)
40 | end
41 |
42 | def test_to_a_edge_cases
43 | assert_equal([nil, nil, nil], MyEnumToA.new(nil, nil, nil).to_a)
44 | end
45 |
46 | def test_entries_alias
47 | msg = '=> Known issue in MRI'
48 | assert_respond_to(@enum, :entries)
49 | # Skipped as Enumerble.java cannot alias in Java and is using method_missing
50 | # assert_equal(true, @enum.method(:to_a) == @enum.method(:entries), msg)
51 | end
52 |
53 | def test_expected_errors
54 | assert_raise(ArgumentError){ @enum.to_a(true) }
55 | end
56 |
57 | def teardown
58 | @enum = nil
59 | end
60 | end
61 |
--------------------------------------------------------------------------------
/src/test/jruby/test/testEnumerable_1_9.rb:
--------------------------------------------------------------------------------
1 | require 'test/minirunit'
2 |
3 | class TestEnumerable
4 | include Enumerable
5 | def initialize(value)
6 | @value = value
7 | end
8 | def each(&block)
9 | @value.each(&block)
10 | end
11 | end
12 |
13 | test_equal nil, TestEnumerable.new([]).first
14 | test_equal :foo, TestEnumerable.new([:foo]).first
15 | test_equal [], TestEnumerable.new([[], 1, 2, 3]).first
16 | test_equal [1], TestEnumerable.new([[1], 1, 2, 3]).first
17 | test_equal [], TestEnumerable.new([]).first(0)
18 |
19 | test_exception(ArgumentError) do
20 | TestEnumerable.new([]).first(-1)
21 | end
22 |
23 | test_equal [], TestEnumerable.new([1,2,3]).first(0)
24 |
25 | test_exception(ArgumentError) do
26 | TestEnumerable.new([1,2,3]).first(-1)
27 | end
28 |
29 | test_equal [1], TestEnumerable.new([1,2,3]).first(1)
30 | test_equal [1,2], TestEnumerable.new([1,2,3]).first(2)
31 | test_equal [1,2,3], TestEnumerable.new([1,2,3]).first(3)
32 | test_equal [1,2,3], TestEnumerable.new([1,2,3]).first(4)
33 |
34 | test_equal({ }, TestEnumerable.new([]).group_by(&:length))
35 | test_equal({5=>["pelle"], 6=>["marcus"], 3=>["ola", "tom"], 4=>["bini", "pele"], 10=>["gustafsson"]},
36 | TestEnumerable.new(%w(ola bini gustafsson pelle tom marcus pele)).group_by(&:length))
37 | test_equal({[5]=>["pelle"], [6]=>["marcus"], [3]=>["ola", "tom"], [4]=>["bini", "pele"], [10]=>["gustafsson"]},
38 | TestEnumerable.new(%w(ola bini gustafsson pelle tom marcus pele)).group_by{ |v| [v.length]})
39 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/chunk_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | ruby_version_is "1.9" do
5 | describe "Enumerable#chunk" do
6 | it "raises an ArgumentError if called without a block" do
7 | lambda do
8 | EnumerableSpecs::Numerous.new.chunk
9 | end.should raise_error(ArgumentError)
10 | end
11 |
12 | it "returns an Enumerator if given a block" do
13 | EnumerableSpecs::Numerous.new.chunk {}.should be_an_instance_of(enumerator_class)
14 | end
15 |
16 | it "yields each element of the Enumerable to the block" do
17 | yields = []
18 | EnumerableSpecs::Numerous.new.chunk {|e| yields << e}.to_a
19 | EnumerableSpecs::Numerous.new.to_a.should == yields
20 | end
21 |
22 | it "returns an Enumerator of 2-element Arrays" do
23 | EnumerableSpecs::Numerous.new.chunk {|e| true}.each do |a|
24 | a.should be_an_instance_of(Array)
25 | a.size.should == 2
26 | end
27 | end
28 |
29 | it "sets the first element of each sub-Array to the return value of the block" do
30 | EnumerableSpecs::Numerous.new.chunk {|e| -e }.each do |a|
31 | a.first.should == -a.last.first
32 | end
33 | end
34 |
35 | it "sets the last element of each sub-Array to the consecutive values for which the block returned the first element" do
36 | ret = EnumerableSpecs::Numerous.new(5,5,2,3,4,5,7,1,9).chunk {|e| e >= 5 }.to_a
37 | ret[0].last.should == [5, 5]
38 | ret[1].last.should == [2, 3, 4]
39 | ret[2].last.should == [5, 7]
40 | ret[3].last.should == [1]
41 | ret[4].last.should == [9]
42 | end
43 | end
44 | end
45 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/collect_concat_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/collect_concat', __FILE__)
4 |
5 | ruby_version_is "1.9" do
6 | describe "Enumerable#collect_concat" do
7 | it_behaves_like(:enumerable_collect_concat , :collect_concat)
8 | end
9 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/collect_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/collect', __FILE__)
4 |
5 | describe "Enumerable#collect" do
6 | it_behaves_like(:enumerable_collect , :collect)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/count_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#count" do
5 | ruby_version_is '1.8.7' do
6 | before :each do
7 | @elements = [1, 2, 4, 2]
8 | @numerous = EnumerableSpecs::Numerous.new(*@elements)
9 | end
10 |
11 | it "returns size when no argument or a block" do
12 | @numerous.count.should == 4
13 | end
14 |
15 | it "counts nils if given nil as an argument" do
16 | EnumerableSpecs::Numerous.new(nil, nil, nil, false).count(nil).should == 3
17 | end
18 |
19 | it "accepts an argument for comparison using ==" do
20 | @numerous.count(2).should == 2
21 | end
22 |
23 | it "uses a block for comparison" do
24 | @numerous.count{|x| x%2==0 }.should == 3
25 | end
26 |
27 | it "ignores the block when given an argument" do
28 | @numerous.count(4){|x| x%2==0 }.should == 1
29 | end
30 | end
31 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/detect_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/find', __FILE__)
4 |
5 | describe "Enumerable#detect" do
6 | it_behaves_like(:enumerable_find , :detect)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/drop_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#drop" do
5 | ruby_version_is '1.8.7' do
6 | before :each do
7 | @enum = EnumerableSpecs::Numerous.new(3, 2, 1, :go)
8 | end
9 |
10 | it "requires exactly one argument" do
11 | lambda{ @enum.drop{} }.should raise_error(ArgumentError)
12 | lambda{ @enum.drop(1, 2){} }.should raise_error(ArgumentError)
13 | end
14 |
15 | describe "passed a number n as an argument" do
16 | it "raise ArgumentError if n < 0" do
17 | lambda{ @enum.drop(-1) }.should raise_error(ArgumentError)
18 | end
19 |
20 | it "tries to convert n to an Integer using #to_int" do
21 | @enum.drop(2.3).should == [1, :go]
22 |
23 | obj = mock('to_int')
24 | obj.should_receive(:to_int).and_return(2)
25 | @enum.drop(obj).should == [1, :go]
26 | end
27 |
28 | it "returns [] for empty enumerables" do
29 | EnumerableSpecs::Empty.new.drop(0).should == []
30 | EnumerableSpecs::Empty.new.drop(2).should == []
31 | end
32 |
33 | it "returns [] if dropping all" do
34 | @enum.drop(5).should == []
35 | EnumerableSpecs::Numerous.new(3, 2, 1, :go).drop(4).should == []
36 | end
37 |
38 | it "raises a TypeError when the passed n can be coerced to Integer" do
39 | lambda{ @enum.drop("hat") }.should raise_error(TypeError)
40 | lambda{ @enum.drop(nil) }.should raise_error(TypeError)
41 | end
42 |
43 | end
44 | end
45 | end
46 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/drop_while_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#drop_while" do
5 | ruby_version_is '1.8.7' do
6 | before :each do
7 | @enum = EnumerableSpecs::Numerous.new(3, 2, 1, :go)
8 | end
9 |
10 | platform_is_not :enumerable_java do
11 | it 'returns an Enumerator if no block given' do
12 | @enum.drop_while.should be_an_instance_of(enumerator_class)
13 | end
14 | end
15 |
16 | it "returns no/all elements for {true/false} block" do
17 | @enum.drop_while{true}.should == []
18 | @enum.drop_while{false}.should == @enum.to_a
19 | end
20 |
21 | it "accepts returns other than true/false" do
22 | @enum.drop_while{1}.should == []
23 | @enum.drop_while{nil}.should == @enum.to_a
24 | end
25 |
26 | it "passes elements to the block until the first false" do
27 | a = []
28 | @enum.drop_while{|obj| (a << obj).size < 3}.should == [1, :go]
29 | a.should == [3, 2, 1]
30 | end
31 |
32 | it "will only go through what's needed" do
33 | enum = EnumerableSpecs::EachCounter.new(1,2,3,4)
34 | enum.drop_while { |x|
35 | break 42 if x == 3
36 | true
37 | }.should == 42
38 | enum.times_yielded.should == 3
39 | end
40 |
41 | platform_is_not :enumerable_java do
42 | it "doesn't return self when it could" do
43 | a = [1,2,3]
44 | a.drop_while{false}.should_not equal(a)
45 | end
46 | end
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/each_entry_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | ruby_version_is '1.9' do
5 | describe "Enumerable#each_entry" do
6 | before :each do
7 | @enum = EnumerableSpecs::YieldsMixed.new
8 | @entries = [1, [2], [3,4], [5,6,7], [8,9], nil, []]
9 | end
10 |
11 | it "yields multiple arguments as an array" do
12 | acc = []
13 | @enum.each_entry {|g| acc << g}.should equal(@enum)
14 | acc.should == @entries
15 | end
16 |
17 | it "returns an enumerator if no block" do
18 | e = @enum.each_entry
19 | e.should be_an_instance_of(enumerator_class)
20 | e.to_a.should == @entries
21 | end
22 |
23 | it "raises an Argument error when extra arguments" do
24 | lambda { @enum.each_entry("one").to_a }.should raise_error(ArgumentError)
25 | lambda { @enum.each_entry("one"){}.to_a }.should raise_error(ArgumentError)
26 | end
27 |
28 | it "passes extra arguments to #each" do
29 | enum = EnumerableSpecs::EachCounter.new(1, 2)
30 | enum.each_entry(:foo, "bar").to_a.should == [1,2]
31 | enum.arguments_passed.should == [:foo, "bar"]
32 | end
33 | end
34 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/each_with_index_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#each_with_index" do
5 |
6 | before :each do
7 | @b = EnumerableSpecs::Numerous.new(2, 5, 3, 6, 1, 4)
8 | end
9 |
10 | it "passes each element and its index to block" do
11 | @a = []
12 | @b.each_with_index { |o, i| @a << [o, i] }
13 | @a.should == [[2, 0], [5, 1], [3, 2], [6, 3], [1, 4], [4, 5]]
14 | end
15 |
16 | it "provides each element to the block" do
17 | acc = []
18 | obj = EnumerableSpecs::EachDefiner.new()
19 | res = obj.each_with_index {|a,i| acc << [a,i]}
20 | acc.should == []
21 | obj.should == res
22 | end
23 |
24 | it "provides each element to the block and its index" do
25 | acc = []
26 | res = @b.each_with_index {|a,i| acc << [a,i]}
27 | [[2, 0], [5, 1], [3, 2], [6, 3], [1, 4], [4, 5]].should == acc
28 | res.should eql(@b)
29 | end
30 |
31 | platform_is_not :enumerable_java do
32 | it "binds splat arguments properly" do
33 | acc = []
34 | res = @b.each_with_index { |*b| c,d = b; acc << c; acc << d }
35 | [2, 0, 5, 1, 3, 2, 6, 3, 1, 4, 4, 5].should == acc
36 | res.should eql(@b)
37 | end
38 | end
39 |
40 | platform_is_not :enumerable_java do
41 | ruby_version_is '1.8.7' do
42 | it "returns an enumerator if no block" do
43 | e = @b.each_with_index
44 | e.should be_an_instance_of(enumerator_class)
45 | e.to_a.should == [[2, 0], [5, 1], [3, 2], [6, 3], [1, 4], [4, 5]]
46 | end
47 | end
48 | end
49 |
50 | ruby_version_is '1.9' do
51 | it "passes extra parameters to each" do
52 | count = EnumerableSpecs::EachCounter.new(:apple)
53 | e = count.each_with_index(:foo, :bar)
54 | e.to_a.should == [[:apple, 0]]
55 | count.arguments_passed.should == [:foo, :bar]
56 | end
57 | end
58 | end
59 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/each_with_object_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#each_with_object" do
5 | ruby_version_is '1.8.8' do
6 | before :each do
7 | @values = [2, 5, 3, 6, 1, 4]
8 | @enum = EnumerableSpecs::Numerous.new(*@values)
9 | @initial = "memo"
10 | end
11 |
12 | it "passes each element and its argument to the block" do
13 | acc = []
14 | @enum.each_with_object(@initial) do |elem, obj|
15 | obj.should equal(@initial)
16 | obj = 42
17 | acc << elem
18 | end.should equal(@initial)
19 | acc.should == @values
20 | end
21 |
22 | platform_is_not :enumerable_java do
23 | it "returns an enumerator if no block" do
24 | acc = []
25 | e = @enum.each_with_object(@initial)
26 | e.each do |elem, obj|
27 | obj.should equal(@initial)
28 | obj = 42
29 | acc << elem
30 | end.should equal(@initial)
31 | acc.should == @values
32 | end
33 | end
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/entries_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/entries', __FILE__)
4 |
5 | describe "Enumerable#entries" do
6 | it_behaves_like(:enumerable_entries , :entries)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/find_all_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/find_all', __FILE__)
4 |
5 | describe "Enumerable#find_all" do
6 | it_behaves_like(:enumerable_find_all , :find_all)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/find_index_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#find_index" do
5 | ruby_version_is "1.8.7" do
6 | before :each do
7 | @elements = [2, 4, 6, 8, 10]
8 | @numerous = EnumerableSpecs::Numerous.new(*@elements)
9 | end
10 |
11 | it "passes each entry in enum to block while block when block is false" do
12 | visited_elements = []
13 | @numerous.find_index do |element|
14 | visited_elements << element
15 | false
16 | end
17 | visited_elements.should == @elements
18 | end
19 |
20 | it "returns nil when the block is false" do
21 | @numerous.find_index {|e| false }.should == nil
22 | end
23 |
24 | it "returns the first index for which the block is not false" do
25 | @elements.each_with_index do |element, index|
26 | @numerous.find_index {|e| e > element - 1 }.should == index
27 | end
28 | end
29 |
30 | it "returns the first index found" do
31 | repeated = [10, 11, 11, 13, 11, 13, 10, 10, 13, 11]
32 | numerous_repeat = EnumerableSpecs::Numerous.new(*repeated)
33 | repeated.each do |element|
34 | numerous_repeat.find_index(element).should == element - 10
35 | end
36 | end
37 |
38 | it "returns nil when the element not found" do
39 | @numerous.find_index(-1).should == nil
40 | end
41 |
42 | it "ignores the block if an argument is given" do
43 | @numerous.find_index(-1) {|e| true }.should == nil
44 | end
45 |
46 | platform_is_not :enumerable_java do
47 | ruby_version_is '1.8.7' do
48 | it 'returns an Enumerator if no block given' do
49 | @numerous.find_index.should be_an_instance_of(enumerator_class)
50 | end
51 | end
52 | end
53 |
54 | end
55 |
56 | end
57 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/find_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/find', __FILE__)
4 |
5 | describe "Enumerable#find" do
6 | it_behaves_like(:enumerable_find , :find)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/first_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/take', __FILE__)
4 |
5 | describe "Enumerable#first" do
6 | ruby_version_is '1.8.7' do
7 | it "returns the first element" do
8 | EnumerableSpecs::Numerous.new.first.should == 2
9 | EnumerableSpecs::Empty.new.first.should == nil
10 | end
11 |
12 | it "returns nil if self is empty" do
13 | EnumerableSpecs::Empty.new.first.should == nil
14 | end
15 |
16 | describe "when passed an argument" do
17 | it_behaves_like :enumerable_take, :first
18 | end
19 | end
20 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/flat_map_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/collect_concat', __FILE__)
4 |
5 | ruby_version_is "1.9" do
6 | describe "Enumerable#flat_map" do
7 | it_behaves_like(:enumerable_collect_concat , :flat_map)
8 | end
9 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/grep_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#grep" do
5 | before(:each) do
6 | @a = EnumerableSpecs::EachDefiner.new( 2, 4, 6, 8, 10)
7 | end
8 |
9 | platform_is_not :enumerable_java do
10 | it "grep without a block should return an array of all elements === pattern" do
11 | class EnumerableSpecGrep; def ===(obj); obj == '2'; end; end
12 |
13 | EnumerableSpecs::Numerous.new('2', 'a', 'nil', '3', false).grep(EnumerableSpecGrep.new).should == ['2']
14 | end
15 | end
16 |
17 | platform_is_not :enumerable_java do
18 | it "grep with a block should return an array of elements === pattern passed through block" do
19 | class EnumerableSpecGrep2; def ===(obj); /^ca/ =~ obj; end; end
20 |
21 | EnumerableSpecs::Numerous.new("cat", "coat", "car", "cadr", "cost").grep(EnumerableSpecGrep2.new) { |i| i.upcase }.should == ["CAT", "CAR", "CADR"]
22 | end
23 | end
24 |
25 | platform_is_not :enumerable_java do
26 | it "grep the enumerable (rubycon legacy)" do
27 | EnumerableSpecs::EachDefiner.new().grep(1).should == []
28 | @a.grep(3..7).should == [4,6]
29 | @a.grep(3..7) {|a| a+1}.should == [5,7]
30 | end
31 | end
32 |
33 | platform_is_not :enumerable_java do
34 | it "can use $~ in the block when used with a Regexp" do
35 | ary = ["aba", "aba"]
36 | ary.grep(/a(b)a/) { $1 }.should == ["b", "b"]
37 | end
38 | end
39 | end
40 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/group_by_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#group_by" do
5 | ruby_version_is "1.8.7" do
6 | it "returns a hash with values grouped according to the block" do
7 | EnumerableSpecs::Numerous.new(*%w(foo bar baz)).group_by{ |word| word[0..0].to_sym }.
8 | should == { :f => ["foo"], :b => ["bar", "baz"]}
9 | end
10 |
11 | it "returns an empty hash for empty enumerables" do
12 | EnumerableSpecs::Empty.new.group_by { |x| x}.should == {}
13 | end
14 |
15 | platform_is_not :enumerable_java do
16 | it "returns an Enumerator if called without a block" do
17 | EnumerableSpecs::Numerous.new.group_by.should be_an_instance_of(enumerator_class)
18 | end
19 | end
20 | end
21 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/include_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/include', __FILE__)
4 |
5 | describe "Enumerable#include?" do
6 | it_behaves_like(:enumerable_include, :include?)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/inject_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/inject', __FILE__)
4 |
5 | describe "Enumerable#inject" do
6 | it_behaves_like :enumerable_inject, :inject
7 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/map_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/collect', __FILE__)
4 |
5 | describe "Enumerable#map" do
6 | it_behaves_like(:enumerable_collect , :map)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/max_by_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#max_by" do
5 | ruby_version_is '1.8.7' do
6 | platform_is_not :enumerable_java do
7 | it "returns an enumerator if no block" do
8 | EnumerableSpecs::Numerous.new(42).max_by.should be_an_instance_of(enumerator_class)
9 | end
10 | end
11 |
12 | it "returns nil if #each yields no objects" do
13 | EnumerableSpecs::Empty.new.max_by {|o| o.nonesuch }.should == nil
14 | end
15 |
16 |
17 | it "returns the object for whom the value returned by block is the largest" do
18 | EnumerableSpecs::Numerous.new(*%w[1 2 3]).max_by {|obj| obj.to_i }.should == '3'
19 | EnumerableSpecs::Numerous.new(*%w[three five]).max_by {|obj| obj.length }.should == 'three'
20 | end
21 |
22 | it "returns the object that appears first in #each in case of a tie" do
23 | a, b, c = '1', '2', '2'
24 | EnumerableSpecs::Numerous.new(a, b, c).max_by {|obj| obj.to_i }.should equal(b)
25 | end
26 |
27 | it "uses max.<=>(current) to determine order" do
28 | a, b, c = (1..3).map{|n| EnumerableSpecs::ReverseComparable.new(n)}
29 |
30 | # Just using self here to avoid additional complexity
31 | EnumerableSpecs::Numerous.new(a, b, c).max_by {|obj| obj }.should == a
32 | end
33 |
34 | platform_is_not :enumerable_java do
35 | it "is able to return the maximum for enums that contain nils" do
36 | enum = EnumerableSpecs::Numerous.new(nil, nil, true)
37 | enum.max_by {|o| o.nil? ? 0 : 1 }.should == true
38 | enum.max_by {|o| o.nil? ? 1 : 0 }.should == nil
39 | end
40 | end
41 | end
42 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/member_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/include', __FILE__)
4 |
5 | describe "Enumerable#member?" do
6 | it_behaves_like(:enumerable_include, :member?)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/min_by_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#min_by" do
5 | ruby_version_is '1.8.7' do
6 | platform_is_not :enumerable_java do
7 | it "returns an enumerator if no block" do
8 | EnumerableSpecs::Numerous.new(42).min_by.should be_an_instance_of(enumerator_class)
9 | end
10 | end
11 |
12 | it "returns nil if #each yields no objects" do
13 | EnumerableSpecs::Empty.new.min_by {|o| o.nonesuch }.should == nil
14 | end
15 |
16 |
17 | it "returns the object for whom the value returned by block is the largest" do
18 | EnumerableSpecs::Numerous.new(*%w[3 2 1]).min_by {|obj| obj.to_i }.should == '1'
19 | EnumerableSpecs::Numerous.new(*%w[five three]).min_by {|obj| obj.length }.should == 'five'
20 | end
21 |
22 | it "returns the object that appears first in #each in case of a tie" do
23 | a, b, c = '2', '1', '1'
24 | EnumerableSpecs::Numerous.new(a, b, c).min_by {|obj| obj.to_i }.should equal(b)
25 | end
26 |
27 | it "uses min.<=>(current) to determine order" do
28 | a, b, c = (1..3).map{|n| EnumerableSpecs::ReverseComparable.new(n)}
29 |
30 | # Just using self here to avoid additional complexity
31 | EnumerableSpecs::Numerous.new(a, b, c).min_by {|obj| obj }.should == c
32 | end
33 |
34 | platform_is_not :enumerable_java do
35 | it "is able to return the maximum for enums that contain nils" do
36 | enum = EnumerableSpecs::Numerous.new(nil, nil, true)
37 | enum.min_by {|o| o.nil? ? 0 : 1 }.should == nil
38 | enum.min_by {|o| o.nil? ? 1 : 0 }.should == true
39 | end
40 | end
41 | end
42 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/minmax_by_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#minmax_by" do
5 | ruby_version_is '1.8.7' do
6 | platform_is_not :enumerable_java do
7 | it "returns an enumerator if no block" do
8 | EnumerableSpecs::Numerous.new(42).minmax_by.should be_an_instance_of(enumerator_class)
9 | end
10 | end
11 |
12 | it "returns nil if #each yields no objects" do
13 | EnumerableSpecs::Empty.new.minmax_by {|o| o.nonesuch }.should == [nil, nil]
14 | end
15 |
16 | it "returns the object for whom the value returned by block is the largest" do
17 | EnumerableSpecs::Numerous.new(*%w[1 2 3]).minmax_by {|obj| obj.to_i }.should == ['1', '3']
18 | EnumerableSpecs::Numerous.new(*%w[three five]).minmax_by {|obj| obj.length }.should == ['five', 'three']
19 | end
20 |
21 | it "returns the object that appears first in #each in case of a tie" do
22 | a, b, c, d = '1', '1', '2', '2'
23 | mm = EnumerableSpecs::Numerous.new(a, b, c, d).minmax_by {|obj| obj.to_i }
24 | mm[0].should equal(a)
25 | mm[1].should equal(c)
26 | end
27 |
28 | it "uses min/max.<=>(current) to determine order" do
29 | a, b, c = (1..3).map{|n| EnumerableSpecs::ReverseComparable.new(n)}
30 |
31 | # Just using self here to avoid additional complexity
32 | EnumerableSpecs::Numerous.new(a, b, c).minmax_by {|obj| obj }.should == [c, a]
33 | end
34 |
35 | platform_is_not :enumerable_java do
36 | it "is able to return the maximum for enums that contain nils" do
37 | enum = EnumerableSpecs::Numerous.new(nil, nil, true)
38 | enum.minmax_by {|o| o.nil? ? 0 : 1 }.should == [nil, true]
39 | end
40 | end
41 | end
42 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/minmax_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#minmax" do
5 | ruby_version_is '1.8.7' do
6 | before :each do
7 | @enum = EnumerableSpecs::Numerous.new(6, 4, 5, 10, 8)
8 |
9 | @strs = EnumerableSpecs::Numerous.new("333", "2", "60", "55555", "1010", "111")
10 | end
11 |
12 | it "min should return the minimum element" do
13 | @enum.minmax.should == [4, 10]
14 | @strs.minmax.should == ["1010", "60" ]
15 | end
16 |
17 | it "returns [nil, nil] for an empty Enumerable" do
18 | EnumerableSpecs::Empty.new.minmax.should == [nil, nil]
19 | end
20 |
21 | it "raises an ArgumentError when elements are incomparable" do
22 | lambda do
23 | EnumerableSpecs::Numerous.new(11,"22").minmax
24 | end.should raise_error(ArgumentError)
25 | lambda do
26 | EnumerableSpecs::Numerous.new(11,12,22,33).minmax{|a, b| nil}
27 | end.should raise_error(ArgumentError)
28 | end
29 |
30 | ruby_version_is ""..."1.9" do
31 | it "raises a NoMethodError for elements without #<=>" do
32 | lambda do
33 | EnumerableSpecs::Numerous.new(Object.new, Object.new).minmax
34 | end.should raise_error(NoMethodError)
35 | end
36 | end
37 |
38 | ruby_version_is "1.9" do
39 | it "raises a NoMethodError for elements without #<=>" do
40 | lambda do
41 | EnumerableSpecs::Numerous.new(BasicObject.new, BasicObject.new).minmax
42 | end.should raise_error(NoMethodError)
43 | end
44 | end
45 |
46 | it "return the minimun when using a block rule" do
47 | @enum.minmax {|a,b| b <=> a }.should == [10, 4]
48 | @strs.minmax {|a,b| a.length <=> b.length }.should == ["2", "55555"]
49 | end
50 | end
51 | end
52 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/none_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | ruby_version_is "1.8.7" do
5 | describe "Enumerable#none?" do
6 | it "returns true if none of the elements in self are true" do
7 | e = EnumerableSpecs::Numerous.new(false, nil, false)
8 | e.none?.should be_true
9 | end
10 |
11 | it "returns false if at least one of the elements in self are true" do
12 | e = EnumerableSpecs::Numerous.new(false, nil, true, false)
13 | e.none?.should be_false
14 | end
15 | end
16 |
17 | describe "Enumerable#none? with a block" do
18 | before(:each) do
19 | @e = EnumerableSpecs::Numerous.new(1,1,2,3,4)
20 | end
21 |
22 | it "passes each element to the block in turn until it returns true" do
23 | acc = []
24 | @e.none? {|e| acc << e; false }
25 | acc.should == [1,1,2,3,4]
26 | end
27 |
28 | it "stops passing elements to the block when it returns true" do
29 | acc = []
30 | @e.none? {|e| acc << e; e == 3 ? true : false }
31 | acc.should == [1,1,2,3]
32 | end
33 |
34 | it "returns true if the block never returns true" do
35 | @e.none? {|e| false }.should be_true
36 | end
37 |
38 | it "returns false if the block ever returns true" do
39 | @e.none? {|e| e == 3 ? true : false }.should be_false
40 | end
41 | end
42 | end
43 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/one_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 |
3 | describe "Enumerable#one?" do
4 | it "needs to be reviewed for spec completeness"
5 | end
6 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/partition_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#partition" do
5 | it "returns two arrays, the first containing elements for which the block is true, the second containing the rest" do
6 | EnumerableSpecs::Numerous.new.partition { |i| i % 2 == 0 }.should == [[2, 6, 4], [5, 3, 1]]
7 | end
8 |
9 | ruby_version_is "" ... "1.8.7" do
10 | it "throws LocalJumpError if called without a block" do
11 | lambda { EnumerableSpecs::Numerous.new.partition }.should raise_error(LocalJumpError)
12 | end
13 | end
14 |
15 | platform_is_not :enumerable_java do
16 | ruby_version_is "1.8.7" do
17 | it "returns an Enumerator if called without a block" do
18 | EnumerableSpecs::Numerous.new.partition.should be_an_instance_of(enumerator_class)
19 | end
20 | end
21 | end
22 | end
23 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/reduce_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/inject', __FILE__)
4 |
5 | describe "Enumerable#reduce" do
6 | ruby_version_is '1.8.7' do
7 | it_behaves_like :enumerable_inject, :reduce
8 | end
9 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/reject_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#reject" do
5 | it "returns an array of the elements for which block is false" do
6 | EnumerableSpecs::Numerous.new.reject { |i| i > 3 }.should == [2, 3, 1]
7 | entries = (1..10).to_a
8 | numerous = EnumerableSpecs::Numerous.new(*entries)
9 | numerous.reject {|i| i % 2 == 0 }.should == [1,3,5,7,9]
10 | numerous.reject {|i| true }.should == []
11 | numerous.reject {|i| false }.should == entries
12 | end
13 |
14 | ruby_version_is "" ... "1.8.7" do
15 | it "raises a LocalJumpError if no block is given" do
16 | lambda { EnumerableSpecs::Numerous.new.reject }.should raise_error(LocalJumpError)
17 | end
18 | end
19 |
20 | platform_is_not :enumerable_java do
21 | ruby_version_is "1.8.7" do
22 | it "returns an Enumerator if called without a block" do
23 | EnumerableSpecs::Numerous.new.reject.should be_an_instance_of(enumerator_class)
24 | end
25 | end
26 | end
27 | end
28 |
29 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/reverse_each_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | ruby_version_is '1.8.7' do
5 | describe "Enumerable#reverse_each" do
6 |
7 | it "traverses enum in reverse order and pass each element to block" do
8 | a=[]
9 | EnumerableSpecs::Numerous.new.reverse_each { |i| a << i }
10 | a.should == [4, 1, 6, 3, 5, 2]
11 | end
12 |
13 | it 'returns an Enumerator if no block given' do
14 | enum = EnumerableSpecs::Numerous.new.reverse_each
15 | enum.should be_an_instance_of(enumerator_class)
16 | enum.to_a.should == [4, 1, 6, 3, 5, 2]
17 | end
18 | end
19 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/select_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/find_all', __FILE__)
4 |
5 | describe "Enumerable#select" do
6 | it_behaves_like(:enumerable_find_all , :select)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/shared/collect.rb:
--------------------------------------------------------------------------------
1 | describe :enumerable_collect, :shared => true do
2 | it "returns a new array with the results of passing each element to block" do
3 | entries = [0, 1, 3, 4, 5, 6]
4 | numerous = EnumerableSpecs::Numerous.new(*entries)
5 | numerous.send(@method) { |i| i % 2 }.should == [0, 1, 1, 0, 1, 0]
6 | numerous.send(@method) { |i| i }.should == entries
7 | end
8 |
9 | ruby_version_is "" ... "1.9" do
10 | it "gathers whole arrays as elements when each yields multiple" do
11 | multi = EnumerableSpecs::YieldsMulti.new
12 | multi.send(@method) {|e| e}.should == [[1,2],[3,4,5],[6,7,8,9]]
13 | end
14 | end
15 |
16 | ruby_version_is "1.9" do
17 | it "gathers initial args as elements when each yields multiple" do
18 | multi = EnumerableSpecs::YieldsMulti.new
19 | multi.send(@method) {|e| e}.should == [1,3,6]
20 | end
21 | end
22 |
23 | ruby_version_is "" ... "1.9" do
24 | it "returns to_a when no block given" do
25 | EnumerableSpecs::Numerous.new.send(@method).should == [2, 5, 3, 6, 1, 4]
26 | end
27 | end
28 |
29 | ruby_version_is "1.9" do
30 | it "returns an enumerator when no block given" do
31 | enum = EnumerableSpecs::Numerous.new.send(@method)
32 | enum.should be_an_instance_of(enumerator_class)
33 | enum.each { |i| -i }.should == [-2, -5, -3, -6, -1, -4]
34 | end
35 | end
36 | end
37 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/shared/collect_concat.rb:
--------------------------------------------------------------------------------
1 | describe :enumerable_collect_concat, :shared => true do
2 | it "returns a new array with the results of passing each element to block, flattened one level" do
3 | numerous = EnumerableSpecs::Numerous.new(1, [2, 3], [4, [5, 6]], {:foo => :bar})
4 | numerous.send(@method){ |i| i }.should == [1, 2, 3, 4, [5, 6], {:foo => :bar}]
5 | end
6 |
7 | it "skips elements that are empty Arrays" do
8 | numerous = EnumerableSpecs::Numerous.new(1, [], 2)
9 | numerous.send(@method){ |i| i }.should == [1, 2]
10 | end
11 |
12 | it "calls to_ary but not to_a" do
13 | obj = mock('array-like')
14 | obj.should_receive(:to_ary).and_return([:foo])
15 | obj2 = mock('has a to_a')
16 | obj2.should_not_receive(:to_a)
17 |
18 | numerous = EnumerableSpecs::Numerous.new(obj, obj2)
19 | numerous.send(@method){ |i| i }.should == [:foo, obj2]
20 | end
21 |
22 | it "returns an enumerator when no block given" do
23 | enum = EnumerableSpecs::Numerous.new(1, 2).send(@method)
24 | enum.should be_an_instance_of(enumerator_class)
25 | enum.each{ |i| [i] * i }.should == [1, 2, 2]
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/shared/entries.rb:
--------------------------------------------------------------------------------
1 | describe :enumerable_entries, :shared => true do
2 | it "returns an array containing the elements" do
3 | numerous = EnumerableSpecs::Numerous.new(1, nil, 'a', 2, false, true)
4 | numerous.send(@method).should == [1, nil, "a", 2, false, true]
5 | end
6 |
7 | platform_is_not :enumerable_java do
8 | ruby_version_is '1.8.7' do
9 | it "passes arguments to each" do
10 | count = EnumerableSpecs::EachCounter.new(1, 2, 3)
11 | count.to_a(:hello, "world").should == [1, 2, 3]
12 | count.arguments_passed.should == [:hello, "world"]
13 | end
14 | end
15 | end
16 | end
17 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/shared/find_all.rb:
--------------------------------------------------------------------------------
1 | describe :enumerable_find_all, :shared => true do
2 | before :each do
3 | @elements = (1..10).to_a
4 | @numerous = EnumerableSpecs::Numerous.new(*@elements)
5 | end
6 |
7 | it "returns all elements for which the block is not false" do
8 | @numerous.send(@method) {|i| i % 3 == 0 }.should == [3, 6, 9]
9 | @numerous.send(@method) {|i| true }.should == @elements
10 | @numerous.send(@method) {|i| false }.should == []
11 | end
12 |
13 | ruby_version_is "" ... "1.8.7" do
14 | it "raises a LocalJumpError if no block given" do
15 | lambda { @numerous.send(@method) }.should raise_error(LocalJumpError)
16 | end
17 | end
18 | platform_is_not :enumerable_java do
19 | ruby_version_is "1.8.7" do
20 | it "returns an enumerator when no block given" do
21 | @numerous.send(@method).should be_an_instance_of(enumerator_class)
22 | end
23 | end
24 | end
25 |
26 | end
27 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/shared/include.rb:
--------------------------------------------------------------------------------
1 | describe :enumerable_include, :shared => true do
2 | platform_is_not :enumerable_java do
3 | it "returns true if any element == argument" do
4 | class EnumerableSpecIncludeP; def ==(obj) obj == 5; end; end
5 |
6 | elements = (0..5).to_a
7 | EnumerableSpecs::Numerous.new(*elements).send(@method,5).should == true
8 | EnumerableSpecs::Numerous.new(*elements).send(@method,10).should == false
9 | EnumerableSpecs::Numerous.new(*elements).send(@method,EnumerableSpecIncludeP.new).should == true
10 | end
11 | end
12 |
13 | platform_is_not :enumerable_java do
14 | it "returns true if any member of enum equals obj when == compare different classes (legacy rubycon)" do
15 | # equality is tested with ==
16 | EnumerableSpecs::Numerous.new(2,4,6,8,10).send(@method, 2.0).should == true
17 | EnumerableSpecs::Numerous.new(2,4,[6,8],10).send(@method, [6, 8]).should == true
18 | EnumerableSpecs::Numerous.new(2,4,[6,8],10).send(@method, [6.0, 8.0]).should == true
19 | end
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/sort_by_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#sort_by" do
5 | it "returns an array of elements ordered by the result of block" do
6 | a = EnumerableSpecs::Numerous.new("once", "upon", "a", "time")
7 | a.sort_by { |i| i[0] }.should == ["a", "once", "time", "upon"]
8 | end
9 |
10 | it "sorts the object by the given attribute" do
11 | a = EnumerableSpecs::SortByDummy.new("fooo")
12 | b = EnumerableSpecs::SortByDummy.new("bar")
13 |
14 | ar = [a, b].sort_by { |d| d.s }
15 | ar.should == [b, a]
16 | end
17 |
18 | platform_is_not :enumerable_java do
19 | ruby_version_is "1.8.7" do
20 | it "returns an Enumerator when a block is not supplied" do
21 | a = EnumerableSpecs::Numerous.new("a","b")
22 | a.sort_by.should be_an_instance_of(enumerator_class)
23 | a.to_a.should == ["a", "b"]
24 | end
25 | end
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/take_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/take', __FILE__)
4 |
5 | describe "Enumerable#take" do
6 | ruby_version_is '1.8.7' do
7 | it "requires an argument" do
8 | lambda{ EnumerableSpecs::Numerous.new.take}.should raise_error(ArgumentError)
9 | end
10 |
11 | describe "when passed an argument" do
12 | it_behaves_like :enumerable_take, :take
13 | end
14 | end
15 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/take_while_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#take_while" do
5 | ruby_version_is '1.8.7' do
6 | before :each do
7 | @enum = EnumerableSpecs::Numerous.new(3, 2, 1, :go)
8 | end
9 |
10 | platform_is_not :enumerable_java do
11 | it 'returns an Enumerator if no block given' do
12 | @enum.take_while.should be_an_instance_of(enumerator_class)
13 | end
14 | end
15 |
16 | it "returns no/all elements for {true/false} block" do
17 | @enum.take_while{true}.should == @enum.to_a
18 | @enum.take_while{false}.should == []
19 | end
20 |
21 | it "accepts returns other than true/false" do
22 | @enum.take_while{1}.should == @enum.to_a
23 | @enum.take_while{nil}.should == []
24 | end
25 |
26 | it "passes elements to the block until the first false" do
27 | a = []
28 | @enum.take_while{|obj| (a << obj).size < 3}.should == [3, 2]
29 | a.should == [3, 2, 1]
30 | end
31 |
32 | it "will only go through what's needed" do
33 | enum = EnumerableSpecs::EachCounter.new(4, 3, 2, 1, :stop)
34 | enum.take_while { |x|
35 | break 42 if x == 3
36 | true
37 | }.should == 42
38 | enum.times_yielded.should == 2
39 | end
40 |
41 | platform_is_not :enumerable_java do
42 | it "doesn't return self when it could" do
43 | a = [1,2,3]
44 | a.take_while{true}.should_not equal(a)
45 | end
46 | end
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/to_a_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 | require File.expand_path('../shared/entries', __FILE__)
4 |
5 | describe "Enumerable#to_a" do
6 | it_behaves_like(:enumerable_entries , :to_a)
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/core/enumerable/zip_spec.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../../../spec_helper', __FILE__)
2 | require File.expand_path('../fixtures/classes', __FILE__)
3 |
4 | describe "Enumerable#zip" do
5 |
6 | it "combines each element of the receiver with the element of the same index in arrays given as arguments" do
7 | EnumerableSpecs::Numerous.new(1,2,3).zip([4,5,6],[7,8,9]).should == [[1,4,7],[2,5,8],[3,6,9]]
8 | EnumerableSpecs::Numerous.new(1,2,3).zip.should == [[1],[2],[3]]
9 | end
10 |
11 | it "passes each element of the result array to a block and return nil if a block is given" do
12 | expected = [[1,4,7],[2,5,8],[3,6,9]]
13 | EnumerableSpecs::Numerous.new(1,2,3).zip([4,5,6],[7,8,9]) do |result_component|
14 | result_component.should == expected.shift
15 | end.should == nil
16 | expected.size.should == 0
17 | end
18 |
19 | it "fills resulting array with nils if an argument array is too short" do
20 | EnumerableSpecs::Numerous.new(1,2,3).zip([4,5,6], [7,8]).should == [[1,4,7],[2,5,8],[3,6,nil]]
21 | end
22 |
23 | platform_is_not :enumerable_java do
24 | ruby_version_is ''...'1.9' do
25 | it "converts arguments to arrays using #to_a" do
26 | convertable = EnumerableSpecs::ArrayConvertable.new(4,5,6)
27 | EnumerableSpecs::Numerous.new(1,2,3).zip(convertable).should == [[1,4],[2,5],[3,6]]
28 | convertable.called.should == :to_a
29 | end
30 | end
31 | end
32 |
33 | ruby_version_is '1.9' do
34 | it "converts arguments to arrays using #to_ary" do
35 | convertable = EnumerableSpecs::ArrayConvertable.new(4,5,6)
36 | EnumerableSpecs::Numerous.new(1,2,3).zip(convertable).should == [[1,4],[2,5],[3,6]]
37 | convertable.called.should == :to_ary
38 | end
39 | end
40 |
41 | end
42 |
43 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers'
2 | require 'mspec/expectations'
3 | require 'mspec/mocks'
4 | require 'mspec/runner'
5 | require 'mspec/guards'
6 | require 'mspec/helpers'
7 |
8 | # If the implementation on which the specs are run cannot
9 | # load pp from the standard library, add a pp.rb file that
10 | # defines the #pretty_inspect method on Object or Kernel.
11 | require 'pp'
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/expectations.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/expectations/expectations'
2 | require 'mspec/expectations/should'
3 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/expectations/expectations.rb:
--------------------------------------------------------------------------------
1 | class SpecExpectationNotMetError < StandardError; end
2 | class SpecExpectationNotFoundError < StandardError
3 | def message
4 | "No behavior expectation was found in the example"
5 | end
6 | end
7 |
8 | class SpecExpectation
9 | def self.fail_with(expected, actual)
10 | if expected.to_s.size + actual.to_s.size > 80
11 | message = expected.to_s.chomp + "\n" + actual.to_s
12 | else
13 | message = expected.to_s + " " + actual.to_s
14 | end
15 | Kernel.raise SpecExpectationNotMetError, message
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/expectations/should.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | NO_MATCHER_GIVEN = Object.new
3 | def should(matcher=NO_MATCHER_GIVEN)
4 | MSpec.expectation
5 | MSpec.actions :expectation, MSpec.current.state
6 | unless matcher.equal?(NO_MATCHER_GIVEN)
7 | unless matcher.matches?(self)
8 | SpecExpectation.fail_with(*matcher.failure_message)
9 | end
10 | else
11 | SpecPositiveOperatorMatcher.new(self)
12 | end
13 | end
14 |
15 | def should_not(matcher=NO_MATCHER_GIVEN)
16 | MSpec.expectation
17 | MSpec.actions :expectation, MSpec.current.state
18 | unless matcher.equal?(NO_MATCHER_GIVEN)
19 | if matcher.matches?(self)
20 | SpecExpectation.fail_with(*matcher.negative_failure_message)
21 | end
22 | else
23 | SpecNegativeOperatorMatcher.new(self)
24 | end
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/utils/ruby_name'
2 | require 'mspec/guards/background'
3 | require 'mspec/guards/bug'
4 | require 'mspec/guards/compliance'
5 | require 'mspec/guards/conflict'
6 | require 'mspec/guards/endian'
7 | require 'mspec/guards/extensions'
8 | require 'mspec/guards/feature'
9 | require 'mspec/guards/guard'
10 | require 'mspec/guards/noncompliance'
11 | require 'mspec/guards/platform'
12 | require 'mspec/guards/quarantine'
13 | require 'mspec/guards/runner'
14 | require 'mspec/guards/specified'
15 | require 'mspec/guards/support'
16 | require 'mspec/guards/superuser'
17 | require 'mspec/guards/tty'
18 | require 'mspec/guards/user'
19 | require 'mspec/guards/version'
20 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/background.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | # Some specs, notably those for Readline, will block under certain
4 | # circumstances when run as background or subprocesses. Use this guard for
5 | # such specs.
6 |
7 | class BackgroundGuard < SpecGuard
8 | def match?
9 | MSpec.mode? :background
10 | end
11 | end
12 |
13 | class Object
14 | def process_is_foreground
15 | g = BackgroundGuard.new
16 | g.name = :process_is_foreground
17 | yield if g.yield? true
18 | ensure
19 | g.unregister
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/bug.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/version'
2 |
3 | class BugGuard < VersionGuard
4 | def initialize(bug, version)
5 | @bug = bug
6 | @version = SpecVersion.new version, true
7 | self.parameters = [@bug, @version]
8 | end
9 |
10 | def match?
11 | return false if MSpec.mode? :no_ruby_bug
12 | standard? && ruby_version <= @version
13 | end
14 | end
15 |
16 | class Object
17 | def ruby_bug(bug, version)
18 | g = BugGuard.new bug, version
19 | g.name = :ruby_bug
20 | yield if g.yield? true
21 | ensure
22 | g.unregister
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/compliance.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class CompliantOnGuard < SpecGuard
4 | def match?
5 | if @args.include? :ruby
6 | raise Exception, "improper use of compliant_on guard"
7 | end
8 | standard? or implementation?(*@args)
9 | end
10 | end
11 |
12 | class NotCompliantOnGuard < SpecGuard
13 | def match?
14 | if @args.include? :ruby
15 | raise Exception, "improper use of not_compliant_on guard"
16 | end
17 | standard? or !implementation?(*@args)
18 | end
19 | end
20 |
21 | class Object
22 | def compliant_on(*args)
23 | g = CompliantOnGuard.new(*args)
24 | g.name = :compliant_on
25 | yield if g.yield?
26 | ensure
27 | g.unregister
28 | end
29 |
30 | def not_compliant_on(*args)
31 | g = NotCompliantOnGuard.new(*args)
32 | g.name = :not_compliant_on
33 | yield if g.yield?
34 | ensure
35 | g.unregister
36 | end
37 | end
38 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/conflict.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class ConflictsGuard < SpecGuard
4 | def match?
5 | # Always convert constants to symbols regardless of version.
6 | constants = Object.constants.map { |x| x.to_sym }
7 | @args.any? { |mod| constants.include? mod }
8 | end
9 | end
10 |
11 | class Object
12 | # In some cases, libraries will modify another Ruby method's
13 | # behavior. The specs for the method's behavior will then fail
14 | # if that library is loaded. This guard will not run if any of
15 | # the specified constants exist in Object.constants.
16 | def conflicts_with(*modules)
17 | g = ConflictsGuard.new(*modules)
18 | g.name = :conflicts_with
19 | yield if g.yield? true
20 | ensure
21 | g.unregister
22 | end
23 | end
24 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/endian.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | # Despite that these are inverses, the two classes are
4 | # used to simplify MSpec guard reporting modes
5 |
6 | class EndianGuard < SpecGuard
7 | def pattern
8 | @pattern ||= [1].pack('L')
9 | end
10 | private :pattern
11 | end
12 |
13 | class BigEndianGuard < EndianGuard
14 | def match?
15 | pattern[-1] == ?\001
16 | end
17 | end
18 |
19 | class LittleEndianGuard < EndianGuard
20 | def match?
21 | pattern[-1] == ?\000
22 | end
23 | end
24 |
25 | class Object
26 | def big_endian
27 | g = BigEndianGuard.new
28 | g.name = :big_endian
29 | yield if g.yield?
30 | ensure
31 | g.unregister
32 | end
33 |
34 | def little_endian
35 | g = LittleEndianGuard.new
36 | g.name = :little_endian
37 | yield if g.yield?
38 | ensure
39 | g.unregister
40 | end
41 | end
42 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/extensions.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class ExtensionsGuard < SpecGuard
4 | def match?
5 | if @args.include? :ruby
6 | raise Exception, "improper use of extended_on guard"
7 | end
8 | !standard? and implementation?(*@args)
9 | end
10 | end
11 |
12 | class Object
13 | def extended_on(*args)
14 | g = ExtensionsGuard.new(*args)
15 | g.name = :extended_on
16 | yield if g.yield?
17 | ensure
18 | g.unregister
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/feature.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class FeatureGuard < SpecGuard
4 | def self.enabled?(*features)
5 | new(*features).match?
6 | end
7 |
8 | def match?
9 | @parameters.all? { |f| MSpec.feature_enabled? f }
10 | end
11 | end
12 |
13 | class Object
14 | # Provides better documentation in the specs by
15 | # naming sets of features that work together as
16 | # a whole. Examples include :encoding, :fiber,
17 | # :continuation, :fork.
18 | #
19 | # Usage example:
20 | #
21 | # with_feature :encoding do
22 | # # specs for a method that provides aspects
23 | # # of the encoding feature
24 | # end
25 | #
26 | # Multiple features must all be enabled for the
27 | # guard to run:
28 | #
29 | # with_feature :one, :two do
30 | # # these specs will run if features :one AND
31 | # # :two are enabled.
32 | # end
33 | #
34 | # The implementation must explicitly enable a feature
35 | # by adding code like the following to the .mspec
36 | # configuration file:
37 | #
38 | # MSpec.enable_feature :encoding
39 | #
40 | def with_feature(*features)
41 | g = FeatureGuard.new(*features)
42 | g.name = :with_feature
43 | yield if g.yield?
44 | ensure
45 | g.unregister
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/noncompliance.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class NonComplianceGuard < SpecGuard
4 | def match?
5 | if @args.include? :ruby
6 | raise Exception, "improper use of deviates_on guard"
7 | end
8 | !standard? and implementation?(*@args)
9 | end
10 | end
11 |
12 | class Object
13 | def deviates_on(*args)
14 | g = NonComplianceGuard.new(*args)
15 | g.name = :deviates_on
16 | yield if g.yield?
17 | ensure
18 | g.unregister
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/platform.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class PlatformGuard < SpecGuard
4 | def self.windows?
5 | PlatformGuard.new(:os => :windows).match?
6 | end
7 |
8 | def initialize(*args)
9 | if args.last.is_a?(Hash)
10 | @options, @platforms = args.last, args[0..-2]
11 | else
12 | @options, @platforms = {}, args
13 | end
14 | self.parameters = args
15 | end
16 |
17 | def match?
18 | match = @platforms.empty? ? true : platform?(*@platforms)
19 | @options.each do |key, value|
20 | case key
21 | when :os
22 | match &&= os?(*value)
23 | when :wordsize
24 | match &&= wordsize? value
25 | end
26 | end
27 | match
28 | end
29 | end
30 |
31 | class Object
32 | def platform_is(*args)
33 | g = PlatformGuard.new(*args)
34 | g.name = :platform_is
35 | yield if g.yield?
36 | ensure
37 | g.unregister
38 | end
39 |
40 | def platform_is_not(*args)
41 | g = PlatformGuard.new(*args)
42 | g.name = :platform_is_not
43 | yield if g.yield? true
44 | ensure
45 | g.unregister
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/quarantine.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class QuarantineGuard < SpecGuard
4 | def match?
5 | false
6 | end
7 | end
8 |
9 | class Object
10 | def quarantine!
11 | g = QuarantineGuard.new
12 | g.name = :quarantine!
13 | yield if g.yield?
14 | ensure
15 | g.unregister
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/runner.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class RunnerGuard < SpecGuard
4 | def match?
5 | @args.any? do |runner|
6 | case runner
7 | when :mspec
8 | ENV['MSPEC_RUNNER'] == '1'
9 | when :rspec
10 | ENV['RSPEC_RUNNER'] == '1' or Object.const_defined?(:Spec)
11 | else
12 | false
13 | end
14 | end
15 | end
16 | end
17 |
18 | class Object
19 | def runner_is(*args)
20 | g = RunnerGuard.new(*args)
21 | g.name = :runner_is
22 | yield if g.yield?
23 | ensure
24 | g.unregister
25 | end
26 |
27 | def runner_is_not(*args)
28 | g = RunnerGuard.new(*args)
29 | g.name = :runner_is_not
30 | yield if g.yield? true
31 | ensure
32 | g.unregister
33 | end
34 | end
35 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/superuser.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class SuperUserGuard < SpecGuard
4 | def match?
5 | Process.euid == 0
6 | end
7 | end
8 |
9 | class Object
10 | def as_superuser
11 | g = SuperUserGuard.new
12 | g.name = :as_superuser
13 | yield if g.yield?
14 | ensure
15 | g.unregister
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/support.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class SupportedGuard < SpecGuard
4 | def match?
5 | if @args.include? :ruby
6 | raise Exception, "improper use of not_supported_on guard"
7 | end
8 | standard? or !implementation?(*@args)
9 | end
10 | end
11 |
12 | class Object
13 | def not_supported_on(*args)
14 | g = SupportedGuard.new(*args)
15 | g.name = :not_supported_on
16 | yield if g.yield?
17 | ensure
18 | g.unregister
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/tty.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | # If a spec depends on STDOUT being a tty, use this guard. For specs that may
4 | # block if run as a background process, see BackgroundGuard.
5 |
6 | class TTYGuard < SpecGuard
7 | def match?
8 | STDOUT.tty?
9 | end
10 | end
11 |
12 | class Object
13 | def with_tty
14 | g = TTYGuard.new
15 | g.name = :with_tty
16 | yield if g.yield?
17 | ensure
18 | g.unregister
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/user.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class UserGuard < SpecGuard
4 | def match?
5 | Process.euid != 0
6 | end
7 | end
8 |
9 | class Object
10 | def as_user
11 | g = UserGuard.new
12 | g.name = :as_user
13 | yield if g.yield?
14 | ensure
15 | g.unregister
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/guards/version.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/utils/version'
2 | require 'mspec/guards/guard'
3 |
4 | class VersionGuard < SpecGuard
5 | def initialize(version)
6 | case version
7 | when String
8 | @version = SpecVersion.new version
9 | when Range
10 | a = SpecVersion.new version.first
11 | b = SpecVersion.new version.last
12 | @version = version.exclude_end? ? a...b : a..b
13 | end
14 | self.parameters = [version]
15 | end
16 |
17 | def ruby_version
18 | @ruby_version ||= SpecVersion.new self.class.ruby_version(:full)
19 | end
20 |
21 | def match?
22 | if Range === @version
23 | @version.include? ruby_version
24 | else
25 | ruby_version >= @version
26 | end
27 | end
28 | end
29 |
30 | class Object
31 | def ruby_version_is(*args)
32 | g = VersionGuard.new(*args)
33 | g.name = :ruby_version_is
34 | yield if g.yield?
35 | ensure
36 | g.unregister
37 | end
38 | end
39 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/helpers/argv'
2 | require 'mspec/helpers/bignum'
3 | require 'mspec/helpers/const_lookup'
4 | require 'mspec/helpers/ducktype'
5 | require 'mspec/helpers/encode'
6 | require 'mspec/helpers/enumerator_class'
7 | require 'mspec/helpers/environment'
8 | require 'mspec/helpers/fixture'
9 | require 'mspec/helpers/flunk'
10 | require 'mspec/helpers/fmode'
11 | require 'mspec/helpers/fs'
12 | require 'mspec/helpers/hash'
13 | require 'mspec/helpers/infinity'
14 | require 'mspec/helpers/io'
15 | require 'mspec/helpers/language_version'
16 | require 'mspec/helpers/metaclass'
17 | require 'mspec/helpers/mock_to_path'
18 | require 'mspec/helpers/nan'
19 | require 'mspec/helpers/ruby_exe'
20 | require 'mspec/helpers/scratch'
21 | require 'mspec/helpers/tmp'
22 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/argv.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | # Convenience helper for altering ARGV. Saves the
3 | # value of ARGV and sets it to +args+. If a block
4 | # is given, yields to the block and then restores
5 | # the value of ARGV. The previously saved value of
6 | # ARGV can be restored by passing +:restore+. The
7 | # former is useful in a single spec. The latter is
8 | # useful in before/after actions. For example:
9 | #
10 | # describe "This" do
11 | # before do
12 | # argv ['a', 'b']
13 | # end
14 | #
15 | # after do
16 | # argv :restore
17 | # end
18 | #
19 | # it "does something" do
20 | # # do something
21 | # end
22 | # end
23 | #
24 | # describe "That" do
25 | # it "does something" do
26 | # argv ['a', 'b'] do
27 | # # do something
28 | # end
29 | # end
30 | # end
31 | def argv(args)
32 | if args == :restore
33 | ARGV.replace(@__mspec_saved_argv__ || [])
34 | else
35 | @__mspec_saved_argv__ = ARGV
36 | ARGV.replace args
37 | if block_given?
38 | yield
39 | argv :restore
40 | end
41 | end
42 | end
43 | end
44 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/bignum.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def bignum_value(plus=0)
3 | 0x8000_0000_0000_0000 + plus
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/const_lookup.rb:
--------------------------------------------------------------------------------
1 | module Kernel
2 | def const_lookup(c)
3 | names = c.split '::'
4 | names.shift if names.first.empty?
5 | names.inject(Object) do |m, n|
6 | defined = RUBY_VERSION =~ /^1.9/ ? m.const_defined?(n, false) : m.const_defined?(n)
7 | defined ? m.const_get(n) : m.const_missing(n)
8 | end
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/ducktype.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def responds_to(sym)
3 | metaclass.class_eval <<-END
4 | def respond_to?(sym, include_private=false)
5 | sym.to_sym == #{sym.to_sym.inspect} ? true : super
6 | end
7 | END
8 | end
9 |
10 | def does_not_respond_to(sym)
11 | metaclass.class_eval <<-END
12 | def respond_to?(sym, include_private=false)
13 | sym.to_sym == #{sym.to_sym.inspect} ? false : super
14 | end
15 | END
16 | end
17 |
18 | def undefine(sym)
19 | metaclass.class_eval <<-END
20 | undef_method #{sym.to_sym.inspect}
21 | END
22 | end
23 |
24 | def fake!(sym, value=nil)
25 | responds_to sym
26 |
27 | metaclass.class_eval <<-END
28 | def method_missing(sym, *args)
29 | return #{value.inspect} if sym.to_sym == #{sym.to_sym.inspect}
30 | end
31 | END
32 | end
33 | end
34 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/encode.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/feature'
2 |
3 | class Object
4 | # Helper to handle String encodings. The +str+ and +encoding+ parameters
5 | # must be Strings and an ArgumentError will be raised if not. This ensures
6 | # that the encode() helper can be used regardless of whether Encoding exits.
7 | # The helper is a no-op (i.e. passes through +str+ unmodified) if the
8 | # :encoding feature is not enabled (see with_feature guard). If the
9 | # :encoding feature is enabled, +str+.force_encoding(+encoding+) is called.
10 | def encode(str, encoding)
11 | unless str.is_a? String and encoding.is_a? String
12 | raise ArgumentError, "encoding name must be a String"
13 | end
14 |
15 | if FeatureGuard.enabled? :encoding
16 | str.force_encoding encoding
17 | end
18 |
19 | str
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/enumerator_class.rb:
--------------------------------------------------------------------------------
1 | class Object
2 |
3 | # Returns the Enumerator class (either Enumerator or Enumerable::Enumerator)
4 | # depending of the version.
5 | #
6 | def enumerator_class
7 | SpecVersion.new(RUBY_VERSION) < "1.9" ? Enumerable::Enumerator : Enumerator
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/environment.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class Object
4 | def env
5 | env = ""
6 | if PlatformGuard.windows?
7 | env = Hash[*`cmd.exe /C set`.split("\n").map { |e| e.split("=", 2) }.flatten]
8 | else
9 | env = Hash[*`env`.split("\n").map { |e| e.split("=", 2) }.flatten]
10 | end
11 | env
12 | end
13 |
14 | def windows_env_echo(var)
15 | `cmd.exe /C ECHO %#{var}%`.strip
16 | end
17 |
18 | def username
19 | user = ""
20 | if PlatformGuard.windows?
21 | user = windows_env_echo('USERNAME')
22 | else
23 | user = `whoami`.strip
24 | end
25 | user
26 | end
27 |
28 | def home_directory
29 | return ENV['HOME'] unless PlatformGuard.windows?
30 | windows_env_echo('HOMEDRIVE') + windows_env_echo('HOMEPATH')
31 | end
32 | end
33 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/fixture.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | # Returns the name of a fixture file by adjoining the directory
3 | # of the +dir+ argument with "fixtures" and the contents of the
4 | # +args+ array. For example,
5 | #
6 | # +dir+ == "some/path"
7 | #
8 | # and
9 | #
10 | # +args+ == ["dir", "file.txt"]
11 | #
12 | # then the result is the expanded path of
13 | #
14 | # "some/fixtures/dir/file.txt".
15 | def fixture(dir, *args)
16 | path = File.dirname(dir)
17 | path = path[0..-7] if path[-7..-1] == "/shared"
18 | dir = path[-9..-1] == "/fixtures" ? "" : "fixtures"
19 | File.expand_path(File.join(path, dir, args))
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/flunk.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def flunk(msg="This example is a failure")
3 | SpecExpectation.fail_with "Failed:", msg
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/fmode.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/feature'
2 |
3 | class Object
4 | # This helper simplifies passing file access modes regardless of
5 | # whether the :encoding feature is enabled. Only the access specifier
6 | # itself will be returned if :encoding is not enabled. Otherwise,
7 | # the full mode string will be returned (i.e. the helper is a no-op).
8 | def fmode(mode)
9 | if FeatureGuard.enabled? :encoding
10 | mode
11 | else
12 | mode.split(':').first
13 | end
14 | end
15 | end
16 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/fs.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | # Copies a file
3 | def cp(source, dest)
4 | File.open(dest, "w") do |d|
5 | File.open(source, "r") do |s|
6 | while data = s.read(1024)
7 | d.write data
8 | end
9 | end
10 | end
11 | end
12 |
13 | # Creates each directory in path that does not exist.
14 | def mkdir_p(path)
15 | parts = File.expand_path(path).split %r[/|\\]
16 | name = parts.shift
17 | parts.each do |part|
18 | name = File.join name, part
19 |
20 | if File.file? name
21 | raise ArgumentError, "path component of #{path} is a file"
22 | end
23 |
24 | Dir.mkdir name unless File.directory? name
25 | end
26 | end
27 |
28 | # Recursively removes all files and directories in +path+
29 | # if +path+ is a directory. Removes the file if +path+ is
30 | # a file.
31 | def rm_r(*paths)
32 | paths.each do |path|
33 | path = File.expand_path path
34 |
35 | prefix = SPEC_TEMP_DIR
36 | unless path[0, prefix.size] == prefix
37 | raise ArgumentError, "#{path} is not prefixed by #{prefix}"
38 | end
39 |
40 | if File.directory? path
41 | Dir.entries(path).each { |x| rm_r "#{path}/#{x}" unless x =~ /^\.\.?$/ }
42 | Dir.rmdir path
43 | elsif File.exists? path
44 | File.delete path
45 | end
46 | end
47 | end
48 |
49 | # Creates a file +name+. Creates the directory for +name+
50 | # if it does not exist.
51 | def touch(name, mode="w")
52 | mkdir_p File.dirname(name)
53 |
54 | File.open(name, mode) do |f|
55 | yield f if block_given?
56 | end
57 | end
58 | end
59 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/hash.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | # The following helpers provide a level of indirection for running the specs
3 | # against a Hash implementation that has a different name than Hash.
4 |
5 | # Returns the Hash class.
6 | unless method_defined?(:hash_class)
7 | def hash_class
8 | Hash
9 | end
10 | end
11 |
12 | # Returns a new instance of hash_class.
13 | def new_hash(*args, &block)
14 | if block
15 | hash_class.new(&block)
16 | elsif args.size == 1
17 | value = args.first
18 | if value.is_a?(Hash) or value.is_a?(hash_class)
19 | hash_class[value]
20 | else
21 | hash_class.new value
22 | end
23 | else
24 | hash_class[*args]
25 | end
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/infinity.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def infinity_value
3 | 1/0.0
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/io.rb:
--------------------------------------------------------------------------------
1 | class IOStub < String
2 | def write(*str)
3 | self << str.join
4 | end
5 |
6 | def print(*str)
7 | write(str.join + $\.to_s)
8 | end
9 |
10 | def puts(*str)
11 | write(str.collect { |s| s.to_s.chomp }.concat([nil]).join("\n"))
12 | end
13 |
14 | def printf(format, *args)
15 | self << sprintf(format, *args)
16 | end
17 |
18 | def flush
19 | self
20 | end
21 | end
22 |
23 | class Object
24 | # Creates a "bare" file descriptor (i.e. one that is not associated
25 | # with any Ruby object). The file descriptor can safely be passed
26 | # to IO.new without creating a Ruby object alias to the fd.
27 | def new_fd(name, mode="w:utf-8")
28 | IO.sysopen name, fmode(mode)
29 | end
30 |
31 | # Creates an IO instance for a temporary file name. The file
32 | # must be deleted.
33 | def new_io(name, mode="w:utf-8")
34 | IO.new new_fd(name, fmode(mode)), fmode(mode)
35 | end
36 | end
37 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/language_version.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/guard'
2 |
3 | class Object
4 | # Helper for syntax-sensitive specs. The specs should be placed in a file in
5 | # the +versions+ subdirectory. For example, suppose language/method_spec.rb
6 | # contains specs whose syntax depends on the Ruby version. In the
7 | # language/method_spec.rb use the helper as follows:
8 | #
9 | # language_version __FILE__, "method"
10 | #
11 | # Then add a file "language/versions/method_1.8.rb" for the specs that are
12 | # syntax-compatible with Ruby 1.8.x.
13 | #
14 | # The most version-specific file will be loaded. If the version is 1.8.6,
15 | # "method_1.8.6.rb" will be loaded if it exists, otherwise "method_1.8.rb"
16 | # will be loaded if it exists.
17 | def language_version(dir, name)
18 | path = File.dirname(File.expand_path(dir))
19 |
20 | [SpecGuard.ruby_version(:tiny), SpecGuard.ruby_version].each do |version|
21 | file = File.join path, "versions", "#{name}_#{version}.rb"
22 | if File.exists? file
23 | require file
24 | break
25 | end
26 | end
27 |
28 | nil
29 | end
30 | end
31 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/metaclass.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | unless method_defined? :metaclass
3 | def metaclass
4 | class << self; self; end
5 | end
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/mock_to_path.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def mock_to_path(path)
3 | obj = mock('path')
4 | obj.should_receive(:to_path).and_return(path)
5 | obj
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/nan.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def nan_value
3 | 0/0.0
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/scratch.rb:
--------------------------------------------------------------------------------
1 | module ScratchPad
2 | def self.clear
3 | @record = nil
4 | end
5 |
6 | def self.record(arg)
7 | @record = arg
8 | end
9 |
10 | def self.<<(arg)
11 | @record << arg
12 | end
13 |
14 | def self.recorded
15 | @record
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/helpers/tmp.rb:
--------------------------------------------------------------------------------
1 | # Creates a temporary directory in the current working directory
2 | # for temporary files created while running the specs. All specs
3 | # should clean up any temporary files created so that the temp
4 | # directory is empty when the process exits.
5 |
6 | SPEC_TEMP_DIR = "#{File.expand_path(Dir.pwd)}/rubyspec_temp"
7 |
8 | SPEC_TEMP_UNIQUIFIER = "0"
9 |
10 | at_exit do
11 | begin
12 | Dir.delete SPEC_TEMP_DIR if File.directory? SPEC_TEMP_DIR
13 | rescue SystemCallError
14 | STDERR.puts <<-EOM
15 |
16 | -----------------------------------------------------
17 | The rubyspec temp directory is not empty. Ensure that
18 | all specs are cleaning up temporary files.
19 | -----------------------------------------------------
20 |
21 | EOM
22 | rescue Object => e
23 | STDERR.puts "failed to remove spec temp directory"
24 | STDERR.puts e.message
25 | end
26 | end
27 |
28 | class Object
29 | def tmp(name, uniquify=true)
30 | Dir.mkdir SPEC_TEMP_DIR unless File.exists? SPEC_TEMP_DIR
31 |
32 | if uniquify and !name.empty?
33 | slash = name.rindex "/"
34 | index = slash ? slash + 1 : 0
35 | name.insert index, "#{SPEC_TEMP_UNIQUIFIER.succ!}-"
36 | end
37 |
38 | File.join SPEC_TEMP_DIR, name
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/base'
2 | require 'mspec/matchers/be_an_instance_of'
3 | require 'mspec/matchers/be_ancestor_of'
4 | require 'mspec/matchers/be_close'
5 | require 'mspec/matchers/be_empty'
6 | require 'mspec/matchers/be_false'
7 | require 'mspec/matchers/be_kind_of'
8 | require 'mspec/matchers/be_nil'
9 | require 'mspec/matchers/be_true'
10 | require 'mspec/matchers/complain'
11 | require 'mspec/matchers/eql'
12 | require 'mspec/matchers/equal'
13 | require 'mspec/matchers/equal_element'
14 | require 'mspec/matchers/equal_utf16'
15 | require 'mspec/matchers/have_constant'
16 | require 'mspec/matchers/have_class_variable'
17 | require 'mspec/matchers/have_data'
18 | require 'mspec/matchers/have_instance_method'
19 | require 'mspec/matchers/have_instance_variable'
20 | require 'mspec/matchers/have_method'
21 | require 'mspec/matchers/have_private_instance_method'
22 | require 'mspec/matchers/have_protected_instance_method'
23 | require 'mspec/matchers/have_public_instance_method'
24 | require 'mspec/matchers/include'
25 | require 'mspec/matchers/match_yaml'
26 | require 'mspec/matchers/raise_error'
27 | require 'mspec/matchers/output'
28 | require 'mspec/matchers/output_to_fd'
29 | require 'mspec/matchers/respond_to'
30 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_an_instance_of.rb:
--------------------------------------------------------------------------------
1 | class BeAnInstanceOfMatcher
2 | def initialize(expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @actual.instance_of?(@expected)
9 | end
10 |
11 | def failure_message
12 | ["Expected #{@actual.inspect} (#{@actual.class})",
13 | "to be an instance of #{@expected}"]
14 | end
15 |
16 | def negative_failure_message
17 | ["Expected #{@actual.inspect} (#{@actual.class})",
18 | "not to be an instance of #{@expected}"]
19 | end
20 | end
21 |
22 | class Object
23 | def be_an_instance_of(expected)
24 | BeAnInstanceOfMatcher.new(expected)
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_ancestor_of.rb:
--------------------------------------------------------------------------------
1 | class BeAncestorOfMatcher
2 | def initialize(expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @expected.ancestors.include? @actual
9 | end
10 |
11 | def failure_message
12 | ["Expected #{@actual}", "to be an ancestor of #{@expected}"]
13 | end
14 |
15 | def negative_failure_message
16 | ["Expected #{@actual}", "not to be an ancestor of #{@expected}"]
17 | end
18 | end
19 |
20 | class Object
21 | def be_ancestor_of(expected)
22 | BeAncestorOfMatcher.new(expected)
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_close.rb:
--------------------------------------------------------------------------------
1 | TOLERANCE = 0.00003 unless Object.const_defined?(:TOLERANCE)
2 |
3 | class BeCloseMatcher
4 | def initialize(expected, tolerance)
5 | @expected = expected
6 | @tolerance = tolerance
7 | end
8 |
9 | def matches?(actual)
10 | @actual = actual
11 | (@actual - @expected).abs < @tolerance
12 | end
13 |
14 | def failure_message
15 | ["Expected #{@expected}", "to be within +/- #{@tolerance} of #{@actual}"]
16 | end
17 |
18 | def negative_failure_message
19 | ["Expected #{@expected}", "not to be within +/- #{@tolerance} of #{@actual}"]
20 | end
21 | end
22 |
23 | class Object
24 | def be_close(expected, tolerance)
25 | BeCloseMatcher.new(expected, tolerance)
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_empty.rb:
--------------------------------------------------------------------------------
1 | class BeEmptyMatcher
2 | def matches?(actual)
3 | @actual = actual
4 | @actual.empty?
5 | end
6 |
7 | def failure_message
8 | ["Expected #{@actual.inspect}", "to be empty"]
9 | end
10 |
11 | def negative_failure_message
12 | ["Expected #{@actual.inspect}", "not to be empty"]
13 | end
14 | end
15 |
16 | class Object
17 | def be_empty
18 | BeEmptyMatcher.new
19 | end
20 | end
21 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_false.rb:
--------------------------------------------------------------------------------
1 | class BeFalseMatcher
2 | def matches?(actual)
3 | @actual = actual
4 | @actual == false
5 | end
6 |
7 | def failure_message
8 | ["Expected #{@actual.inspect}", "to be false"]
9 | end
10 |
11 | def negative_failure_message
12 | ["Expected #{@actual.inspect}", "not to be false"]
13 | end
14 | end
15 |
16 | class Object
17 | def be_false
18 | BeFalseMatcher.new
19 | end
20 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_kind_of.rb:
--------------------------------------------------------------------------------
1 | class BeKindOfMatcher
2 | def initialize(expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @actual.is_a?(@expected)
9 | end
10 |
11 | def failure_message
12 | ["Expected #{@actual.inspect} (#{@actual.class})", "to be kind of #{@expected}"]
13 | end
14 |
15 | def negative_failure_message
16 | ["Expected #{@actual.inspect} (#{@actual.class})", "not to be kind of #{@expected}"]
17 | end
18 | end
19 |
20 | class Object
21 | def be_kind_of(expected)
22 | BeKindOfMatcher.new(expected)
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_nil.rb:
--------------------------------------------------------------------------------
1 | class BeNilMatcher
2 | def matches?(actual)
3 | @actual = actual
4 | @actual.nil?
5 | end
6 |
7 | def failure_message
8 | ["Expected #{@actual.inspect}", "to be nil"]
9 | end
10 |
11 | def negative_failure_message
12 | ["Expected #{@actual.inspect}", "not to be nil"]
13 | end
14 | end
15 |
16 | class Object
17 | def be_nil
18 | BeNilMatcher.new
19 | end
20 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/be_true.rb:
--------------------------------------------------------------------------------
1 | class BeTrueMatcher
2 | def matches?(actual)
3 | @actual = actual
4 | @actual == true
5 | end
6 |
7 | def failure_message
8 | ["Expected #{@actual.inspect}", "to be true"]
9 | end
10 |
11 | def negative_failure_message
12 | ["Expected #{@actual.inspect}", "not to be true"]
13 | end
14 | end
15 |
16 | class Object
17 | def be_true
18 | BeTrueMatcher.new
19 | end
20 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/complain.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/helpers/io'
2 |
3 | class ComplainMatcher
4 | def initialize(complaint)
5 | @complaint = complaint
6 | end
7 |
8 | def matches?(proc)
9 | @saved_err = $stderr
10 | @stderr = $stderr = IOStub.new
11 | @verbose = $VERBOSE
12 | $VERBOSE = false
13 |
14 | proc.call
15 |
16 | unless @complaint.nil?
17 | case @complaint
18 | when Regexp
19 | return false unless $stderr =~ @complaint
20 | else
21 | return false unless $stderr == @complaint
22 | end
23 | end
24 |
25 | return $stderr.empty? ? false : true
26 | ensure
27 | $VERBOSE = @verbose
28 | $stderr = @saved_err
29 | end
30 |
31 | def failure_message
32 | if @complaint.nil?
33 | ["Expected a warning", "but received none"]
34 | elsif @complaint.kind_of? Regexp
35 | ["Expected warning to match:", @complaint.inspect]
36 | else
37 | ["Expected warning: #{@complaint.inspect}", "but got: #{@stderr.chomp.inspect}"]
38 | end
39 | end
40 |
41 | def negative_failure_message
42 | if @complaint.nil?
43 | ["Unexpected warning: ", @stderr.chomp.inspect]
44 | elsif @complaint.kind_of? Regexp
45 | ["Expected warning not to match:", @complaint.inspect]
46 | else
47 | ["Expected warning: #{@complaint.inspect}", "but got: #{@stderr.chomp.inspect}"]
48 | end
49 | end
50 | end
51 |
52 | class Object
53 | def complain(complaint=nil)
54 | ComplainMatcher.new(complaint)
55 | end
56 | end
57 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/eql.rb:
--------------------------------------------------------------------------------
1 | class EqlMatcher
2 | def initialize(expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @actual.eql?(@expected)
9 | end
10 |
11 | def failure_message
12 | ["Expected #{@actual.pretty_inspect}",
13 | "to have same value and type as #{@expected.pretty_inspect}"]
14 | end
15 |
16 | def negative_failure_message
17 | ["Expected #{@actual.pretty_inspect}",
18 | "not to have same value or type as #{@expected.pretty_inspect}"]
19 | end
20 | end
21 |
22 | class Object
23 | def eql(expected)
24 | EqlMatcher.new(expected)
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/equal.rb:
--------------------------------------------------------------------------------
1 | class EqualMatcher
2 | def initialize(expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @actual.equal?(@expected)
9 | end
10 |
11 | def failure_message
12 | ["Expected #{@actual.pretty_inspect}",
13 | "to be identical to #{@expected.pretty_inspect}"]
14 | end
15 |
16 | def negative_failure_message
17 | ["Expected #{@actual.pretty_inspect}",
18 | "not to be identical to #{@expected.pretty_inspect}"]
19 | end
20 | end
21 |
22 | class Object
23 | def equal(expected)
24 | EqualMatcher.new(expected)
25 | end
26 | end
27 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/equal_utf16.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/helpers/encode'
2 |
3 | class EqualUtf16Matcher
4 | def initialize(expected)
5 | @expected = Array(expected).map { |x| encode x, "binary" }
6 | end
7 |
8 | def matches?(actual)
9 | @actual = Array(actual).map { |x| encode x, "binary" }
10 | @actual == @expected || @actual == expected_swapped
11 | end
12 |
13 | def expected_swapped
14 | @expected_swapped ||= @expected.map { |x| x.to_str.gsub(/(.)(.)/, '\2\1') }
15 | end
16 |
17 | def failure_message
18 | ["Expected #{@actual.pretty_inspect}",
19 | "to equal #{@expected.pretty_inspect} or #{expected_swapped.pretty_inspect}"]
20 | end
21 |
22 | def negative_failure_message
23 | ["Expected #{@actual.pretty_inspect}",
24 | "not to equal #{@expected.pretty_inspect} nor #{expected_swapped.pretty_inspect}"]
25 | end
26 | end
27 |
28 | class Object
29 | def equal_utf16(expected)
30 | EqualUtf16Matcher.new(expected)
31 | end
32 | end
33 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_class_variable.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/variable'
2 |
3 | class HaveClassVariableMatcher < VariableMatcher
4 | self.variables_method = :class_variables
5 | self.description = 'class variable'
6 | end
7 |
8 | class Object
9 | def have_class_variable(variable)
10 | HaveClassVariableMatcher.new(variable)
11 | end
12 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_constant.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/variable'
2 |
3 | class HaveConstantMatcher < VariableMatcher
4 | self.variables_method = :constants
5 | self.description = 'constant'
6 | end
7 |
8 | class Object
9 | def have_constant(variable)
10 | HaveConstantMatcher.new(variable)
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_data.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/guards/feature'
2 | require 'mspec/helpers/fmode'
3 |
4 | class HaveDataMatcher
5 | def initialize(data)
6 | @data = data
7 | end
8 |
9 | def matches?(name)
10 | @name = name
11 |
12 | if FeatureGuard.enabled? :encoding
13 | size = @data.bytesize
14 | else
15 | size = @data.size
16 | end
17 |
18 | File.open @name, fmode("rb:binary") do |f|
19 | return f.read(size) == @data
20 | end
21 | end
22 |
23 | def failure_message
24 | ["Expected #{@name}",
25 | "to have data #{@data.pretty_inspect}"]
26 | end
27 |
28 | def negative_failure_message
29 | ["Expected #{@name}",
30 | "not to have data #{@data.pretty_inspect}"]
31 | end
32 | end
33 |
34 | class Object
35 | # Opens a file specified by the string the matcher is called on
36 | # and compares the +data+ passed to the matcher with the contents
37 | # of the file. Expects to match the first N bytes of the file
38 | # with +data+. For example, suppose @name is the name of a file:
39 | #
40 | # @name.should have_data("123")
41 | #
42 | # passes if the file @name has "123" as the first 3 bytes. The
43 | # file can contain more bytes than +data+. The extra bytes do not
44 | # affect the result.
45 | def have_data(data)
46 | HaveDataMatcher.new(data)
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_instance_method.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/method'
2 |
3 | class HaveInstanceMethodMatcher < MethodMatcher
4 | def matches?(mod)
5 | @mod = mod
6 | mod.instance_methods(@include_super).include? @method
7 | end
8 |
9 | def failure_message
10 | ["Expected #{@mod} to have instance method '#{@method.to_s}'",
11 | "but it does not"]
12 | end
13 |
14 | def negative_failure_message
15 | ["Expected #{@mod} NOT to have instance method '#{@method.to_s}'",
16 | "but it does"]
17 | end
18 | end
19 |
20 | class Object
21 | def have_instance_method(method, include_super=true)
22 | HaveInstanceMethodMatcher.new method, include_super
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_instance_variable.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/variable'
2 |
3 | class HaveInstanceVariableMatcher < VariableMatcher
4 | self.variables_method = :instance_variables
5 | self.description = 'instance variable'
6 | end
7 |
8 | class Object
9 | def have_instance_variable(variable)
10 | HaveInstanceVariableMatcher.new(variable)
11 | end
12 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_method.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/method'
2 |
3 | class HaveMethodMatcher < MethodMatcher
4 | def matches?(mod)
5 | @mod = mod
6 | @mod.methods(@include_super).include? @method
7 | end
8 |
9 | def failure_message
10 | ["Expected #{@mod} to have method '#{@method.to_s}'",
11 | "but it does not"]
12 | end
13 |
14 | def negative_failure_message
15 | ["Expected #{@mod} NOT to have method '#{@method.to_s}'",
16 | "but it does"]
17 | end
18 | end
19 |
20 | class Object
21 | def have_method(method, include_super=true)
22 | HaveMethodMatcher.new method, include_super
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_private_instance_method.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/method'
2 |
3 | class HavePrivateInstanceMethodMatcher < MethodMatcher
4 | def matches?(mod)
5 | @mod = mod
6 | mod.private_instance_methods(@include_super).include? @method
7 | end
8 |
9 | def failure_message
10 | ["Expected #{@mod} to have private instance method '#{@method.to_s}'",
11 | "but it does not"]
12 | end
13 |
14 | def negative_failure_message
15 | ["Expected #{@mod} NOT to have private instance method '#{@method.to_s}'",
16 | "but it does"]
17 | end
18 | end
19 |
20 | class Object
21 | def have_private_instance_method(method, include_super=true)
22 | HavePrivateInstanceMethodMatcher.new method, include_super
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_protected_instance_method.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/method'
2 |
3 | class HaveProtectedInstanceMethodMatcher < MethodMatcher
4 | def matches?(mod)
5 | @mod = mod
6 | mod.protected_instance_methods(@include_super).include? @method
7 | end
8 |
9 | def failure_message
10 | ["Expected #{@mod} to have protected instance method '#{@method.to_s}'",
11 | "but it does not"]
12 | end
13 |
14 | def negative_failure_message
15 | ["Expected #{@mod} NOT to have protected instance method '#{@method.to_s}'",
16 | "but it does"]
17 | end
18 | end
19 |
20 | class Object
21 | def have_protected_instance_method(method, include_super=true)
22 | HaveProtectedInstanceMethodMatcher.new method, include_super
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/have_public_instance_method.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/method'
2 |
3 | class HavePublicInstanceMethodMatcher < MethodMatcher
4 | def matches?(mod)
5 | @mod = mod
6 | mod.public_instance_methods(@include_super).include? @method
7 | end
8 |
9 | def failure_message
10 | ["Expected #{@mod} to have public instance method '#{@method.to_s}'",
11 | "but it does not"]
12 | end
13 |
14 | def negative_failure_message
15 | ["Expected #{@mod} NOT to have public instance method '#{@method.to_s}'",
16 | "but it does"]
17 | end
18 | end
19 |
20 | class Object
21 | def have_public_instance_method(method, include_super=true)
22 | HavePublicInstanceMethodMatcher.new method, include_super
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/include.rb:
--------------------------------------------------------------------------------
1 | class IncludeMatcher
2 | def initialize(*expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @expected.each do |e|
9 | @element = e
10 | unless @actual.include?(e)
11 | return false
12 | end
13 | end
14 | return true
15 | end
16 |
17 | def failure_message
18 | ["Expected #{@actual.inspect}", "to include #{@element.inspect}"]
19 | end
20 |
21 | def negative_failure_message
22 | ["Expected #{@actual.inspect}", "not to include #{@element.inspect}"]
23 | end
24 | end
25 |
26 | # Cannot override #include at the toplevel in MRI
27 | module MSpec
28 | def include(*expected)
29 | IncludeMatcher.new(*expected)
30 | end
31 | module_function :include
32 | end
33 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/match_yaml.rb:
--------------------------------------------------------------------------------
1 | class MatchYAMLMatcher
2 |
3 | def initialize(expected)
4 | if valid_yaml?(expected)
5 | @expected = expected
6 | else
7 | @expected = expected.to_yaml
8 | end
9 | end
10 |
11 | def matches?(actual)
12 | @actual = actual
13 | clean_yaml(@actual) == @expected
14 | end
15 |
16 | def failure_message
17 | ["Expected #{@actual.inspect}", " to match #{@expected.inspect}"]
18 | end
19 |
20 | def negative_failure_message
21 | ["Expected #{@actual.inspect}", " to match #{@expected.inspect}"]
22 | end
23 |
24 | protected
25 |
26 | def clean_yaml(yaml)
27 | yaml.gsub(/([^-])\s+\n/, "\\1\n")
28 | end
29 |
30 | def valid_yaml?(obj)
31 | require 'yaml'
32 | begin
33 | YAML.load(obj)
34 | rescue
35 | false
36 | else
37 | true
38 | end
39 | end
40 | end
41 |
42 | class Object
43 | def match_yaml(expected)
44 | MatchYAMLMatcher.new(expected)
45 | end
46 | end
47 |
48 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/method.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/stringsymboladapter'
2 |
3 | class MethodMatcher
4 | include StringSymbolAdapter
5 |
6 | def initialize(method, include_super=true)
7 | @include_super = include_super
8 | @method = convert_name method
9 | end
10 |
11 | def matches?(mod)
12 | raise Exception, "define #matches? in the subclass"
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/output.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/helpers/io'
2 |
3 | class OutputMatcher
4 | def initialize(stdout, stderr)
5 | @out = stdout
6 | @err = stderr
7 | end
8 |
9 | def matches?(proc)
10 | @saved_out = $stdout
11 | @saved_err = $stderr
12 | @stdout = $stdout = IOStub.new
13 | @stderr = $stderr = IOStub.new
14 |
15 | proc.call
16 |
17 | unless @out.nil?
18 | case @out
19 | when Regexp
20 | return false unless $stdout =~ @out
21 | else
22 | return false unless $stdout == @out
23 | end
24 | end
25 |
26 | unless @err.nil?
27 | case @err
28 | when Regexp
29 | return false unless $stderr =~ @err
30 | else
31 | return false unless $stderr == @err
32 | end
33 | end
34 |
35 | return true
36 | ensure
37 | $stdout = @saved_out
38 | $stderr = @saved_err
39 | end
40 |
41 | def failure_message
42 | expected_out = "\n"
43 | actual_out = "\n"
44 | unless @out.nil?
45 | expected_out << " $stdout: #{@out.inspect}\n"
46 | actual_out << " $stdout: #{@stdout.chomp.inspect}\n"
47 | end
48 | unless @err.nil?
49 | expected_out << " $stderr: #{@err.inspect}\n"
50 | actual_out << " $stderr: #{@stderr.chomp.inspect}\n"
51 | end
52 | ["Expected:#{expected_out}", " got:#{actual_out}"]
53 | end
54 |
55 | def negative_failure_message
56 | out = ""
57 | out << " $stdout: #{@stdout.chomp.dump}\n" unless @out.nil?
58 | out << " $stderr: #{@stderr.chomp.dump}\n" unless @err.nil?
59 | ["Expected output not to be:\n", out]
60 | end
61 | end
62 |
63 | class Object
64 | def output(stdout=nil, stderr=nil)
65 | OutputMatcher.new(stdout, stderr)
66 | end
67 | end
68 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/output_to_fd.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/helpers/tmp'
2 | require 'fileutils'
3 |
4 | # Lower-level output speccing mechanism for a single
5 | # output stream. Unlike OutputMatcher which provides
6 | # methods to capture the output, we actually replace
7 | # the FD itself so that there is no reliance on a
8 | # certain method being used.
9 | class OutputToFDMatcher
10 | def initialize(expected, to)
11 | @to, @expected = to, expected
12 |
13 | case @to
14 | when STDOUT
15 | @to_name = "STDOUT"
16 | when STDERR
17 | @to_name = "STDERR"
18 | when IO
19 | @to_name = @to.object_id.to_s
20 | else
21 | raise ArgumentError, "#{@to.inspect} is not a supported output target"
22 | end
23 | end
24 |
25 | def matches?(block)
26 | old_to = @to.dup
27 | out = File.open(tmp("mspec_output_to_#{$$}_#{Time.now.to_i}"), 'w+')
28 |
29 | # Replacing with a file handle so that Readline etc. work
30 | @to.reopen out
31 |
32 | block.call
33 |
34 | ensure
35 | begin
36 | @to.reopen old_to
37 |
38 | out.rewind
39 | @actual = out.read
40 |
41 | case @expected
42 | when Regexp
43 | return !(@actual =~ @expected).nil?
44 | else
45 | return @actual == @expected
46 | end
47 |
48 | # Clean up
49 | ensure
50 | out.close unless out.closed?
51 | FileUtils.rm out.path
52 | end
53 |
54 | return true
55 | end
56 |
57 | def failure_message()
58 | ["Expected (#{@to_name}): #{@expected.inspect}\n",
59 | "#{'but got'.rjust(@to_name.length + 10)}: #{@actual.inspect}\nBacktrace"]
60 | end
61 |
62 | def negative_failure_message()
63 | ["Expected output (#{@to_name}) to NOT be:\n", @actual.inspect]
64 | end
65 | end
66 |
67 | class Object
68 | def output_to_fd(what, where = STDOUT)
69 | OutputToFDMatcher.new what, where
70 | end
71 | end
72 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/raise_error.rb:
--------------------------------------------------------------------------------
1 | class RaiseErrorMatcher
2 | def initialize(exception, message, &block)
3 | @exception = exception
4 | @message = message
5 | @block = block
6 | end
7 |
8 | def matches?(proc)
9 | proc.call
10 | return false
11 | rescue Exception => @actual
12 | return false unless @exception === @actual
13 | if @message then
14 | case @message
15 | when String then
16 | return false if @message != @actual.message
17 | when Regexp then
18 | return false if @message !~ @actual.message
19 | end
20 | end
21 |
22 | @block[@actual] if @block
23 |
24 | return true
25 | end
26 |
27 | def failure_message
28 | message = ["Expected #{@exception}#{%[ (#{@message})] if @message}"]
29 |
30 | if @actual then
31 | message << "but got #{@actual.class}#{%[ (#{@actual.message})] if @actual.message}"
32 | else
33 | message << "but no exception was raised"
34 | end
35 |
36 | message
37 | end
38 |
39 | def negative_failure_message
40 | ["Expected to not get #{@exception}#{%[ (#{@message})] if @message}", ""]
41 | end
42 | end
43 |
44 | class Object
45 | def raise_error(exception=Exception, message=nil, &block)
46 | RaiseErrorMatcher.new(exception, message, &block)
47 | end
48 | end
49 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/respond_to.rb:
--------------------------------------------------------------------------------
1 | class RespondToMatcher
2 | def initialize(expected)
3 | @expected = expected
4 | end
5 |
6 | def matches?(actual)
7 | @actual = actual
8 | @actual.respond_to?(@expected)
9 | end
10 |
11 | def failure_message
12 | ["Expected #{@actual.inspect} (#{@actual.class})", "to respond to #{@expected}"]
13 | end
14 |
15 | def negative_failure_message
16 | ["Expected #{@actual.inspect} (#{@actual.class})", "not to respond to #{@expected}"]
17 | end
18 | end
19 |
20 | class Object
21 | def respond_to(expected)
22 | RespondToMatcher.new(expected)
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/stringsymboladapter.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/utils/version'
2 |
3 | module StringSymbolAdapter
4 | def convert_name(name)
5 | version = SpecVersion.new(RUBY_VERSION) <=> "1.9"
6 | version < 0 ? name.to_s : name.to_sym
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/matchers/variable.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/matchers/stringsymboladapter'
2 |
3 | class VariableMatcher
4 | include StringSymbolAdapter
5 |
6 | class << self
7 | attr_accessor :variables_method, :description
8 | end
9 |
10 | def initialize(variable)
11 | @variable = convert_name(variable)
12 | end
13 |
14 | def matches?(object)
15 | @object = object
16 | @object.send(self.class.variables_method).include? @variable
17 | end
18 |
19 | def failure_message
20 | ["Expected #{@object} to have #{self.class.description} '#{@variable}'",
21 | "but it does not"]
22 | end
23 |
24 | def negative_failure_message
25 | ["Expected #{@object} NOT to have #{self.class.description} '#{@variable}'",
26 | "but it does"]
27 | end
28 | end
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/mocks.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/mocks/mock'
2 | require 'mspec/mocks/proxy'
3 | require 'mspec/mocks/object'
4 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/mocks/object.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/mocks/proxy'
2 |
3 | class Object
4 | def stub!(sym)
5 | Mock.install_method self, sym, :stub
6 | end
7 |
8 | def should_receive(sym)
9 | Mock.install_method self, sym
10 | end
11 |
12 | def should_not_receive(sym)
13 | proxy = Mock.install_method self, sym
14 | proxy.exactly(0).times
15 | end
16 |
17 | def mock(name, options={})
18 | MockObject.new name, options
19 | end
20 |
21 | def mock_numeric(name, options={})
22 | NumericMockObject.new name, options
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/mocks'
2 | require 'mspec/runner/mspec'
3 | require 'mspec/runner/context'
4 | require 'mspec/runner/example'
5 | require 'mspec/runner/exception'
6 | require 'mspec/runner/object'
7 | require 'mspec/runner/formatters'
8 | require 'mspec/runner/actions'
9 | require 'mspec/runner/filters'
10 | require 'mspec/runner/shared'
11 | require 'mspec/runner/tag'
12 |
13 | def $stderr.write(str)
14 | # The 'useless use of' warnings are a crime against OO.
15 | str =~ /useless use of/ ? nil : super
16 | end
17 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/actions/tally'
2 | require 'mspec/runner/actions/timer'
3 | require 'mspec/runner/actions/filter'
4 | require 'mspec/runner/actions/tag'
5 | require 'mspec/runner/actions/taglist'
6 | require 'mspec/runner/actions/tagpurge'
7 | require 'mspec/runner/actions/debug'
8 | require 'mspec/runner/actions/gdb'
9 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions/debug.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/actions/filter'
2 |
3 | class DebugAction < ActionFilter
4 | def before(state)
5 | Kernel.debugger if self === state.description
6 | end
7 |
8 | def register
9 | super
10 | MSpec.register :before, self
11 | end
12 |
13 | def unregister
14 | super
15 | MSpec.unregister :before, self
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions/filter.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/filters/match'
2 |
3 | # ActionFilter is a base class for actions that are triggered by
4 | # specs that match the filter. The filter may be specified by
5 | # strings that match spec descriptions or by tags for strings
6 | # that match spec descriptions.
7 | #
8 | # Unlike TagFilter and RegexpFilter, ActionFilter instances do
9 | # not affect the specs that are run. The filter is only used to
10 | # trigger the action.
11 |
12 | class ActionFilter
13 | def initialize(tags=nil, descs=nil)
14 | @tags = Array(tags)
15 | descs = Array(descs)
16 | @sfilter = MatchFilter.new(nil, *descs) unless descs.empty?
17 | end
18 |
19 | def ===(string)
20 | @sfilter === string or @tfilter === string
21 | end
22 |
23 | def load
24 | @tfilter = nil
25 | return if @tags.empty?
26 |
27 | desc = MSpec.read_tags(@tags).map { |t| t.description }
28 | return if desc.empty?
29 |
30 | @tfilter = MatchFilter.new(nil, *desc)
31 | end
32 |
33 | def register
34 | MSpec.register :load, self
35 | end
36 |
37 | def unregister
38 | MSpec.unregister :load, self
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions/gdb.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/actions/filter'
2 |
3 | class GdbAction < ActionFilter
4 | def before(state)
5 | Kernel.yield_gdb(true) if self === state.description
6 | end
7 |
8 | def register
9 | super
10 | MSpec.register :before, self
11 | end
12 |
13 | def unregister
14 | super
15 | MSpec.unregister :before, self
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions/taglist.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/actions/filter'
2 |
3 | # TagListAction - prints out the descriptions for any specs
4 | # tagged with +tags+. If +tags+ is an empty list, prints out
5 | # descriptions for any specs that are tagged.
6 | class TagListAction
7 | def initialize(tags=nil)
8 | @tags = tags.nil? || tags.empty? ? nil : Array(tags)
9 | @filter = nil
10 | end
11 |
12 | # Returns true. This enables us to match any tag when loading
13 | # tags from the file.
14 | def include?(arg)
15 | true
16 | end
17 |
18 | # Returns true if any tagged descriptions matches +string+.
19 | def ===(string)
20 | @filter === string
21 | end
22 |
23 | # Prints a banner about matching tagged specs.
24 | def start
25 | if @tags
26 | print "\nListing specs tagged with #{@tags.map { |t| "'#{t}'" }.join(", ") }\n\n"
27 | else
28 | print "\nListing all tagged specs\n\n"
29 | end
30 | end
31 |
32 | # Creates a MatchFilter for specific tags or for all tags.
33 | def load
34 | @filter = nil
35 | desc = MSpec.read_tags(@tags || self).map { |t| t.description }
36 | @filter = MatchFilter.new(nil, *desc) unless desc.empty?
37 | end
38 |
39 | # Prints the spec description if it matches the filter.
40 | def after(state)
41 | return unless self === state.description
42 | print state.description, "\n"
43 | end
44 |
45 | def register
46 | MSpec.register :start, self
47 | MSpec.register :load, self
48 | MSpec.register :after, self
49 | end
50 |
51 | def unregister
52 | MSpec.unregister :start, self
53 | MSpec.unregister :load, self
54 | MSpec.unregister :after, self
55 | end
56 | end
57 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions/tagpurge.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/actions/filter'
2 | require 'mspec/runner/actions/taglist'
3 |
4 | # TagPurgeAction - removes all tags not matching any spec
5 | # descriptions.
6 | class TagPurgeAction < TagListAction
7 | attr_reader :matching
8 |
9 | def initialize
10 | @matching = []
11 | @filter = nil
12 | @tags = nil
13 | end
14 |
15 | # Prints a banner about purging tags.
16 | def start
17 | print "\nRemoving tags not matching any specs\n\n"
18 | end
19 |
20 | # Creates a MatchFilter for all tags.
21 | def load
22 | @filter = nil
23 | @tags = MSpec.read_tags self
24 | desc = @tags.map { |t| t.description }
25 | @filter = MatchFilter.new(nil, *desc) unless desc.empty?
26 | end
27 |
28 | # Saves any matching tags
29 | def after(state)
30 | @matching << state.description if self === state.description
31 | end
32 |
33 | # Rewrites any matching tags. Prints non-matching tags.
34 | # Deletes the tag file if there were no tags (this cleans
35 | # up empty or malformed tag files).
36 | def unload
37 | if @filter
38 | matched = @tags.select { |t| @matching.any? { |s| s == t.description } }
39 | MSpec.write_tags matched
40 |
41 | (@tags - matched).each { |t| print t.description, "\n" }
42 | else
43 | MSpec.delete_tags
44 | end
45 | end
46 |
47 | def register
48 | super
49 | MSpec.register :unload, self
50 | end
51 |
52 | def unregister
53 | super
54 | MSpec.unregister :unload, self
55 | end
56 | end
57 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/actions/timer.rb:
--------------------------------------------------------------------------------
1 | class TimerAction
2 | def register
3 | MSpec.register :start, self
4 | MSpec.register :finish, self
5 | end
6 |
7 | def start
8 | @start = Time.now
9 | end
10 |
11 | def finish
12 | @stop = Time.now
13 | end
14 |
15 | def elapsed
16 | @stop - @start
17 | end
18 |
19 | def format
20 | "Finished in %f seconds" % elapsed
21 | end
22 | end
23 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/example.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/mspec'
2 |
3 | # Holds some of the state of the example (i.e. +it+ block) that is
4 | # being evaluated. See also +ContextState+.
5 | class ExampleState
6 | attr_reader :context, :it, :example
7 |
8 | def initialize(context, it, example=nil)
9 | @context = context
10 | @it = it
11 | @example = example
12 | end
13 |
14 | def context=(context)
15 | @description = nil
16 | @context = context
17 | end
18 |
19 | def describe
20 | @context.description
21 | end
22 |
23 | def description
24 | @description ||= "#{describe} #{@it}"
25 | end
26 |
27 | def filtered?
28 | incl = MSpec.retrieve(:include) || []
29 | excl = MSpec.retrieve(:exclude) || []
30 | included = incl.empty? || incl.any? { |f| f === description }
31 | included &&= excl.empty? || !excl.any? { |f| f === description }
32 | not included
33 | end
34 | end
35 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/exception.rb:
--------------------------------------------------------------------------------
1 | class ExceptionState
2 | attr_reader :description, :describe, :it, :exception
3 |
4 | def initialize(state, location, exception)
5 | @exception = exception
6 |
7 | @description = location ? "An exception occurred during: #{location}" : ""
8 | if state
9 | @description << "\n" unless @description.empty?
10 | @description << state.description
11 | @describe = state.describe
12 | @it = state.it
13 | else
14 | @describe = @it = ""
15 | end
16 | end
17 |
18 | def failure?
19 | [SpecExpectationNotMetError, SpecExpectationNotFoundError].any? { |e| @exception.is_a? e }
20 | end
21 |
22 | def message
23 | if @exception.message.empty?
24 | ""
25 | elsif @exception.class == SpecExpectationNotMetError ||
26 | @exception.class == SpecExpectationNotFoundError
27 | @exception.message
28 | else
29 | "#{@exception.class}: #{@exception.message}"
30 | end
31 | end
32 |
33 | def backtrace
34 | @backtrace_filter ||= MSpecScript.config[:backtrace_filter]
35 |
36 | begin
37 | bt = @exception.awesome_backtrace.show.split "\n"
38 | rescue Exception
39 | bt = @exception.backtrace || []
40 | end
41 |
42 | bt.select { |line| $MSPEC_DEBUG or @backtrace_filter !~ line }.join("\n")
43 | end
44 | end
45 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/filters.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/filters/match'
2 | require 'mspec/runner/filters/regexp'
3 | require 'mspec/runner/filters/tag'
4 | require 'mspec/runner/filters/profile'
5 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/filters/match.rb:
--------------------------------------------------------------------------------
1 | class MatchFilter
2 | def initialize(what, *strings)
3 | @what = what
4 | @descriptions = to_regexp(*strings)
5 | end
6 |
7 | def to_regexp(*strings)
8 | strings.map { |str| Regexp.new Regexp.escape(str) }
9 | end
10 |
11 | def ===(string)
12 | @descriptions.any? { |d| d === string }
13 | end
14 |
15 | def register
16 | MSpec.register @what, self
17 | end
18 |
19 | def unregister
20 | MSpec.unregister @what, self
21 | end
22 | end
23 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/filters/profile.rb:
--------------------------------------------------------------------------------
1 | class ProfileFilter
2 | def initialize(what, *files)
3 | @what = what
4 | @methods = load(*files)
5 | @pattern = /([^ .#]+[.#])([^ ]+)/
6 | end
7 |
8 | def find(name)
9 | return name if File.exist?(File.expand_path(name))
10 |
11 | ["spec/profiles", "spec", "profiles", "."].each do |dir|
12 | file = File.join dir, name
13 | return file if File.exist? file
14 | end
15 | end
16 |
17 | def parse(file)
18 | pattern = /(\S+):\s*/
19 | key = ""
20 | file.inject(Hash.new { |h,k| h[k] = [] }) do |hash, line|
21 | line.chomp!
22 | if line[0,2] == "- "
23 | hash[key] << line[2..-1].gsub(/[ '"]/, "")
24 | elsif m = pattern.match(line)
25 | key = m[1]
26 | end
27 | hash
28 | end
29 | end
30 |
31 | def load(*files)
32 | files.inject({}) do |hash, file|
33 | next hash unless name = find(file)
34 |
35 | File.open name, "r" do |f|
36 | hash.merge parse(f)
37 | end
38 | end
39 | end
40 |
41 | def ===(string)
42 | return false unless m = @pattern.match(string)
43 | return false unless l = @methods[m[1]]
44 | l.include? m[2]
45 | end
46 |
47 | def register
48 | MSpec.register @what, self
49 | end
50 |
51 | def unregister
52 | MSpec.unregister @what, self
53 | end
54 | end
55 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/filters/regexp.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/filters/match'
2 |
3 | class RegexpFilter < MatchFilter
4 | def to_regexp(*strings)
5 | strings.map { |str| Regexp.new str }
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/filters/tag.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/filters/match'
2 |
3 | class TagFilter
4 | def initialize(what, *tags)
5 | @what = what
6 | @tags = tags
7 | end
8 |
9 | def load
10 | desc = MSpec.read_tags(@tags).map { |t| t.description }
11 |
12 | @filter = MatchFilter.new(@what, *desc)
13 | @filter.register
14 | end
15 |
16 | def unload
17 | @filter.unregister if @filter
18 | end
19 |
20 | def register
21 | MSpec.register :load, self
22 | MSpec.register :unload, self
23 | end
24 |
25 | def unregister
26 | MSpec.unregister :load, self
27 | MSpec.unregister :unload, self
28 | end
29 | end
30 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/formatters/describe'
2 | require 'mspec/runner/formatters/dotted'
3 | require 'mspec/runner/formatters/file'
4 | require 'mspec/runner/formatters/specdoc'
5 | require 'mspec/runner/formatters/html'
6 | require 'mspec/runner/formatters/summary'
7 | require 'mspec/runner/formatters/unit'
8 | require 'mspec/runner/formatters/spinner'
9 | require 'mspec/runner/formatters/method'
10 | require 'mspec/runner/formatters/yaml'
11 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters/describe.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/formatters/dotted'
2 | require 'mspec/runner/actions/tally'
3 |
4 | class DescribeFormatter < DottedFormatter
5 | # Callback for the MSpec :finish event. Prints a summary of
6 | # the number of errors and failures for each +describe+ block.
7 | def finish
8 | describes = Hash.new { |h,k| h[k] = Tally.new }
9 |
10 | @exceptions.each do |exc|
11 | desc = describes[exc.describe]
12 | exc.failure? ? desc.failures! : desc.errors!
13 | end
14 |
15 | print "\n"
16 | describes.each do |d, t|
17 | text = d.size > 40 ? "#{d[0,37]}..." : d.ljust(40)
18 | print "\n#{text} #{t.failure}, #{t.error}"
19 | end
20 | print "\n" unless describes.empty?
21 |
22 | print "\n#{@timer.format}\n\n#{@tally.format}\n"
23 | end
24 | end
25 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters/file.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/formatters/dotted'
2 |
3 | class FileFormatter < DottedFormatter
4 | # Unregisters DottedFormatter#before, #after methods and
5 | # registers #load, #unload, which perform the same duties
6 | # as #before, #after in DottedFormatter.
7 | def register
8 | super
9 |
10 | MSpec.unregister :before, self
11 | MSpec.unregister :after, self
12 |
13 | MSpec.register :load, self
14 | MSpec.register :unload, self
15 | end
16 |
17 | alias_method :load, :before
18 | alias_method :unload, :after
19 | end
20 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters/specdoc.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/expectations/expectations'
2 | require 'mspec/runner/formatters/dotted'
3 |
4 | class SpecdocFormatter < DottedFormatter
5 | def register
6 | super
7 | MSpec.register :enter, self
8 | end
9 |
10 | # Callback for the MSpec :enter event. Prints the
11 | # +describe+ block string.
12 | def enter(describe)
13 | print "\n#{describe}\n"
14 | end
15 |
16 | # Callback for the MSpec :before event. Prints the
17 | # +it+ block string.
18 | def before(state)
19 | super
20 | print "- #{state.it}"
21 | end
22 |
23 | # Callback for the MSpec :exception event. Prints
24 | # either 'ERROR - X' or 'FAILED - X' where _X_ is
25 | # the sequential number of the exception raised. If
26 | # there has already been an exception raised while
27 | # evaluating this example, it prints another +it+
28 | # block description string so that each discription
29 | # string has an associated 'ERROR' or 'FAILED'
30 | def exception(exception)
31 | print "\n- #{exception.it}" if exception?
32 | super
33 | print " (#{exception.failure? ? 'FAILED' : 'ERROR'} - #{@count})"
34 | end
35 |
36 | # Callback for the MSpec :after event. Prints a
37 | # newline to finish the description string output.
38 | def after(state)
39 | print "\n"
40 | end
41 | end
42 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters/summary.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/expectations/expectations'
2 | require 'mspec/runner/formatters/dotted'
3 |
4 | class SummaryFormatter < DottedFormatter
5 | # Callback for the MSpec :after event. Overrides the
6 | # callback provided by +DottedFormatter+ and does not
7 | # print any output for each example evaluated.
8 | def after(state)
9 | # do nothing
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters/unit.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/expectations/expectations'
2 | require 'mspec/runner/formatters/dotted'
3 |
4 | class UnitdiffFormatter < DottedFormatter
5 | def finish
6 | print "\n\n#{@timer.format}\n"
7 | count = 0
8 | @exceptions.each do |exc|
9 | outcome = exc.failure? ? "FAILED" : "ERROR"
10 | print "\n#{count += 1})\n#{exc.description} #{outcome}\n"
11 | print exc.message, ": \n"
12 | print exc.backtrace, "\n"
13 | end
14 | print "\n#{@tally.format}\n"
15 | end
16 |
17 | def backtrace(exc)
18 | exc.backtrace && exc.backtrace.join("\n")
19 | end
20 | private :backtrace
21 | end
22 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/formatters/yaml.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/expectations/expectations'
2 | require 'mspec/runner/formatters/dotted'
3 |
4 | class YamlFormatter < DottedFormatter
5 | def initialize(out=nil)
6 | @exception = @failure = false
7 | @exceptions = []
8 | @count = 0
9 | @out = $stdout
10 |
11 | if out.nil?
12 | @finish = $stdout
13 | else
14 | @finish = File.open out, "w"
15 | end
16 | end
17 |
18 | def switch
19 | @out = @finish
20 | end
21 |
22 | def after(state)
23 | end
24 |
25 | def finish
26 | switch
27 |
28 | print "---\n"
29 | print "exceptions:\n"
30 | @exceptions.each do |exc|
31 | outcome = exc.failure? ? "FAILED" : "ERROR"
32 | str = "#{exc.description} #{outcome}\n"
33 | str << exc.message << "\n" << exc.backtrace
34 | print "- ", str.inspect, "\n"
35 | end
36 |
37 | print "time: ", @timer.elapsed, "\n"
38 | print "files: ", @tally.counter.files, "\n"
39 | print "examples: ", @tally.counter.examples, "\n"
40 | print "expectations: ", @tally.counter.expectations, "\n"
41 | print "failures: ", @tally.counter.failures, "\n"
42 | print "errors: ", @tally.counter.errors, "\n"
43 | end
44 | end
45 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/object.rb:
--------------------------------------------------------------------------------
1 | class Object
2 | def before(at=:each, &block)
3 | MSpec.current.before at, &block
4 | end
5 |
6 | def after(at=:each, &block)
7 | MSpec.current.after at, &block
8 | end
9 |
10 | def describe(mod, msg=nil, options=nil, &block)
11 | MSpec.describe mod, msg, &block
12 | end
13 |
14 | def it(msg, &block)
15 | MSpec.current.it msg, &block
16 | end
17 |
18 | def it_should_behave_like(desc)
19 | MSpec.current.it_should_behave_like desc
20 | end
21 |
22 | # For ReadRuby compatiability
23 | def doc(*a)
24 | end
25 |
26 | alias_method :context, :describe
27 | alias_method :specify, :it
28 | end
29 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/shared.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/runner/mspec'
2 |
3 | class Object
4 | def it_behaves_like(desc, meth, obj=nil)
5 | send :before, :all do
6 | @method = meth
7 | @object = obj if obj
8 | end
9 |
10 | send :it_should_behave_like, desc.to_s
11 | end
12 | end
13 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/runner/tag.rb:
--------------------------------------------------------------------------------
1 | class SpecTag
2 | attr_accessor :tag, :comment, :description
3 |
4 | def initialize(string=nil)
5 | parse(string) if string
6 | end
7 |
8 | def parse(string)
9 | m = /^([^()#:]+)(\(([^)]+)?\))?:(.*)$/.match string
10 | @tag, @comment, description = m.values_at(1, 3, 4) if m
11 | @description = unescape description
12 | end
13 |
14 | def unescape(str)
15 | return unless str
16 | str = str[1..-2] if str[0] == ?" and str[-1] == ?"
17 | str.gsub(/\\n/, "\n")
18 | end
19 |
20 | def escape(str)
21 | str = %["#{str.gsub(/\n/, '\n')}"] if /\n/ =~ str
22 | str
23 | end
24 |
25 | def to_s
26 | "#{@tag}#{ "(#{@comment})" if @comment }:#{escape @description}"
27 | end
28 |
29 | def ==(o)
30 | @tag == o.tag and @comment == o.comment and @description == o.description
31 | end
32 | end
33 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/utils/ruby_name.rb:
--------------------------------------------------------------------------------
1 | unless Object.const_defined?(:RUBY_NAME) and RUBY_NAME
2 | if Object.const_defined?(:RUBY_ENGINE) and RUBY_ENGINE
3 | RUBY_NAME = RUBY_ENGINE
4 | else
5 | require 'rbconfig'
6 | RUBY_NAME = Config::CONFIG["RUBY_INSTALL_NAME"] || Config::CONFIG["ruby_install_name"]
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/utils/version.rb:
--------------------------------------------------------------------------------
1 | class SpecVersion
2 | # If beginning implementations have a problem with this include, we can
3 | # manually implement the relational operators that are needed.
4 | include Comparable
5 |
6 | # SpecVersion handles comparison correctly for the context by filling in
7 | # missing version parts according to the value of +ceil+. If +ceil+ is
8 | # +false+, 0 digits fill in missing version parts. If +ceil+ is +true+, 9
9 | # digits fill in missing parts. (See e.g. VersionGuard and BugGuard.)
10 | def initialize(version, ceil = false)
11 | @version = version
12 | @ceil = ceil
13 | @integer = nil
14 | end
15 |
16 | def to_s
17 | @version
18 | end
19 |
20 | def to_str
21 | to_s
22 | end
23 |
24 | # Converts a string representation of a version major.minor.tiny.patchlevel
25 | # to an integer representation so that comparisons can be made. For example,
26 | # "1.8.6.77" < "1.8.6.123" would be false if compared as strings.
27 | def to_i
28 | unless @integer
29 | major, minor, tiny, patch = @version.split "."
30 | if @ceil
31 | tiny = 99 unless tiny
32 | patch = 9999 unless patch
33 | end
34 | parts = [major, minor, tiny, patch].map { |x| x.to_i }
35 | @integer = ("1%02d%02d%02d%04d" % parts).to_i
36 | end
37 | @integer
38 | end
39 |
40 | def to_int
41 | to_i
42 | end
43 |
44 | def <=>(other)
45 | if other.respond_to? :to_int
46 | other = Integer other
47 | else
48 | other = SpecVersion.new(String(other)).to_i
49 | end
50 |
51 | self.to_i <=> other
52 | end
53 | end
54 |
--------------------------------------------------------------------------------
/src/test/rubyspec/mspec/version.rb:
--------------------------------------------------------------------------------
1 | require 'mspec/utils/version'
2 |
3 | module MSpec
4 | VERSION = SpecVersion.new "1.5.17"
5 | end
6 |
--------------------------------------------------------------------------------
/src/test/scala/org/enumerable/lambda/support/scala/ScalaTest.scala:
--------------------------------------------------------------------------------
1 | package org.enumerable.lambda.support.scala
2 |
3 | import org.enumerable.lambda.Lambda._
4 | import org.enumerable.lambda.Parameters._
5 |
6 | object EnumerableJavaScalaTest {
7 | def toUpperCase() = {
8 | λ(s, s.toUpperCase)
9 | }
10 | }
11 |
--------------------------------------------------------------------------------