diff --git a/.gitignore b/.gitignore index b3d0261d..5392375c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,8 @@ */bin/* .metadata bin/* -lib/build/bin/* -lib/build/reports/* +lib/build +lib/out koans/data koans/data* .classpath @@ -16,3 +16,4 @@ lib/file-compiler/bin *.iml *.ipr *.iws +.idea diff --git a/.travis.yml b/.travis.yml index 2ebee51c..c0eb7f08 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,2 +1,17 @@ -language: java -script: "./lib/gradlew -b lib/build.gradle test" +sudo: required + +language: ruby + +services: + - docker + +before_install: + - docker build -t java/koans docker + +script: + - docker run java/koans /bin/bash -c "git clone https://github.com/matyb/java-koans && gradle -p java-koans/lib buildApp" + +cache: + directories: + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ diff --git a/README.md b/README.md index 34bd739e..a0519e70 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -#Java Koans [![Build Status](https://travis-ci.org/matyb/java-koans.png?branch=master)](https://travis-ci.org/matyb/java-koans) +# Java Koans + +[![Build Status](https://travis-ci.org/matyb/java-koans.png?branch=master)](https://travis-ci.org/matyb/java-koans) Running Instructions: ===================== @@ -17,6 +19,7 @@ Developing a Koan: ================== * Follow any of the existing koans as an example to create a new class with koan methods (indicated by the @Koan annotation, they're public and specify no arguments) * Define the order the koan suite (if it's new) will run in the koans/app/config/PathToEnlightenment.xml file +* [Override the lesson text](https://github.com/matyb/java-koans/blob/master/koans/app/config/i18n/messages_en.properties#L1) when it fails (default is expected 'X' found 'Y') * Optionally you may use dynamic content in your lesson, examples are located in the XmlVariableInjector class (and Test) and the AboutKoans.java file Something's wrong: diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 00000000..f7c564aa --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,18 @@ +FROM centos:7 +MAINTAINER Mat Bentley + +ENV JAVA_VERSION 1.8.0 +ENV GRADLE_VERSION 3.4.1 + +# install wget, git, curl, jdk, which +RUN yum remove -y java &&\ + yum install -y wget git curl unzip java-$JAVA_VERSION-openjdk-devel which + +# install gradle +RUN wget https://services.gradle.org/distributions/gradle-$GRADLE_VERSION-bin.zip &&\ + mkdir -p /etc/alternatives/gradle &&\ + unzip -d /etc/alternatives/gradle gradle-$GRADLE_VERSION-bin.zip &&\ + ln -s /etc/alternatives/gradle/gradle-$GRADLE_VERSION /opt/gradle + +ENV PATH $PATH:/opt/gradle/bin +RUN JAVA_HOME=$(readlink $(readlink `which java`) | gawk '$0=gensub(/\/jre\/bin\/java/,"",1)') diff --git a/docker/spec/Dockerfile_spec.rb b/docker/spec/Dockerfile_spec.rb new file mode 100644 index 00000000..85bc02b8 --- /dev/null +++ b/docker/spec/Dockerfile_spec.rb @@ -0,0 +1,30 @@ +#! /usr/bin/ruby + +require "serverspec" +require "docker" + +describe "Dockerfile" do + before(:all) do + image = Docker::Image.build_from_dir('.') + + set :os, family: :redhat + set :backend, :docker + set :docker_image, image.id + end + + it "has jdk8 installed" do + expect(command("javac -version").stderr).to include(" 1.8.") + end + + it "has gradle installed" do + expect(command("gradle -version").stdout).to include("Build time") + end + + it "can build app" do + output = command("git clone https://github.com/matyb/java-koans && gradle -p java-koans/lib buildApp").stdout + expect(output).to include(":test\n") + expect(output).to include("BUILD SUCCESSFUL") + end + +end + diff --git a/koans/README.md b/koans/README.md index 657fe638..044f12ce 100755 --- a/koans/README.md +++ b/koans/README.md @@ -1,9 +1,7 @@ -#Java Koans [![Build Status](https://travis-ci.org/matyb/java-koans.png?branch=master)](https://travis-ci.org/matyb/java-koans) - ## Quick Start * Download and unarchive the contents of the most recent java-koans in development from: https://github.com/matyb/java-koans/archive/master.zip -* Open a console (termina) and cd to the directory you unarchived: +* Open a console (terminal) and cd to the directory you unarchived: ```cd ``` * Change directory to the koans directory: ```cd koans``` * To export koans to run below command and open in IDE: diff --git a/koans/app/config/PathToEnlightenment.xml b/koans/app/config/PathToEnlightenment.xml index 5aa2e209..dd104446 100755 --- a/koans/app/config/PathToEnlightenment.xml +++ b/koans/app/config/PathToEnlightenment.xml @@ -52,5 +52,6 @@ + diff --git a/koans/app/config/config.properties b/koans/app/config/config.properties index 50b21fde..5d078c19 100644 --- a/koans/app/config/config.properties +++ b/koans/app/config/config.properties @@ -1,4 +1,5 @@ compile_timeout_in_ms=5000 +ignore_from_monitoring=(.*\\.idea|^\\.#.*\\..*|^#.*\\..*) debug=false exit_character=Q enable_encouragement=false diff --git a/koans/app/lib/koans.jar b/koans/app/lib/koans.jar index 8820ac3f..492231ba 100644 Binary files a/koans/app/lib/koans.jar and b/koans/app/lib/koans.jar differ diff --git a/koans/run.bat b/koans/run.bat index 1cf878ea..bd54d6c2 100755 --- a/koans/run.bat +++ b/koans/run.bat @@ -1,11 +1,15 @@ @echo off cls setLocal EnableDelayedExpansion -set CLASSPATH="%~dp0app\bin;"%~dp0\app\config" -for /R "%~dp0\app\lib" %%a in (*.jar) do ( - set CLASSPATH=!CLASSPATH!;%%a +set string=%~dp0 +set string=%string:\=/% +set CLASSPATH="%string%app/bin";"%string%app/config" +for /R "%~dp0/app/lib" %%a in (*.jar) do ( + set string=%%a + set string=!string:\=/! + set CLASSPATH=!CLASSPATH!;"!string!" ) -set CLASSPATH=!CLASSPATH!;" +set CLASSPATH=!CLASSPATH!; javac -version if ERRORLEVEL 3 goto no_javac java -version @@ -16,12 +20,12 @@ java -Dapplication.basedir="%~dp0"" -classpath %CLASSPATH% com.sandwich.koan.run goto end :no_java -REM cls +cls @echo java is not bound to PATH variable. goto end :no_javac -REM cls +cls @echo javac is not bound to PATH variable. goto end diff --git a/koans/src/beginner/AboutAssertions.java b/koans/src/beginner/AboutAssertions.java old mode 100755 new mode 100644 index 818662e9..a83ba2ae --- a/koans/src/beginner/AboutAssertions.java +++ b/koans/src/beginner/AboutAssertions.java @@ -62,17 +62,25 @@ public void assertEqualsWithDescriptiveMessage() { @Koan public void assertSameInstance() { - // Just because something is equal doesn't mean that it is the same. - // It's only the same if the reference is the same. - Object same = new Integer(1); - Object sameReference = __; - assertSame(same, sameReference); + Integer original = new Integer(1); + Integer same = original; + Integer different = new Integer(1); + // These are both equal to the original... + assertEquals(original, same); + assertEquals(original, different); + // ...but only one refers to the same instance as the original. + assertSame(original, __); } @Koan public void assertNotSameInstance() { - Integer same = new Integer(1); - Integer sameReference = same; - assertNotSame(same, sameReference); + Integer original = new Integer(1); + Integer same = original; + Integer different = new Integer(1); + // These are both equal to the original... + assertEquals(original, same); + assertEquals(original, different); + // ...but only one of them refers to a different instance. + assertNotSame(original, same); // We want equal, but _not_ the same. } } diff --git a/koans/src/beginner/AboutConditionals.java b/koans/src/beginner/AboutConditionals.java index f7883dfb..ca3d3fd6 100644 --- a/koans/src/beginner/AboutConditionals.java +++ b/koans/src/beginner/AboutConditionals.java @@ -47,20 +47,35 @@ public void basicIfElseIfElse() { @Koan public void nestedIfsWithoutCurlysAreReallyMisleading() { - // Why are these ugly you ask? Well, try for yourself int x = 1; boolean secretBoolean = false; boolean otherBooleanCondition = true; - // Ifs without curly braces are ugly and not recommended but still valid: + // Curly braces after an "if" or "else" are not required... + if (secretBoolean) + x++; + if (otherBooleanCondition) + x = 10; + else + x--; + // ...but they are recommended. + assertEquals(x, __); + } + + @Koan + public void ifAsIntended() { + int x = 1; + boolean secretBoolean = false; + boolean otherBooleanCondition = true; + // Adding curly braces avoids the "dangling else" problem seen + // above. if (secretBoolean) { x++; - } - if (otherBooleanCondition) { - x = 10; + if (otherBooleanCondition) { + x = 10; + } } else { x--; } - // Where does this else belong to!? assertEquals(x, __); } @@ -147,11 +162,39 @@ public void switchStatementSwitchValues() { @Koan public void shortCircuit() { - int i = 1; - int a = 6; - // Why did we use a variable here? - // What happens if you replace 'a' with '6' below? - if ((a < 9) || (++i < 8)) i = i + 1; - assertEquals(i, __); + Counter trueCount = new Counter(true); + Counter falseCount = new Counter(false); + String x = "Hai"; + if (trueCount.count() || falseCount.count()) { + x = "kthxbai"; + } + assertEquals(x, __); + assertEquals(trueCount.count, __); + assertEquals(falseCount.count, __); + } + + @Koan + public void bitwise() { + Counter trueCount = new Counter(true); + Counter falseCount = new Counter(false); + String x = "Hai"; + if (trueCount.count() | falseCount.count()) { + x = "kthxbai"; + } + assertEquals(x, __); + assertEquals(trueCount.count, __); + assertEquals(falseCount.count, __); + } + + class Counter { + boolean returnValue; + int count = 0; + Counter(boolean returnValue) { + this.returnValue = returnValue; + } + boolean count() { + count++; + return returnValue; + } } } diff --git a/koans/src/beginner/AboutObjects.java b/koans/src/beginner/AboutObjects.java index df66e647..b93e5e28 100755 --- a/koans/src/beginner/AboutObjects.java +++ b/koans/src/beginner/AboutObjects.java @@ -29,6 +29,7 @@ class Foo { @Koan public void objectToString() { Object object = new Object(); + // TODO: Why is it best practice to ALWAYS override toString? String expectedToString = MessageFormat.format("{0}@{1}", Object.class.getName(), Integer.toHexString(object.hashCode())); assertEquals(expectedToString, __); // hint: object.toString() } @@ -48,9 +49,7 @@ public String toString() { @Koan public void toStringIsTestedForNullWhenInvokedImplicitly() { String string = "string"; - Integer i = new Integer(128); - Short s = new Short((short) 15); - assertEquals(string + " " + i + " " + s, __); + assertEquals(string + null, __); } private Class[] getAncestors(Object object) { diff --git a/koans/src/beginner/AboutPrimitives.java b/koans/src/beginner/AboutPrimitives.java index f8a240b5..2f196653 100644 --- a/koans/src/beginner/AboutPrimitives.java +++ b/koans/src/beginner/AboutPrimitives.java @@ -117,7 +117,7 @@ public void primitivesOfTypeCharHaveAnObjectTypeCharacter() { } @Koan - public void charsCanOnlyBePositive() { + public void charsAreNotNegative() { assertEquals((int) Character.MIN_VALUE, __); assertEquals((int) Character.MAX_VALUE, __); diff --git a/koans/src/intermediate/AboutFileIO.java b/koans/src/intermediate/AboutFileIO.java index 4649ebc9..3fb98e7d 100644 --- a/koans/src/intermediate/AboutFileIO.java +++ b/koans/src/intermediate/AboutFileIO.java @@ -12,7 +12,7 @@ public class AboutFileIO { @Koan public void fileObjectDoesntCreateFile() { - File f = new File("foo.txt"); + File f = new File("i-never.exist"); assertEquals(f.exists(), __); } @@ -29,11 +29,12 @@ public void fileCreationAndDeletion() throws IOException { public void basicFileWritingAndReading() throws IOException { File file = new File("file.txt"); FileWriter fw = new FileWriter(file); - fw.write("First line\nSecond line"); + String data = "First line\nSecond line"; + fw.write(data); fw.flush(); fw.close(); - char[] in = new char[50]; + char[] in = new char[data.length()]; int size = 0; FileReader fr = new FileReader(file); size = fr.read(in); diff --git a/koans/src/java8/AboutBase64.java b/koans/src/java8/AboutBase64.java new file mode 100644 index 00000000..ed1235e8 --- /dev/null +++ b/koans/src/java8/AboutBase64.java @@ -0,0 +1,40 @@ +package java8; + +import com.sandwich.koan.Koan; + +import java.util.Base64; +import java.io.UnsupportedEncodingException; + +import static com.sandwich.koan.constant.KoanConstants.__; +import static com.sandwich.util.Assert.assertEquals; + +public class AboutBase64 { + + private final String plainText = "lorem ipsum"; + private final String encodedText = "bG9yZW0gaXBzdW0="; + + @Koan + public void base64Encoding() { + try { + // Encode the plainText + // This uses the basic Base64 encoding scheme but there are corresponding + // getMimeEncoder and getUrlEncoder methods available if you require a + // different format/Base64 Alphabet + assertEquals(encodedText, Base64.getEncoder().encodeToString(__.getBytes("utf-8"))); + } catch (UnsupportedEncodingException ex) {} + } + + @Koan + public void base64Decoding() { + // Decode the Base64 encodedText + // This uses the basic Base64 decoding scheme but there are corresponding + // getMimeDecoder and getUrlDecoder methods available if you require a + // different format/Base64 Alphabet + byte[] decodedBytes = Base64.getDecoder().decode(__); + try { + String decodedText = new String(decodedBytes, "utf-8"); + assertEquals(plainText, decodedText); + } catch (UnsupportedEncodingException ex) {} + } + +} diff --git a/koans/src/java8/AboutLambdas.java b/koans/src/java8/AboutLambdas.java index 2b1c436a..8cab569b 100644 --- a/koans/src/java8/AboutLambdas.java +++ b/koans/src/java8/AboutLambdas.java @@ -23,9 +23,9 @@ public String toString() { static String str = ""; //lambda has access to "this" - Caps lambdaField = s -> this.toString(); + Caps thisLambdaField = s -> this.toString(); //lambda has access to object methods - Caps lambdaField2 = s -> toString(); + Caps toStringLambdaField = s -> toString(); @Koan public void verySimpleLambda() throws InterruptedException { @@ -55,12 +55,12 @@ public void simpleSuccinctLambda() { @Koan public void lambdaField() { - assertEquals(lambdaField.capitalize(""), __); + assertEquals(thisLambdaField.capitalize(""), __); } @Koan public void lambdaField2() { - assertEquals(lambdaField2.capitalize(""), __); + assertEquals(toStringLambdaField.capitalize(""), __); } @Koan diff --git a/koans/src/java8/AboutStreams.java b/koans/src/java8/AboutStreams.java index 42e7b2db..ee0c90e4 100644 --- a/koans/src/java8/AboutStreams.java +++ b/koans/src/java8/AboutStreams.java @@ -68,13 +68,6 @@ public void join() { assertEquals(join, __); } - @Koan - public void reduceWithBinaryOperator() { - String join = places.stream() - .reduce("", String::concat); - assertEquals(join, __); - } - @Koan public void stringJoin() { String join = places.stream() diff --git a/lib/build.gradle b/lib/build.gradle index 949e3631..0f6aae3d 100644 --- a/lib/build.gradle +++ b/lib/build.gradle @@ -26,7 +26,7 @@ task createJar(type: Jar){ task copyJarToBin { doLast { copy { - from 'build/libs/koans.jar' + from './build/libs/koans.jar' into '../koans/app/lib' } } diff --git a/lib/out/test/lib/data/com/sandwich/koan/KoansResultTest.java b/lib/out/test/lib/data/com/sandwich/koan/KoansResultTest.java deleted file mode 100644 index b2011ebd..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/KoansResultTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.sandwich.koan; - -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - -import org.junit.Test; - -import com.sandwich.koan.result.KoanMethodResult; -import com.sandwich.koan.result.KoanSuiteResult; -import com.sandwich.koan.result.KoanSuiteResult.KoanResultBuilder; -import com.sandwich.koan.suite.OneFailingKoan; - -public class KoansResultTest { - - @Test - public void testToString() throws Exception { - KoanResultBuilder builder = new KoanResultBuilder() - .remainingCases(Arrays.asList(OneFailingKoan.class.getSimpleName())) - .methodResult(new KoanMethodResult(KoanMethod.getInstance("", OneFailingKoan.class.getDeclaredMethods()[0]), "msg", "2")) - .level("1") - .numberPassing(3); - KoanSuiteResult result = builder.build(); - String string = result.toString(); - assertTrue(string.contains("1")); - assertTrue(string.contains("2")); - assertTrue(string.contains("3")); - assertTrue(string.contains(OneFailingKoan.class.getSimpleName())); - assertTrue(string.contains(OneFailingKoan.class.getDeclaredMethods()[0].getName())); - assertTrue(string.contains("msg")); - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/TestUtils.java b/lib/out/test/lib/data/com/sandwich/koan/TestUtils.java deleted file mode 100644 index 52dd8dc2..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/TestUtils.java +++ /dev/null @@ -1,315 +0,0 @@ -package com.sandwich.koan; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.PrintStream; -import java.io.Serializable; -import java.lang.Thread.State; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Random; - -import com.sandwich.koan.constant.KoanConstants; - -public class TestUtils { - - private static Random random = new Random(System.currentTimeMillis()); - public static final String EOL = System.getProperty("line.separator"); - public static final int MAX_UNIQUE_CHARS = 1000; - - public static long sizeInBytes(Serializable... objects) { - byte[] ba = null; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(objects); - oos.close(); - ba = baos.toByteArray(); - baos.close(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } - return ba.length; - } - - public static void chewUpVM(){ - chewUpVM(100); - } - - public static void chewUpVM(long forApproxHowLongInMs){ - long start = System.currentTimeMillis(); - while(System.currentTimeMillis() - start > forApproxHowLongInMs){new Object();} - } - - public static String getRandomText(int i) { - return getRandomText(i,false); - } - - public static String getRandomText(int i, boolean enforceUnique) { - if(enforceUnique && i > MAX_UNIQUE_CHARS){ - throw new RuntimeException("call getRandomText w/ a value under 1000 if u wish to enforce unique"); - } - StringBuilder sb = new StringBuilder(); - int j = 0; - while(j < i){ - char nextChar = (char)random.nextInt(); - if(enforceUnique && sb.indexOf(String.valueOf(nextChar)) != -1){ - continue; - } - sb.append(nextChar); - j++; - } - return sb.toString(); - } - - public static long time(Runnable runnable) { - long start = System.currentTimeMillis(); - runnable.run(); - return System.currentTimeMillis() - start; - } - - public static void forEachLine(String text, ArgRunner runnable){ - String[] strings = text.split(KoanConstants.EOLS, -1); - for(String line : strings){ - runnable.run(line); - } - } - - @SuppressWarnings("unchecked") - public static T serialize(T t) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(t); - oos.close(); - final byte[] ba = baos.toByteArray(); - baos.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(ba); - ObjectInputStream ois = new ObjectInputStream(bais); - Object returnValue = ois.readObject(); - ois.close(); - return (T) returnValue; - } catch (IOException e) { - throw new RuntimeException(e); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static T getValue(String fieldName, Object target) { - Class clazz = target instanceof Class ? (Class)target : target.getClass(); - Field field = getField(clazz, fieldName); - try { - boolean wasAccessible = field.isAccessible(); - field.setAccessible(true); - Object value = field.get(target); - field.setAccessible(wasAccessible); - return (T)value; - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - public static void setValue(String fieldName, Object value, Object target) { - Class clazz = target instanceof Class ? (Class)target : target.getClass(); - Field field = getField(clazz, fieldName); - try { - boolean wasAccessible = field.isAccessible(); - field.setAccessible(true); - field.set(target, value); - field.setAccessible(wasAccessible); - return; - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - public static Field getField(Class clazz, String fieldName){ - String className = clazz.getName(); - do{ - for(Field field : clazz.getDeclaredFields()){ - if(field.getName().equals(fieldName)){ - return field; - } - } - clazz = (Class)clazz.getSuperclass(); - }while(clazz != null); - throw new IllegalArgumentException(fieldName+" was not found in class: "+className); - } - - /** - * Used to simulate multiple threads accessing the same method whilst busy. - * Will fail in insufficiently concurrent scenarios. - * - * @param assertion - * @param rs - * @throws InterruptedException - */ - public static void doSimultaneouslyAndRepetitively(TwoObjectAssertion assertion, final Runnable... rs) throws InterruptedException{ - assertTrue("Whats the point of testing for synchronization w/ less than two threads?", rs.length > 1); - final int[] c = new int[]{0}; - int startRuns = rs.length + 9; - final Thread[] threads = new Thread[rs.length]; - int totalRuns = 0; - for(int i = 0; i < rs.length; i++){ - final int it = i; - final int startRunsTemp = startRuns; - totalRuns += startRunsTemp; - startRuns--; - threads[i] = new Thread(new Runnable(){ - public void run() { - Runnable runnable = rs[it]; - for(int j = 0; j < startRunsTemp; j++){ - runnable.run(); - c[0]++; - } - } - }); - threads[i].start(); - } - allowThreadsToFinish(threads); - assertion.assertOn("Threads died before they could finish.", totalRuns, c[0]); - } - - public static void doSimultaneouslyAndRepetitively(TwoObjectAssertion assertion, - Class anticipatedExceptionClass, - final Runnable... rs) throws InterruptedException{ - PrintStream temp = System.err; - try { - ByteArrayOutputStream sysErr = new ByteArrayOutputStream(); - System.setErr(new PrintStream(sysErr)); - doSimultaneouslyAndRepetitively(assertion, rs); - String errors = sysErr.toString(); - int i = rs.length; - assertFalse(errors.contains("Thread-"+(i+1))); - for(;i > 0; i--){ - assertTrue(errors.contains("Thread-"+i+"\" "+anticipatedExceptionClass.getName())); - } - } finally { - System.setErr(temp); - } - } - - /** - * Will lock Thread accessible when called from Thread via repetitive sleep - * calls until the passed in threads are terminated. Generally used to keep - * the test exec thread alive while the other threads are still working. - * - * @param threads - * @throws InterruptedException - */ - public static void allowThreadsToFinish(final Thread[] threads) - throws InterruptedException { - boolean threadsDone = false; - while(!threadsDone){ - threadsDone = true; - for(Thread thread : threads){ - if(thread.getState() != State.TERMINATED){ - Thread.sleep(10); - threadsDone = false; - } - } - } - } - - public static void assertEqualsContractEnforcement(Object obj0, Object obj1, Object obj2){ - assertFalse(obj0.equals(null)); - assertFalse(obj1.equals(null)); - assertFalse(obj2.equals(null)); - - assertEquals(obj0, obj0); - assertEquals(obj1, obj1); - assertEquals(obj2, obj2); - - assertEquals(obj0, obj1); - assertEquals(obj1, obj0); - - assertEquals(obj1, obj2); - assertEquals(obj2, obj1); - - assertEquals(obj2, obj0); - assertEquals(obj0, obj2); - } - - public static void assertHashCodeContractEnforcement(Object obj0, Object obj1, Object obj2){ - assertEquals(obj0.hashCode(), obj0.hashCode()); - assertEquals(obj1.hashCode(), obj1.hashCode()); - assertEquals(obj2.hashCode(), obj2.hashCode()); - - assertEquals(obj0.hashCode(), obj1.hashCode()); - assertEquals(obj1.hashCode(), obj0.hashCode()); - - assertEquals(obj1.hashCode(), obj2.hashCode()); - assertEquals(obj2.hashCode(), obj1.hashCode()); - - assertEquals(obj2.hashCode(), obj0.hashCode()); - assertEquals(obj0.hashCode(), obj2.hashCode()); - } - - public static void assertHashCodeEqualsContracts(Object obj0, Object obj1, Object obj2){ - assertEqualsContractEnforcement(obj0, obj1, obj2); - assertHashCodeContractEnforcement(obj0, obj1, obj2); - } - - public static Object invokePrivate( - String name, - final Object obj, - Object[] objects) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - Method method = null; - Class objClass = obj instanceof Class ? (Class)obj : obj.getClass(); - while(objClass != null && method == null){ - for(Method m : objClass.getDeclaredMethods()){ - if (name.equals(m.getName()) && - (objects == null && m.getParameterTypes().length == 0) || - (objects != null && objects.length == m.getParameterTypes().length)){ - method = m; - break; - } - } - objClass = objClass.getSuperclass(); - } - if(method == null){ - throw new IllegalArgumentException("method with name "+name+" was not found, check class definition."); - } - final boolean wasAccessible = method.isAccessible(); - try{ - method.setAccessible(true); - return method.invoke(obj, objects); - }finally{ - if(wasAccessible != method.isAccessible()){ - method.setAccessible(wasAccessible); - } - } - } - - public static interface ArgRunner { - public void run(T t); - } - - public static interface TwoObjectAssertion { - /** - * Message to display when assertion fails. Followed by 2 objects to - * assertOn. Useful for reusing in object composition tests or a - * chain of command pattern based assertion chain. - * - * @param msg - * @param o0 - * @param o1 - */ - void assertOn(String msg, Object o0, Object o1); - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/TestUtilsTest.java b/lib/out/test/lib/data/com/sandwich/koan/TestUtilsTest.java deleted file mode 100644 index a5a66b8c..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/TestUtilsTest.java +++ /dev/null @@ -1,436 +0,0 @@ -package com.sandwich.koan; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -import org.easymock.EasyMock; -import org.junit.Test; - -import com.sandwich.koan.TestUtils.ArgRunner; -import com.sandwich.koan.TestUtils.TwoObjectAssertion; - -public class TestUtilsTest { - - @Test - public void testEqualsContractEnforcement_integerIdentity_happyPath() throws Exception { - Integer one = 1; - TestUtils.assertEqualsContractEnforcement(one, one, one); - } - - @Test - public void testEqualsContractEnforcement_integerObject_happyPath() throws Exception { - TestUtils.assertEqualsContractEnforcement(new Integer(1), new Integer(1), new Integer(1)); - } - - @Test(expected=AssertionError.class) - public void testEqualsContractEnforcement_integer_exceptionPath0() throws Exception { - TestUtils.assertEqualsContractEnforcement(new Integer(2), new Integer(1), new Integer(1)); - } - - @Test(expected=AssertionError.class) - public void testEqualsContractEnforcement_integer_exceptionPath1() throws Exception { - TestUtils.assertEqualsContractEnforcement(new Integer(1), new Integer(2), new Integer(1)); - } - - @Test(expected=AssertionError.class) - public void testEqualsContractEnforcement_integer_exceptionPath() throws Exception { - TestUtils.assertEqualsContractEnforcement(new Integer(1), new Integer(1), new Integer(2)); - } - - @Test - public void testHashCodeContractEnforcement_integerIdentity_happyPath() throws Exception { - Integer one = 1; - TestUtils.assertHashCodeContractEnforcement(one, one, one); - } - - @Test - public void testHashCodeContractEnforcement_integerObject_happyPath() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new Integer(1), new Integer(1), new Integer(1)); - } - - @Test(expected=AssertionError.class) - public void testHashCodeContractEnforcement_integer_exceptionPath0() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new Integer(2), new Integer(1), new Integer(1)); - } - - @Test(expected=AssertionError.class) - public void testHashCodeContractEnforcement_integer_exceptionPath1() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new Integer(1), new Integer(2), new Integer(1)); - } - - @Test(expected=AssertionError.class) - public void testHashCodeContractEnforcement_integer_exceptionPath() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new Integer(1), new Integer(1), new Integer(2)); - } - - @Test - public void testHashCodeContractEnforcement_testObj_happyPath() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new ContractEnforcementBase(), - new ContractEnforcementBase(), - new ContractEnforcementBase()); - } - - @Test(expected=AssertionError.class) - public void testHashCodeContractEnforcement_testObj_exceptionPath0() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new ContractEnforcementSubclass(), - new ContractEnforcementBase(), - new ContractEnforcementBase()); - } - - @Test(expected=AssertionError.class) - public void testHashCodeContractEnforcement_testObj_exceptionPath1() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new ContractEnforcementBase(), - new ContractEnforcementSubclass(), - new ContractEnforcementBase()); - } - - @Test(expected=AssertionError.class) - public void testHashCodeContractEnforcement_testObj_exceptionPath2() throws Exception { - TestUtils.assertHashCodeContractEnforcement(new ContractEnforcementBase(), - new ContractEnforcementBase(), - new ContractEnforcementSubclass()); - } - - @Test - public void testEqualsContractEnforcement_testObj_happyPath() throws Exception { - TestUtils.assertEqualsContractEnforcement(new ContractEnforcementBase(), - new ContractEnforcementBase(), - new ContractEnforcementBase()); - } - - @Test(expected=AssertionError.class) - public void testEqualsContractEnforcement_testObj_exceptionPath0() throws Exception { - TestUtils.assertEqualsContractEnforcement(new ContractEnforcementSubclass(), - new ContractEnforcementBase(), - new ContractEnforcementBase()); - } - - @Test(expected=AssertionError.class) - public void testEqualsContractEnforcement_testObj_exceptionPath1() throws Exception { - TestUtils.assertEqualsContractEnforcement(new ContractEnforcementBase(), - new ContractEnforcementSubclass(), - new ContractEnforcementBase()); - } - - @Test(expected=AssertionError.class) - public void testEqualsContractEnforcement_testObj_exceptionPath2() throws Exception { - TestUtils.assertEqualsContractEnforcement(new ContractEnforcementBase(), - new ContractEnforcementBase(), - new ContractEnforcementSubclass()); - } - - static class ContractEnforcementBase { - int i = 1; - @Override - public boolean equals(Object o){ - return o instanceof ContractEnforcementBase && i == ((ContractEnforcementBase)o).i; - } - @Override - public int hashCode(){ - return 1; - } - } - - static class ContractEnforcementSubclass extends ContractEnforcementBase { - int j = 2; - @Override - public boolean equals(Object o){ - return o instanceof ContractEnforcementSubclass - && i == ((ContractEnforcementSubclass)o).i - && j == ((ContractEnforcementSubclass)o).j; - } - @Override - public int hashCode(){ - return 2; - } - } - - @Test(expected=AssertionError.class, timeout=1000) - public void testEqualsConcurrency_concurrentAccessFails() throws Exception { - final PrintStream temp = System.err; - try { - ByteArrayOutputStream sysErr = new ByteArrayOutputStream(); - System.setErr(new PrintStream(sysErr)); - TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { - public void assertOn(String msg, Object o0, Object o1) { - assertEquals(msg, o0, o1); - } - }, IllegalMonitorStateException.class, - new Runnable() { - public void run() { - waste(10); - } - }, new Runnable() { - public void run() { - waste(11); - } - }, new Runnable() { - public void run() { - waste(3); - } - }); - String errors = sysErr.toString(); - assertTrue(errors.contains("Thread-1\" java.lang.IllegalMonitorStateException")); - assertTrue(errors.contains("Thread-2\" java.lang.IllegalMonitorStateException")); - assertTrue(errors.contains("Thread-3\" java.lang.IllegalMonitorStateException")); - assertFalse(errors.contains("Thread-4")); - } finally { - System.setErr(new PrintStream(temp)); - } - } - - @Test(expected=java.lang.AssertionError.class, timeout=500) - public void testEqualsConcurrency_concurrentAccessFails_assertIllegalMonitorStateException() throws Exception { - TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { - public void assertOn(String msg, Object o0, Object o1) { - assertEquals(msg, o0, o1); - } - }, - IllegalMonitorStateException.class, - new Runnable() { - public void run() { - waste(10); - } - }, - new Runnable() { - public void run() { - waste(11); - } - }, - new Runnable() { - public void run() { - waste(3); - } - }); - } - - @Test - public void testEqualsConcurrency() throws Exception { - TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { - public void assertOn(String msg, Object o0, Object o1) { - assertEquals(msg, o0, o1); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(10); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(11); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(3); - } - }); - } - - @Test - public void testEqualsConcurrency_II() throws Exception { - TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { - public void assertOn(String msg, Object o0, Object o1) { - assertEquals(msg, o0, o1); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(10); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(11); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(4); - } - }, new Runnable(){ - public void run() { - wasteSynchronized(6); - } - }); - } - - private void waste(int i) { - try { - wait(i); - } catch (InterruptedException e) { - fail(e.getMessage()); - } - } - - private int wasteSynchronized(int i) { synchronized(this){ - try { - wait(i); - } catch (InterruptedException e) { - fail(e.getMessage()); - } - return i; - }} - - @Test - public void testForEachLine_threeNewLines() throws Exception { - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("\n\n\n", runner); - EasyMock.verify(runner); - } - - @Test - public void testForEachLine_spaceNewLineNewLine(){ - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine(" \n\n", runner); - EasyMock.verify(runner); - } - - @Test - public void testForEachLine_newLineNewLineSpace(){ - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("\n\n ", runner); - EasyMock.verify(runner); - } - - @Test - public void testMixingBackslashRAndBackslashNNewLines() throws Exception { - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("\r \n ", runner); // can mix and match \r and \n - EasyMock.verify(runner); - } - - @Test - public void testMixingBackslashNAndBackslashRNewLines() throws Exception { - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("\n \r ", runner); // can mix and match \r and \n - EasyMock.verify(runner); - } - - @Test - public void testForEachLine_emptyString() throws Exception { - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - runner.run(""); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("", runner); - EasyMock.verify(runner); - } - - @Test - public void testForEachLine_nothingThreeNewLinesSeperatedBy1Space() throws Exception { - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("\n \n \n", runner); - EasyMock.verify(runner); - } - - @Test - public void testForEachLine_nothingThreeNewLinesSeperatedBy1SpaceThen2Spaces() throws Exception { - @SuppressWarnings("unchecked") - ArgRunner runner = EasyMock.createStrictMock(ArgRunner.class); - - runner.run(""); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(" "); - EasyMock.expectLastCall(); - - runner.run(""); - EasyMock.expectLastCall(); - - EasyMock.replay(runner); - - TestUtils.forEachLine("\n \n \n", runner); - EasyMock.verify(runner); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/cmdline/CommandLineArgumentBuilderTest.java b/lib/out/test/lib/data/com/sandwich/koan/cmdline/CommandLineArgumentBuilderTest.java deleted file mode 100644 index 5098f8da..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/cmdline/CommandLineArgumentBuilderTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.sandwich.koan.cmdline; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Map; -import java.util.Map.Entry; - -import org.junit.Test; - -import com.sandwich.koan.constant.ArgumentType; -import com.sandwich.util.SimpleEntry; - - -public class CommandLineArgumentBuilderTest { - - @Test - public void testNoArguments() throws Exception { - assertEquals(ArgumentType.RUN_KOANS, new CommandLineArgumentBuilder().entrySet().iterator().next().getKey()); - } - - @Test - public void testUnanticipatedArgument_yieldsMethodArg_constructedImplicitly() throws Exception { - String value = - "if string isn't a known command line arg (ArgumentType) or class - assume its a method"; - Entry anticipatedResult = - new SimpleEntry(ArgumentType.METHOD_ARG, - new CommandLineArgument(ArgumentType.METHOD_ARG, value)); - Map commandLineArgs = - new CommandLineArgumentBuilder(value); - assertEquals(1, commandLineArgs.size()); - assertEquals(anticipatedResult, commandLineArgs.entrySet().iterator().next()); - } - - @Test - public void testMethodArg_constructedExplicitly() throws Exception { - String value = "someMethodName"; - Entry anticipatedResult = - new SimpleEntry(ArgumentType.METHOD_ARG, - new CommandLineArgument(ArgumentType.METHOD_ARG, value)); - Map commandLineArgs = new CommandLineArgumentBuilder( - ArgumentType.METHOD_ARG.args().iterator().next(), - value); - assertEquals(1, commandLineArgs.size()); - assertEquals(anticipatedResult, commandLineArgs.entrySet().iterator().next()); - } - - @Test - public void testClassArg_constructedImplicitly() throws Exception { - String value = Object.class.getName(); - Map commandLineArgs = new CommandLineArgumentBuilder(value); - assertEquals(2, commandLineArgs.size()); - assertTrue(commandLineArgs.containsKey(ArgumentType.CLASS_ARG)); - assertTrue(commandLineArgs.containsKey(ArgumentType.RUN_KOANS)); - } - - @Test - public void testClassArg_constructedExplicitly() throws Exception { - String value = Object.class.getName(); - Map commandLineArgs = new CommandLineArgumentBuilder( - ArgumentType.CLASS_ARG.args().iterator().next(), value); - assertEquals(2, commandLineArgs.size()); - assertTrue(commandLineArgs.containsKey(ArgumentType.CLASS_ARG)); - assertTrue(commandLineArgs.containsKey(ArgumentType.RUN_KOANS)); - } - - @Test - public void testMultipleMethodOrUnknownArgs_throwsException() throws Exception { - String value = "someMethodName"; - try{ - new CommandLineArgumentBuilder(ArgumentType.METHOD_ARG.args().iterator().next(), value, value); - fail(); - }catch(IllegalArgumentException x){ - - } - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/constant/ArgumentTypeTest.java b/lib/out/test/lib/data/com/sandwich/koan/constant/ArgumentTypeTest.java deleted file mode 100644 index 48ec575a..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/constant/ArgumentTypeTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.sandwich.koan.constant; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; - -import com.sandwich.koan.path.CommandLineTestCase; - -public class ArgumentTypeTest extends CommandLineTestCase { - - @Test - public void testClassPrecedesMethod() throws Exception { - assertTrue(ArgumentType.CLASS_ARG.compareTo(ArgumentType.METHOD_ARG) == -1); - // further drive point home - method inserted at index 0, class index 1 - List classVsMethod = Arrays.asList(ArgumentType.METHOD_ARG, ArgumentType.CLASS_ARG); - assertEquals(0, classVsMethod.indexOf(ArgumentType.METHOD_ARG)); - assertEquals(1, classVsMethod.indexOf(ArgumentType.CLASS_ARG)); - Collections.sort(classVsMethod); - // now - because of comparable impl was applied, class precedes method - this is necessary - // @ see KaonSuiteRunner.run() - assertEquals(1, classVsMethod.indexOf(ArgumentType.METHOD_ARG)); - assertEquals(0, classVsMethod.indexOf(ArgumentType.CLASS_ARG)); - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/path/CommandLineTestCase.java b/lib/out/test/lib/data/com/sandwich/koan/path/CommandLineTestCase.java deleted file mode 100644 index a39f265c..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/path/CommandLineTestCase.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.sandwich.koan.path; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.junit.After; -import org.junit.Before; - -import com.sandwich.koan.Koan; -import com.sandwich.koan.KoanIncompleteException; -import com.sandwich.koan.TestUtils; -import com.sandwich.koan.TestUtils.ArgRunner; -import com.sandwich.koan.constant.ArgumentType; -import com.sandwich.koan.path.PathToEnlightenment.Path; -import com.sandwich.koan.path.xmltransformation.FakeXmlToPathTransformer; -import com.sandwich.koan.path.xmltransformation.KoanElementAttributes; -import com.sandwich.koan.runner.RunKoans; -import com.sandwich.util.io.DynamicClassLoader; -import com.sandwich.util.io.directories.DirectoryManager; -import com.sandwich.util.io.directories.Production; -import com.sandwich.util.io.directories.UnitTest; - -public abstract class CommandLineTestCase { - - private PrintStream console; - private ByteArrayOutputStream bytes; - - @Before - public void setUp() { - DirectoryManager.setDirectorySet(new UnitTest()); - bytes = new ByteArrayOutputStream(); - console = System.out; - TestUtils.setValue("behavior", new RunKoans(), ArgumentType.RUN_KOANS); - PathToEnlightenment.xmlToPathTransformer = new FakeXmlToPathTransformer(); - PathToEnlightenment.theWay = PathToEnlightenment.createPath(); - System.setOut(new PrintStream(bytes)); - } - - @After - public void tearDown() { - DirectoryManager.setDirectorySet(new Production()); - setRealPath(); - System.setOut(console); - } - - protected void setRealPath(){ - PathToEnlightenment.xmlToPathTransformer = null; - PathToEnlightenment.theWay = PathToEnlightenment.createPath(); - } - - protected Path stubAllKoans(String packageName, List path){ - Path oldKoans = PathToEnlightenment.getPathToEnlightenment(); - Map> tempSuitesAndMethods = - new LinkedHashMap>(); - DynamicClassLoader loader = new DynamicClassLoader(); - for(String suite : path){ - Map methodsByName = new LinkedHashMap(); - for(Method m : loader.loadClass(suite).getMethods()){ - if(m.getAnnotation(Koan.class) != null){ - methodsByName.put(m.getName(), new KoanElementAttributes("", m.getName(), "", m.getDeclaringClass().getName())); - } - } - tempSuitesAndMethods.put(suite, methodsByName); - } - Map>> stubbedPath = - new LinkedHashMap>>(); - stubbedPath.put(packageName, tempSuitesAndMethods); - PathToEnlightenment.theWay = new Path(null,stubbedPath); - return oldKoans; - } - - public Path stubAllKoans(List path){ - List classes = new ArrayList(); - for(Object o : path){ - String className; - if(o instanceof Class){ - className = ((Class)o).getName(); - }else{ - className = o.getClass().getName(); - } - classes.add(className); - } - return stubAllKoans("Test", classes); - } - - public void clearSysout(){ - bytes = new ByteArrayOutputStream(); - System.setOut(new PrintStream(bytes)); - } - - public void assertSystemOutEquals(String expectation){ - expectation = expectation == null ? "" : expectation; - if(!expectation.equals(bytes.toString())){ - throw new KoanIncompleteException("expected: <"+expectation+"> but found: <"+bytes.toString()+">"); - } - } - - public void assertSystemOutContains(String expectation){ - assertSystemOutContains(true, expectation); - } - - protected void assertSystemOutDoesntContain(String expectation){ - assertSystemOutContains(false, expectation); - } - - private void assertSystemOutContains(boolean assertContains, String expectation) { - String consoleOutput = bytes.toString(); - boolean containsTheSubstring = consoleOutput.contains(expectation); - if(assertContains && !containsTheSubstring || !assertContains && containsTheSubstring){ - throw new KoanIncompleteException(new StringBuilder( - "<").append( - expectation).append( - "> ").append( - (assertContains ? "wasn't" : "was")).append( - " found in: " ).append( - "<").append( - consoleOutput).append( - ">").toString()); - } - } - - public void assertSystemOutLineEquals(final int lineNumber, final String lineText){ - assertSystemOutLineEquals(lineNumber, lineText, false); - } - - public void assertSystemOutLineEquals(final int lineNumber, final String lineText, - final boolean trimLinesString) { - final int[] onLine = new int[]{0}; - final boolean[] found = new boolean[]{false}; - TestUtils.forEachLine(bytes.toString(), new ArgRunner(){ - public void run(String s){ - if(onLine[0] == lineNumber){ - if(trimLinesString){ - s = s.trim(); - } - assertEquals(lineText, s); - found[0] = true; - } - onLine[0]++; - } - }); - if(!found[0]){ - throw new KoanIncompleteException(lineText+" was expected, but not found in: "+bytes.toString()); - } - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/path/DefaultKoanDescriptionTest.java b/lib/out/test/lib/data/com/sandwich/koan/path/DefaultKoanDescriptionTest.java deleted file mode 100644 index 8f4f6de0..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/path/DefaultKoanDescriptionTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.sandwich.koan.path; - -import java.util.Map; -import java.util.Map.Entry; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.sandwich.koan.Koan; -import com.sandwich.koan.KoanMethod; -import com.sandwich.koan.constant.KoanConstants; -import com.sandwich.koan.path.xmltransformation.KoanElementAttributes; - -public class DefaultKoanDescriptionTest extends CommandLineTestCase { - - @Before - public void setUp(){ - super.setUp(); - } - - @After - public void tearDown(){ - super.tearDown(); - } - - @Test - public void defaultKoanDescriptions() throws Exception { - StringBuilder exceptionStringBuilder = new StringBuilder(KoanConstants.EOL); - for (Entry> suiteAndKoans : - PathToEnlightenment.getPathToEnlightenment().getKoanMethodsBySuiteByPackage().next().getValue().entrySet()) { - for(Entry koanEntry : suiteAndKoans.getValue().entrySet()){ - KoanMethod koan = KoanMethod.getInstance(koanEntry.getValue()); - Koan annotation = koan.getMethod().getAnnotation(Koan.class); - if (annotation != null && KoanConstants.DEFAULT_KOAN_DESC.equals(koan.getLesson())) { - exceptionStringBuilder.append(suiteAndKoans.getKey().getClass().getName()).append('.') - .append(koan.getMethod().getName()).append(KoanConstants.EOL); - } - } - } - String exceptionString = exceptionStringBuilder.toString(); - if(exceptionString.trim().length() != 0){ - throw new RuntimeException(new StringBuilder(KoanConstants.EOL).append( - "Following still have default Koan description:").append(exceptionString).toString()); - } - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/path/XmlVariableInjectorTest.java b/lib/out/test/lib/data/com/sandwich/koan/path/XmlVariableInjectorTest.java deleted file mode 100644 index 0b12af7f..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/path/XmlVariableInjectorTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.sandwich.koan.path; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; - -import com.sandwich.koan.path.xmltransformation.XmlVariableInjector; -import com.sandwich.koan.suite.OneFailingKoan; - -public class XmlVariableInjectorTest { - - @Test - public void construction_nullMethod() throws Exception { - try{ - new XmlVariableInjector("", null); - fail("why construct w/ null method?"); - }catch(IllegalArgumentException t){ - // this is ok - we want this! - } - } - -// @Test -// public void construction_nullLesson() throws Exception { -// try{ -// new XmlVariableInjector(null, Object.class.getDeclaredMethod("equals", Object.class)); -// fail("why construct w/ null lesson?"); -// }catch(IllegalArgumentException t){ -// // this is ok - we want this! -// } -// } - - @Test - public void injectInputVariables_filePath() throws Exception { - String lesson = "meh ${file_path}"; - String result = new XmlVariableInjector(lesson, OneFailingKoan.class.getDeclaredMethod("koanMethod")) - .injectLessonVariables(); - String firstPkgName = "com"; - // just inspect anything beyond the root of the project - result = result.substring(result.indexOf(firstPkgName)+firstPkgName.length(), result.length()); - assertTrue(result.indexOf(firstPkgName) < result.indexOf("sandwich")); - assertTrue(result.indexOf("sandwich") < result.indexOf("koan")); - assertTrue(result.indexOf("koan") < result.indexOf("suite")); - } - - @Test - public void injectInputVariables_fileName() throws Exception { - String lesson = "meh ${file_name}"; - String result = new XmlVariableInjector(lesson, OneFailingKoan.class.getDeclaredMethod("koanMethod")) - .injectLessonVariables(); - assertEquals("meh OneFailingKoan", result); - } - - @Test - public void injectInputVariables_methodName() throws Exception { - String lesson = "meh ${method_name}"; - String result = new XmlVariableInjector(lesson, OneFailingKoan.class.getDeclaredMethod("koanMethod")) - .injectLessonVariables(); - assertEquals("meh koanMethod", result); - } - - @Test - public void nothingToInject() throws Exception { - String lesson = " meh ea asdwdw s "; - assertSame(lesson, new XmlVariableInjector(lesson, - OneFailingKoan.class.getDeclaredMethod("koanMethod")).injectLessonVariables()); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/path/xmltransformation/FakeXmlToPathTransformer.java b/lib/out/test/lib/data/com/sandwich/koan/path/xmltransformation/FakeXmlToPathTransformer.java deleted file mode 100644 index 63f84368..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/path/xmltransformation/FakeXmlToPathTransformer.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.sandwich.koan.path.xmltransformation; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import com.sandwich.koan.path.PathToEnlightenment.Path; - -public class FakeXmlToPathTransformer extends XmlToPathTransformerImpl { - - private Map> methodsBySuite; - - @SuppressWarnings("unchecked") - public FakeXmlToPathTransformer() { - this(Collections.EMPTY_MAP); - } - - public FakeXmlToPathTransformer(Map> methodsBySuite){ - this.methodsBySuite = methodsBySuite; - } - - public Map> getMethodsBySuite() { - return methodsBySuite; - } - - public void setMethodsBySuite(Map> methodsBySuite) { - this.methodsBySuite = methodsBySuite; - } - - @Override - public Path transform(){ - Map>> koans = - new LinkedHashMap>>(); - koans.put("test", new LinkedHashMap>(methodsBySuite)); - return new Path(null,koans); - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/runner/AppLauncherTest.java b/lib/out/test/lib/data/com/sandwich/koan/runner/AppLauncherTest.java deleted file mode 100644 index a3559be1..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/runner/AppLauncherTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.sandwich.koan.runner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import com.sandwich.koan.cmdline.CommandLineArgument; -import com.sandwich.koan.cmdline.CommandLineArgumentBuilder; -import com.sandwich.koan.constant.ArgumentType; - -public class AppLauncherTest { - - @Test - public void testNecessityOfAddingRunKoansCommandLineArgument_addsIfNoArgsPresent(){ //default target - Map args = new CommandLineArgumentBuilder(); - assertArgsContains(true, args, ArgumentType.RUN_KOANS); - } - - @Test - public void testNecessityOfAddingRunKoansCommandLineArgument_ifClassArgIsPresent(){ - Map args = new CommandLineArgumentBuilder(Object.class.getName()); - assertArgsContains(true, args, ArgumentType.RUN_KOANS, ArgumentType.CLASS_ARG); - } - - @Test - public void testNecessityOfAddingRunKoansCommandLineArgument_doesntIfClassArgIsntPresent(){ - List types = new ArrayList(Arrays.asList(ArgumentType.values())); - assertTrue(types.remove(ArgumentType.CLASS_ARG)); - assertTrue(types.remove(ArgumentType.DEBUG)); - assertTrue(types.remove(ArgumentType.RUN_KOANS)); - for(ArgumentType type : types){ - Map args = new CommandLineArgumentBuilder(type.args().iterator().next()); - assertArgsContains(false, args, ArgumentType.RUN_KOANS); - assertArgsContains(true, args, type); - } - } - - private static void assertArgsContains( - boolean shouldContain, Map args, ArgumentType...types) { - if(shouldContain){ - assertEquals("expected arguments of a certain length, but found those built were of a differing size", - types.length, args.size()); - } - for(ArgumentType type : types){ - assertEquals("the arguments built should" - + (shouldContain ? "" : "n't") - + " contain the type: "+type, shouldContain, args.containsKey(type)); - } - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java b/lib/out/test/lib/data/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java deleted file mode 100644 index 630ebb5c..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.sandwich.koan.runner; - -import static com.sandwich.koan.constant.KoanConstants.EXPECTATION_LEFT_ARG; -import static com.sandwich.koan.constant.KoanConstants.__; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; -import java.util.logging.Handler; -import java.util.logging.LogRecord; -import java.util.logging.Logger; - -import org.junit.Test; - -import com.sandwich.koan.Koan; -import com.sandwich.koan.KoanMethod; -import com.sandwich.koan.cmdline.CommandLineArgumentBuilder; -import com.sandwich.koan.cmdline.CommandLineArgumentRunner; -import com.sandwich.koan.constant.KoanConstants; -import com.sandwich.koan.path.CommandLineTestCase; -import com.sandwich.koan.path.PathToEnlightenment; -import com.sandwich.koan.path.xmltransformation.KoanElementAttributes; -import com.sandwich.koan.result.KoanSuiteResult; -import com.sandwich.koan.suite.BlowUpOnLineEleven; -import com.sandwich.koan.suite.BlowUpOnLineTen; -import com.sandwich.koan.suite.OneFailingKoan; -import com.sandwich.koan.suite.OnePassingKoan; -import com.sandwich.koan.ui.SuitePresenter; -import com.sandwich.util.io.directories.DirectoryManager; -import com.sandwich.util.io.directories.Production; - -/** - * Anything that absoutely has to happen before bundling client jar - to be sure: - * - all koans fail by default - * - necessary aspects of app presentation are preserved - * - progression through koans (the sequence of koans) is consistent - */ -public class AppReadinessForDeploymentTest extends CommandLineTestCase { - - @Test - public void testMainMethodWithClassNameArg_qualifiedWithPkgName() throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(KoanConstants.PASSING_SUITES+" "+OnePassingKoan.class.getSimpleName()); - } - - @Test - public void testMainMethodWithClassNameArg_classSimpleName() throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(KoanConstants.PASSING_SUITES+" "+OnePassingKoan.class.getSimpleName()); - } - - @Test - public void testMainMethodWithClassNameArg_classNameAndMethod() throws Throwable { - stubAllKoans(Arrays.asList(new TwoFailingKoans())); - String failingKoanMethodName = TwoFailingKoans.class.getMethod("koanTwo").getName(); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(failingKoanMethodName); - assertSystemOutContains("0/2"); - } - - public static class TwoFailingKoans extends OneFailingKoan { - @Koan - public void koanTwo(){assertEquals(true, false);} - } - - @Test - public void testGetKoans() throws Exception { - stubAllKoans(Arrays.asList(new OnePassingKoan())); - Map> koans = PathToEnlightenment.getPathToEnlightenment().iterator().next().getValue(); - assertEquals(1, koans.size()); - Entry> entry = koans.entrySet().iterator().next(); - assertEquals(OnePassingKoan.class.getName(), entry.getKey()); - assertEquals( OnePassingKoan.class.getDeclaredMethod("koan").toString(), - KoanMethod.getInstance(entry.getValue().get("koan")).getMethod().toString()); - } - - @Test /** Ensures that koans are ready for packaging & distribution */ - public void testKoanSuiteRunner_firstKoanFail() throws Exception { - setRealPath(); - final KoanSuiteResult[] result = new KoanSuiteResult[]{null}; - final SuitePresenter presenter = new SuitePresenter(){ - public void displayResult(KoanSuiteResult actualAppResult) { - // don't display, capture them so we can analyze and ensure first failure is reported - result[0] = actualAppResult; - } - }; - doAsIfInProd(new Runnable(){ - public void run(){ - new RunKoans(presenter, PathToEnlightenment.getPathToEnlightenment()).run(null); - } - }); - String firstSuiteClassRan = PathToEnlightenment.getPathToEnlightenment() - .iterator().next().getValue().entrySet().iterator().next().getKey(); - assertEquals(result[0].getFailingCase(), firstSuiteClassRan.substring(firstSuiteClassRan.lastIndexOf(".") + 1)); - } - - @Test /** Ensures that koans are ready for packaging & distribution */ - public void testKoanSuiteRunner_allKoansFail() throws Exception { - setRealPath(); - final KoanSuiteResult[] result = new KoanSuiteResult[]{null}; - final SuitePresenter presenter = new SuitePresenter(){ - public void displayResult(KoanSuiteResult actualAppResult) { - // don't display, capture them so we can analyze and ensure first failure is reported - result[0] = actualAppResult; - } - }; - doAsIfInProd(new Runnable(){ - public void run(){ - new RunKoans(presenter, PathToEnlightenment.getPathToEnlightenment()).run(null); - } - }); - String message = "Not all koans need solving! Each should ship in a failing state."; - assertEquals(message, 0, result[0].getNumberPassing()); - // make sure test was actually useful (ie something actually failed) - assertNotNull(result[0].getFailingCase()); - } - - private void doAsIfInProd(Runnable runnable) { - DirectoryManager.setDirectorySet(new Production()); - runnable.run(); - } - - @Test - public void testLineExceptionIsThrownAtIsHintedAt() throws Exception { - stubAllKoans(Arrays.asList(new BlowUpOnLineTen())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains("Line 10"); - assertSystemOutDoesntContain("Line 11"); - } - - @Test - public void testLineExceptionIsThrownAtIsHintedAtEvenIfThrownFromSuperClass() throws Exception { - stubAllKoans(Arrays.asList(new BlowUpOnLineEleven())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains("Line 11"); - assertSystemOutDoesntContain("Line 10"); - } - - @Test - public void testWarningFromPlacingExpecationOnWrongSide() throws Throwable { - final String[] message = new String[1]; - stubAllKoans(Arrays.asList(new WrongExpectationOrderKoan())); - Logger.getLogger(CommandLineArgumentRunner.class.getSimpleName()).addHandler( - new Handler() { - @Override - public void close() throws SecurityException { - } - - @Override - public void flush() { - } - - @Override - public void publish(LogRecord arg0) { - message[0] = arg0.getMessage(); - } - }); - new CommandLineArgumentRunner(new CommandLineArgumentBuilder()).run(); - assertEquals( - new StringBuilder( - WrongExpectationOrderKoan.class.getSimpleName()) - .append(".expectationOnLeft ") - .append(EXPECTATION_LEFT_ARG).toString(), message[0]); - } - - @Test - public void testNoWarningFromPlacingExpecationOnRightSide() - throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan())); - Logger.getLogger(CommandLineArgumentRunner.class.getSimpleName()).addHandler( - new Handler() { - @Override - public void close() throws SecurityException { - } - - @Override - public void flush() { - } - - @Override - public void publish(LogRecord arg0) { - fail("No logging necessary when koan passes, otherwise - logging is new, adjust accordingly."); - } - }); - new CommandLineArgumentRunner().run(); - } - - public static class WrongExpectationOrderKoan { - @Koan - public void expectationOnLeft() { - com.sandwich.util.Assert.assertEquals(__, false); - } - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/runner/CommandLineTestCaseTest.java b/lib/out/test/lib/data/com/sandwich/koan/runner/CommandLineTestCaseTest.java deleted file mode 100644 index 179d7f31..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/runner/CommandLineTestCaseTest.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.sandwich.koan.runner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; - -import java.io.PrintStream; -import java.util.Collections; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.sandwich.koan.path.CommandLineTestCase; -import com.sandwich.koan.path.PathToEnlightenment; -import com.sandwich.koan.path.PathToEnlightenment.Path; - -public class CommandLineTestCaseTest { - - CommandLineTestCase testCase; - - @Before - public void setUp(){ - testCase = new CommandLineTestCase(){}; - } - - @After - public void tearDown(){ - testCase.tearDown(); // really important - will remove regular System.out if commented! - testCase = null; - } - - @Test - public void testThatConsoleIsInitializedBySetUp() throws Exception { - PrintStream originalOut = System.out; - testCase.setUp(); - assertNotSame(originalOut, System.out); - } - - @Test - public void testThatConsoleIsCleanAfterSetUp() throws Exception { - testCase.setUp(); - testCase.assertSystemOutLineEquals(0, ""); - } - - @Test - public void testThatConsoleIsAttachedToSystem() throws Exception { - testCase.setUp(); - System.out.print("hello \n world!"); - testCase.assertSystemOutLineEquals(0, "hello "); - testCase.assertSystemOutLineEquals(1, " world!"); - } - - @Test - public void testThatAssertSystemOutLineEquals_withTrimStringArg() throws Exception { - testCase.setUp(); - System.out.println(" hello \n world! "); - testCase.assertSystemOutLineEquals(0, "hello", true); - testCase.assertSystemOutLineEquals(1, "world!", true); - } - - @Test - public void testThatTearDownDetachesDummiedConsoleFromSystem(){ - PrintStream originalConsole = System.out; - testCase.setUp(); - PrintStream fakeConsole = System.out; - assertNotSame(fakeConsole, originalConsole); - testCase.tearDown(); - assertSame(originalConsole, System.out); - } - - @Test - public void testThatStubAllKoansStubsAllKoansReference() throws Exception { - Path oldKoans = PathToEnlightenment.getPathToEnlightenment(); - List newKoans = Collections.emptyList(); - testCase.stubAllKoans(newKoans); - assertNotSame(oldKoans, PathToEnlightenment.getPathToEnlightenment()); - // number of suites - assertEquals(0, PathToEnlightenment.getPathToEnlightenment() - .iterator().next().getValue().size()); - } - - @Test - public void testTestCaseRestoresAllKoansReference() throws Exception { - Path oldKoans = PathToEnlightenment.getPathToEnlightenment(); - List newKoans = Collections.emptyList(); - testCase.stubAllKoans(newKoans); - assertNotSame(oldKoans, PathToEnlightenment.getPathToEnlightenment()); - testCase.tearDown(); - // creates all new instance - assertNotSame(oldKoans, PathToEnlightenment.getPathToEnlightenment()); - assertEquals(oldKoans, PathToEnlightenment.getPathToEnlightenment()); - } - - @Test - public void testClearSysout() throws Exception { - testCase.setUp(); - System.out.print("!"); - testCase.assertSystemOutLineEquals(0, "!"); - testCase.clearSysout(); - testCase.assertSystemOutLineEquals(0, ""); - } - - @Test - public void testSystemOutEquals_freshStart(){ - testCase.setUp(); - testCase.assertSystemOutEquals(""); - } - - @Test - public void testSystemOutEquals_aString() throws Exception { - String helloWorld = "Hello World!"; - testCase.setUp(); - testCase.assertSystemOutEquals(""); - System.out.print(helloWorld); - testCase.assertSystemOutEquals(helloWorld); - } - - @Test - public void testSystemOutContains_happyPath() throws Exception { - testCase.setUp(); - String zeroThruOne = "01"; - System.out.print(zeroThruOne); - for(char c : zeroThruOne.toCharArray()){ - testCase.assertSystemOutContains(String.valueOf(c)); - } - } - - @Test - public void testSystemOutContains_failurePath() throws Exception { - testCase.setUp(); - String zeroThruOne = "01"; - System.out.print(zeroThruOne); - try{ - testCase.assertSystemOutContains(String.valueOf("a")); - fail(); - }catch(AssertionError ex){ - assertEquals(" wasn't found in: <01>", ex.getMessage()); - } - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/runner/ConsolePresenterTest.java b/lib/out/test/lib/data/com/sandwich/koan/runner/ConsolePresenterTest.java deleted file mode 100644 index 748f9818..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/runner/ConsolePresenterTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.sandwich.koan.runner; - -import static com.sandwich.koan.constant.KoanConstants.ALL_SUCCEEDED; -import static com.sandwich.koan.constant.KoanConstants.COMPLETE_CHAR; -import static com.sandwich.koan.constant.KoanConstants.CONQUERED; -import static com.sandwich.koan.constant.KoanConstants.ENCOURAGEMENT; -import static com.sandwich.koan.constant.KoanConstants.EOL; -import static com.sandwich.koan.constant.KoanConstants.FAILING_SUITES; -import static com.sandwich.koan.constant.KoanConstants.INCOMPLETE_CHAR; -import static com.sandwich.koan.constant.KoanConstants.INVESTIGATE_IN_THE; -import static com.sandwich.koan.constant.KoanConstants.KOAN; -import static com.sandwich.koan.constant.KoanConstants.OUT_OF; -import static com.sandwich.koan.constant.KoanConstants.PASSING_SUITES; -import static com.sandwich.koan.constant.KoanConstants.PROGRESS; -import static com.sandwich.koan.constant.KoanConstants.PROGRESS_BAR_START; -import static com.sandwich.koan.constant.KoanConstants.PROGRESS_BAR_WIDTH; -import static com.sandwich.koan.constant.KoanConstants.WHATS_WRONG; - -import java.util.Arrays; - -import org.junit.Test; - -import com.sandwich.koan.cmdline.CommandLineArgumentRunner; -import com.sandwich.koan.cmdline.CommandLineArgumentBuilder; -import com.sandwich.koan.constant.KoanConstants; -import com.sandwich.koan.path.CommandLineTestCase; -import com.sandwich.koan.suite.OneFailingKoan; -import com.sandwich.koan.suite.OneFailingKoanDifferentName; -import com.sandwich.koan.suite.OnePassingKoan; -import com.sandwich.koan.suite.OnePassingKoanDifferentName; - -public class ConsolePresenterTest extends CommandLineTestCase { - - @Test - public void hintPresentation() throws Throwable { - stubAllKoans(Arrays.asList(new OneFailingKoanDifferentName())); - new CommandLineArgumentRunner(new CommandLineArgumentBuilder()).run(); - assertSystemOutContains(new StringBuilder( - INVESTIGATE_IN_THE).append( - " ").append( - OneFailingKoanDifferentName.class.getSimpleName()).append( - " class's ").append( - OneFailingKoanDifferentName.class.getDeclaredMethod("koanMethod").getName()).append( - " method.").toString()); - assertSystemOutContains("Line 11 may offer a clue as to how you may progress, now make haste!"); - } - - @Test // uncomment enableEncouragement @ the top of ConsolePresenter class - public void encouragement() throws Throwable { - if(KoanConstants.ENABLE_ENCOURAGEMENT){ - stubAllKoans(Arrays.asList(new Class[] { - OneFailingKoan.class })); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(new StringBuilder( - CONQUERED).append( - " 0 ").append( - OUT_OF).append( - " 1 ").append( - KOAN).append( - "! ").append( - ENCOURAGEMENT).toString()); - assertSystemOutDoesntContain(ALL_SUCCEEDED); - } - } - - @Test - public void testOneHundredPercentSuccessReward() throws Throwable { - stubAllKoans(Arrays.asList(new Class[] { - OnePassingKoan.class })); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(ALL_SUCCEEDED); - assertSystemOutDoesntContain(CONQUERED); - assertSystemOutDoesntContain(ENCOURAGEMENT); - } - - @Test - public void passingSuites() throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan(), new OnePassingKoanDifferentName())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(PASSING_SUITES+" OnePassingKoan, OnePassingKoanDifferentName"); - } - - @Test - public void failingSuites() throws Throwable { - stubAllKoans(Arrays.asList(new OneFailingKoan(), new OneFailingKoanDifferentName())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(FAILING_SUITES+" OneFailingKoan, OneFailingKoanDifferentName"); - } - - @Test - public void failingAndPassingSuites() throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan(), new OneFailingKoan())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(PASSING_SUITES+" OnePassingKoan"+EOL+ - FAILING_SUITES+" OneFailingKoan"); - } - - @Test - public void progressAllPassing() throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan())); - new CommandLineArgumentRunner().run(); - StringBuilder sb = new StringBuilder(PROGRESS).append(" ") - .append(PROGRESS_BAR_START); - for(int i = 0; i < PROGRESS_BAR_WIDTH; i++){ // 100% success - sb.append(COMPLETE_CHAR); - } - sb.append("] 1/1").append(EOL); - assertSystemOutContains(sb.toString()); - } - - @Test - public void progressAllFailing() throws Throwable { - stubAllKoans(Arrays.asList(new OneFailingKoan(), new OneFailingKoanDifferentName())); - new CommandLineArgumentRunner().run(); - StringBuilder sb = new StringBuilder( - PROGRESS).append(" ").append( - PROGRESS_BAR_START); - for(int i = 0; i < PROGRESS_BAR_WIDTH; i++){ // 100% failed - sb.append(INCOMPLETE_CHAR); - } - sb.append("] 0/2").append(EOL); - assertSystemOutContains(sb.toString()); - } - - @Test - public void progressFiftyFifty() throws Throwable { - stubAllKoans(Arrays.asList(new OnePassingKoan(), new OneFailingKoan())); - new CommandLineArgumentRunner().run(); - StringBuilder sb = new StringBuilder( - PROGRESS).append(" ").append( - PROGRESS_BAR_START); - for(int i = 0; i < PROGRESS_BAR_WIDTH / 2; i++){ // 50% succeeded - sb.append(COMPLETE_CHAR); - } - for(int i = 0; i < PROGRESS_BAR_WIDTH / 2; i++){ // 50% failed - sb.append(INCOMPLETE_CHAR); - } - sb.append("] 1/2").append(EOL); - assertSystemOutContains(sb.toString()); - } - - @Test - public void whatWentWrongExplanation() throws Throwable { - stubAllKoans(Arrays.asList(new OneFailingKoan())); - new CommandLineArgumentRunner().run(); - assertSystemOutContains(new StringBuilder( - WHATS_WRONG).append( - EOL).append( - "expected: but was:").toString()); - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/runner/KoanSuiteRunnerTest.java b/lib/out/test/lib/data/com/sandwich/koan/runner/KoanSuiteRunnerTest.java deleted file mode 100644 index aa106442..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/runner/KoanSuiteRunnerTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.sandwich.koan.runner; - - -public class KoanSuiteRunnerTest { - -// @Test -// public void testRunSortsAndInvokesByComparableImplInArgumentType() throws Exception { -// // test depends on this - this is to ensure rest of test is true -// { -//// assertEquals(-1, ArgumentType.TEST.compareTo(ArgumentType.CLASS_ARG)); -// } -// Map args = new LinkedHashMap(); -// final boolean[] called = {false, false, false}; -// args.put(ArgumentType.TEST, new CommandLineArgument(ArgumentType.TEST, null){ -// @Override public void run(){ -// assertFalse(called[0]); -// assertFalse(called[1]); -// assertFalse(called[2]); -// called[0] = true; -// } -// }); -// args.put(ArgumentType.CLASS_ARG, new CommandLineArgument(ArgumentType.CLASS_ARG, null){ -// @Override public void run(){ -// assertTrue(called[0]); -// assertFalse(called[1]); -// assertFalse(called[2]); -// called[1] = true; -// } -// }); -// args.put(ArgumentType.RUN_KOANS, new CommandLineArgument(ArgumentType.RUN_KOANS, null){ -// @Override public void run(){ -// assertTrue(called[0]); -// assertTrue(called[1]); -// assertFalse(called[2]); -// called[2] = true; -// } -// }); -// new CommandLineArgumentRunner(args).run(); -// assertTrue(called[0]); -// assertTrue(called[1]); -// assertTrue(called[2]); -// } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/runner/ui/AbstractSuitePresenterTest.java b/lib/out/test/lib/data/com/sandwich/koan/runner/ui/AbstractSuitePresenterTest.java deleted file mode 100644 index 1e22df3c..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/runner/ui/AbstractSuitePresenterTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.sandwich.koan.runner.ui; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.util.Arrays; - -import org.junit.Test; - -import com.sandwich.koan.KoanMethod; -import com.sandwich.koan.result.KoanMethodResult; -import com.sandwich.koan.result.KoanSuiteResult; -import com.sandwich.koan.result.KoanSuiteResult.KoanResultBuilder; -import com.sandwich.koan.suite.OneFailingKoan; -import com.sandwich.koan.ui.AbstractSuitePresenter; - -public class AbstractSuitePresenterTest { - - @Test - public void testForwardingOneHundredPercentSuccess() throws Exception { - final int state[] = new int[]{0}; - AbstractSuitePresenter presenter = new AbstractSuitePresenter() { - public void displayAllSuccess(KoanSuiteResult result) { - assertEquals(0, state[0]); - state[0] = 1; - } - public void displayChart(KoanSuiteResult result) { - assertEquals(1, state[0]); - state[0] = 2; - } - public void displayPassingFailing(KoanSuiteResult result) { - assertEquals(2, state[0]); - state[0] = 3; - } - public void displayHeader(KoanSuiteResult result) { - assertEquals(3, state[0]); - state[0] = 4; - } - public void displayOneOrMoreFailure(KoanSuiteResult result) { - fail(); - } - }; - - KoanSuiteResult kr = new KoanResultBuilder().build(); - presenter.displayResult(kr); - assertEquals(4, state[0]); - } - - @Test - public void testForwardingOneOrMoreFails() throws Exception { - final int state[] = new int[]{0}; - AbstractSuitePresenter presenter = new AbstractSuitePresenter() { - public void displayOneOrMoreFailure(KoanSuiteResult result) { - assertEquals(0, state[0]); - state[0] = 1; - } - public void displayChart(KoanSuiteResult result) { - assertEquals(1, state[0]); - state[0] = 2; - } - public void displayPassingFailing(KoanSuiteResult result) { - assertEquals(2, state[0]); - state[0] = 3; - } - public void displayHeader(KoanSuiteResult result) { - assertEquals(3, state[0]); - state[0] = 4; - } - public void displayAllSuccess(KoanSuiteResult result) { - fail(); - } - }; - - KoanSuiteResult kr = new KoanResultBuilder().remainingCases(Arrays.asList(OneFailingKoan.class.getSimpleName()) - ).methodResult(new KoanMethodResult(KoanMethod.getInstance("", OneFailingKoan.class.getDeclaredMethods()[0]), - "", "")).build(); - presenter.displayResult(kr); - assertEquals(4, state[0]); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/suite/BlowUpOnLineEleven.java b/lib/out/test/lib/data/com/sandwich/koan/suite/BlowUpOnLineEleven.java deleted file mode 100644 index 3d6753c3..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/suite/BlowUpOnLineEleven.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.sandwich.koan.suite; - -import com.sandwich.koan.Koan; -import com.sandwich.koan.KoanIncompleteException; - -public class BlowUpOnLineEleven { - // gotta put it on line 11 thus the two spaces here - // - @Koan - public void blowUpOnLineEleven() { - throw new KoanIncompleteException(null); - } - -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/suite/BlowUpOnLineTen.java b/lib/out/test/lib/data/com/sandwich/koan/suite/BlowUpOnLineTen.java deleted file mode 100644 index 331e54d3..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/suite/BlowUpOnLineTen.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.sandwich.koan.suite; - -import com.sandwich.koan.Koan; - -public class BlowUpOnLineTen extends BlowUpOnLineEleven { - // gotta blow up on line 10 thus the two spaces - // - @Koan - public void blowUpOnLineTen(){ - super.blowUpOnLineEleven(); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/suite/OneFailingKoan.java b/lib/out/test/lib/data/com/sandwich/koan/suite/OneFailingKoan.java deleted file mode 100644 index e16e4296..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/suite/OneFailingKoan.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.sandwich.koan.suite; - -import static com.sandwich.util.Assert.assertEquals; - -import com.sandwich.koan.Koan; - -public class OneFailingKoan { - @Koan - public void koanMethod() { - assertEquals(true, false); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/suite/OneFailingKoanDifferentName.java b/lib/out/test/lib/data/com/sandwich/koan/suite/OneFailingKoanDifferentName.java deleted file mode 100644 index 64666e0d..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/suite/OneFailingKoanDifferentName.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.sandwich.koan.suite; - -import static org.junit.Assert.assertEquals; - -import com.sandwich.koan.Koan; - -public class OneFailingKoanDifferentName extends OneFailingKoan { - @Koan - @Override - public void koanMethod() { - assertEquals(true, false); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/suite/OnePassingKoan.java b/lib/out/test/lib/data/com/sandwich/koan/suite/OnePassingKoan.java deleted file mode 100644 index 2db4f932..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/suite/OnePassingKoan.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.sandwich.koan.suite; - -import com.sandwich.koan.Koan; - -public class OnePassingKoan { - boolean[] invoked; - public OnePassingKoan(){ - invoked = new boolean[]{false}; - } - @Koan - public void koan() { - invoked[0] = true; - } -} diff --git a/lib/out/test/lib/data/com/sandwich/koan/suite/OnePassingKoanDifferentName.java b/lib/out/test/lib/data/com/sandwich/koan/suite/OnePassingKoanDifferentName.java deleted file mode 100644 index 5a76b430..00000000 --- a/lib/out/test/lib/data/com/sandwich/koan/suite/OnePassingKoanDifferentName.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.sandwich.koan.suite; - -public class OnePassingKoanDifferentName extends OnePassingKoan { - -} diff --git a/lib/out/test/lib/data/com/sandwich/util/KoanComparatorTest.java b/lib/out/test/lib/data/com/sandwich/util/KoanComparatorTest.java deleted file mode 100644 index 78473088..00000000 --- a/lib/out/test/lib/data/com/sandwich/util/KoanComparatorTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.sandwich.util; - -import static org.junit.Assert.assertSame; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.Test; - -import com.sandwich.koan.Koan; -import com.sandwich.koan.KoanMethod; -import com.sandwich.koan.path.CommandLineTestCase; - -public class KoanComparatorTest extends CommandLineTestCase { - - @Test - public void testThatKomparatorBombsWhenNotFound() throws Exception { - Method m = new Object(){ - @SuppressWarnings("unused") @Koan public void someMethod(){} - }.getClass().getDeclaredMethod("someMethod"); - KoanComparator comparator = new KoanComparator("meh"); - try{ - comparator.compare(KoanMethod.getInstance("2",m), KoanMethod.getInstance("1",m)); - }catch(RuntimeException fileNotFound){} - } - - @Test - public void testComparatorRanksByOrder() throws Exception { - Class clazz = new Object(){ - @SuppressWarnings("unused") @Koan public void someMethodOne(){} - @SuppressWarnings("unused") @Koan public void someMethodTwo(){} - }.getClass(); - KoanMethod m1 = KoanMethod.getInstance("",clazz.getDeclaredMethod("someMethodOne")); - KoanMethod m2 = KoanMethod.getInstance("",clazz.getDeclaredMethod("someMethodTwo")); - List methods = Arrays.asList(m2,m1); - Collections.sort(methods, new KoanComparator("someMethodOne","someMethodTwo")); - assertSame(m1,methods.get(0)); - assertSame(m2,methods.get(1)); - } -} - diff --git a/lib/out/test/lib/data/com/sandwich/util/io/DirectoryManagerTest.java b/lib/out/test/lib/data/com/sandwich/util/io/DirectoryManagerTest.java deleted file mode 100644 index d97f5ef6..00000000 --- a/lib/out/test/lib/data/com/sandwich/util/io/DirectoryManagerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.sandwich.util.io; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.sandwich.koan.path.CommandLineTestCase; -import com.sandwich.util.io.directories.DirectoryManager; - - -public class DirectoryManagerTest extends CommandLineTestCase { - - @Test - public void testFileSeparatorInjection_happyPath() throws Exception { - assertEquals("/home/wilford/liberty", DirectoryManager.injectFileSystemSeparators( - "home", "wilford", "liberty")); - } - - @Test - public void testFileSeparatorInjection_separatorsAtBeginning() throws Exception { - assertEquals("/home/wilford/liberty", DirectoryManager.injectFileSystemSeparators( - "/home", "/wilford", "/liberty")); - } - - @Test - public void testFileSeparatorInjection_separatorsAtEnding() throws Exception { - assertEquals("/home/wilford/liberty", DirectoryManager.injectFileSystemSeparators( - "home/", "wilford/", "liberty/")); - } - - @Test - public void testFileSeparatorInjection_separatorsAtBeginningAndEnding() throws Exception { - assertEquals("/home/wilford/liberty", DirectoryManager.injectFileSystemSeparators( - "home/", "wilford/", "/liberty/")); - } - - @Test - public void testFileSeparatorInjection_separatorsInMiddle() throws Exception { - assertEquals("/home/wilford/liberty", DirectoryManager.injectFileSystemSeparators( - "home", "wilford/liberty")); - } -} diff --git a/lib/out/test/lib/data/com/sandwich/util/io/FileMonitorTest.java b/lib/out/test/lib/data/com/sandwich/util/io/FileMonitorTest.java deleted file mode 100644 index 2f3d10e9..00000000 --- a/lib/out/test/lib/data/com/sandwich/util/io/FileMonitorTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.sandwich.util.io; - -import org.junit.After; -import org.junit.Before; - -import com.sandwich.koan.constant.KoanConstants; - - -public class FileMonitorTest { - - String SAMPLE_DIR = FileUtils.makeAbsoluteRelativeTo(KoanConstants.PROJ_TESTS_FOLDER); - FileMonitor monitor; - - @Before - public void createInstance() throws Exception{ - monitor = FileMonitorFactory.getInstance(SAMPLE_DIR); - } - - @After - public void destroyInstance(){ - monitor.close(); - } - -} diff --git a/lib/src/main/java/com/sandwich/koan/ApplicationSettings.java b/lib/src/main/java/com/sandwich/koan/ApplicationSettings.java index ca8a0423..168e1b7d 100644 --- a/lib/src/main/java/com/sandwich/koan/ApplicationSettings.java +++ b/lib/src/main/java/com/sandwich/koan/ApplicationSettings.java @@ -43,6 +43,10 @@ public static String getPathXmlFileName(){ public static long getFileCompilationTimeoutInMs(){ return Long.valueOf(getConfigBundle().getString("compile_timeout_in_ms")); } + + public static String getMonitorIgnorePattern(){ + return getConfigBundle().getString("ignore_from_monitoring"); + } private static boolean isEqual(String value, Object e2, boolean ignoreCase){ if(value == e2){ diff --git a/lib/src/main/java/com/sandwich/util/KoanComparator.java b/lib/src/main/java/com/sandwich/util/KoanComparator.java index c7b02423..b41499ad 100755 --- a/lib/src/main/java/com/sandwich/util/KoanComparator.java +++ b/lib/src/main/java/com/sandwich/util/KoanComparator.java @@ -1,29 +1,15 @@ package com.sandwich.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import com.sandwich.koan.KoanMethod; import com.sandwich.util.io.directories.DirectoryManager; import com.sandwich.util.io.filecompiler.FileCompiler; public class KoanComparator implements Comparator { - List orderedKeywords; - Set methodNamesCompared = new HashSet(); - - public KoanComparator(String...koans){ - this(Arrays.asList(koans)); - } - - public KoanComparator(Collection koans){ - this.orderedKeywords = new ArrayList(koans); - } public int compare(KoanMethod arg0, KoanMethod arg1) { Class declaringClass0 = arg0.getMethod().getDeclaringClass(); @@ -33,9 +19,22 @@ public int compare(KoanMethod arg0, KoanMethod arg1) { return 0; } String contentsOfOriginalJavaFile = FileCompiler.getContentsOfJavaFile(DirectoryManager.getSourceDir(), declaringClass0.getName()); - Integer index0 = Integer.valueOf( contentsOfOriginalJavaFile.indexOf(arg0.getMethod().getName())); - Integer index1 = Integer.valueOf( contentsOfOriginalJavaFile.indexOf(arg1.getMethod().getName())); + String pattern = ".*\\s%s(\\(|\\s*\\))"; + Integer index0 = indexOfMatch(contentsOfOriginalJavaFile, String.format(pattern, arg0.getMethod().getName())); + Integer index1 = indexOfMatch(contentsOfOriginalJavaFile, String.format(pattern, arg1.getMethod().getName())); return index0.compareTo(index1); } + + /* + * TODO: This is utility code... + */ + private int indexOfMatch(String inputString, String pattern) { + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(inputString); + if (m.find()) { + return m.start(); + } + return -1; + } } \ No newline at end of file diff --git a/lib/src/main/java/com/sandwich/util/io/ExistingFileAction.java b/lib/src/main/java/com/sandwich/util/io/ExistingFileAction.java index f082da5c..fb6e6f10 100644 --- a/lib/src/main/java/com/sandwich/util/io/ExistingFileAction.java +++ b/lib/src/main/java/com/sandwich/util/io/ExistingFileAction.java @@ -5,6 +5,10 @@ public abstract class ExistingFileAction extends FileOperation { + public ExistingFileAction(String... strings) { + super(strings); + } + public void onNull(File file) throws IOException { throwNonExistentFileError(String.valueOf(file)); } diff --git a/lib/src/main/java/com/sandwich/util/io/FileMonitor.java b/lib/src/main/java/com/sandwich/util/io/FileMonitor.java index d90c5e64..eb9f1415 100644 --- a/lib/src/main/java/com/sandwich/util/io/FileMonitor.java +++ b/lib/src/main/java/com/sandwich/util/io/FileMonitor.java @@ -7,6 +7,8 @@ import java.util.Map; import java.util.Vector; +import com.sandwich.koan.ApplicationSettings; + public class FileMonitor { private final List listeners = new Vector(); @@ -69,7 +71,7 @@ synchronized void notifyListeners(){ Map getFilesystemHashes() throws IOException { final HashMap fileHashes = new HashMap(); - new ForEachFileAction(){ + new ForEachFileAction(ApplicationSettings.getMonitorIgnorePattern()){ public void onFile(File src) throws IOException { fileHashes.put(src.getAbsolutePath(), src.lastModified()); } diff --git a/lib/src/main/java/com/sandwich/util/io/FileOperation.java b/lib/src/main/java/com/sandwich/util/io/FileOperation.java index c6e2e167..1cea8894 100644 --- a/lib/src/main/java/com/sandwich/util/io/FileOperation.java +++ b/lib/src/main/java/com/sandwich/util/io/FileOperation.java @@ -2,19 +2,48 @@ import java.io.File; import java.io.IOException; +import java.util.Arrays; +import java.util.List; public abstract class FileOperation implements FileAction { + private List ignoredPaths; + + public FileOperation(String... ignoredPaths){ + this(Arrays.asList(ignoredPaths)); + } + + public FileOperation(List ignoredPaths){ + this.ignoredPaths = ignoredPaths; + } + public void operate(File file) throws IOException { - if(file == null){ - onNull(file); - }else if(!file.exists()){ - onNew(file); - }else if(file.isDirectory()){ - onDirectory(file); - }else{ - onFile(file); + if(!isIgnored(file)){ + if(file == null){ + onNull(file); + }else if(!file.exists()){ + onNew(file); + }else if(file.isDirectory()){ + onDirectory(file); + }else{ + onFile(file); + } + } + } + + boolean isIgnored(File file){ + boolean ignore = false; + while(file != null){ + String end = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(System.getProperty("file.separator")) + 1); + for(String pathToIgnore: ignoredPaths){ + ignore = end.matches(pathToIgnore); + if(ignore){ + return true; + } + } + file = file.getParentFile(); } + return ignore; } } diff --git a/lib/src/main/java/com/sandwich/util/io/ForEachFileAction.java b/lib/src/main/java/com/sandwich/util/io/ForEachFileAction.java index 44499b77..cfd04179 100644 --- a/lib/src/main/java/com/sandwich/util/io/ForEachFileAction.java +++ b/lib/src/main/java/com/sandwich/util/io/ForEachFileAction.java @@ -5,6 +5,10 @@ public abstract class ForEachFileAction extends ExistingFileAction { + public ForEachFileAction(String... strings) { + super(strings); + } + public void onDirectory(File dir) throws IOException { for (String fileName : dir.list()) { operate(new File(dir, fileName)); diff --git a/lib/src/main/java/com/sandwich/util/io/StreamUtils.java b/lib/src/main/java/com/sandwich/util/io/StreamUtils.java index 3c562893..1038ce97 100644 --- a/lib/src/main/java/com/sandwich/util/io/StreamUtils.java +++ b/lib/src/main/java/com/sandwich/util/io/StreamUtils.java @@ -7,10 +7,13 @@ public class StreamUtils { public static String convertStreamToString(InputStream stream) { + Scanner scanner = new Scanner(stream); try { - return new Scanner(stream).useDelimiter("\\A").next(); + return scanner.useDelimiter("\\A").next(); } catch (NoSuchElementException e) { return ""; + } finally { + scanner.close(); } } diff --git a/lib/src/test/java/com/sandwich/koan/TestUtilsTest.java b/lib/src/test/java/com/sandwich/koan/TestUtilsTest.java index ad047315..19ccd88a 100755 --- a/lib/src/test/java/com/sandwich/koan/TestUtilsTest.java +++ b/lib/src/test/java/com/sandwich/koan/TestUtilsTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.fail; import org.easymock.EasyMock; +import org.junit.Ignore; import org.junit.Test; import com.sandwich.koan.TestUtils.ArgRunner; @@ -146,7 +147,7 @@ public int hashCode(){ } } - @Test(expected=AssertionError.class, timeout=1000) + @Test(expected=AssertionError.class, timeout=2000) public void testEqualsConcurrency_concurrentAccessFails() throws Exception { TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { public void assertOn(String msg, Object o0, Object o1) { @@ -197,7 +198,7 @@ public void run() { }); } - @Test + @Test @Ignore // disk/os access causing random failures at this low a deviation in timing public void testEqualsConcurrency() throws Exception { TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { public void assertOn(String msg, Object o0, Object o1) { @@ -218,7 +219,7 @@ public void run() { }); } - @Test + @Test @Ignore // disk/os access causing random failures at this low a deviation in timing public void testEqualsConcurrency_II() throws Exception { TestUtils.doSimultaneouslyAndRepetitively(new TwoObjectAssertion() { public void assertOn(String msg, Object o0, Object o1) { diff --git a/lib/src/test/java/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java b/lib/src/test/java/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java index 581b542e..ae156b72 100755 --- a/lib/src/test/java/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java +++ b/lib/src/test/java/com/sandwich/koan/runner/AppReadinessForDeploymentTest.java @@ -15,7 +15,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.junit.Ignore; import com.sandwich.koan.KoanMethod; import com.sandwich.koan.cmdline.CommandLineArgumentBuilder; @@ -94,7 +93,7 @@ public void testGetKoans() throws Exception { KoanMethod.getInstance(entry.getValue().get("koan")).getMethod().toString()); } - @Test @Ignore /** Ensures that koans are ready for packaging & distribution */ + @Test public void testKoanSuiteRunner_firstKoanFail() throws Exception { final KoanSuiteResult[] result = new KoanSuiteResult[]{null}; stubPresenter(new SuitePresenter(){ @@ -116,7 +115,7 @@ public void run(){ assertEquals(result[0].getFailingCase(), firstSuiteClassRan.substring(firstSuiteClassRan.lastIndexOf(".") + 1)); } - @Test @Ignore /** Ensures that koans are ready for packaging & distribution */ + @Test public void testKoanSuiteRunner_allKoansFail() throws Exception { setRealPath(); final KoanSuiteResult[] result = new KoanSuiteResult[]{null}; diff --git a/lib/src/test/java/com/sandwich/util/KoanComparatorTest.java b/lib/src/test/java/com/sandwich/util/KoanComparatorTest.java index ef16fb86..8b709d23 100755 --- a/lib/src/test/java/com/sandwich/util/KoanComparatorTest.java +++ b/lib/src/test/java/com/sandwich/util/KoanComparatorTest.java @@ -15,12 +15,16 @@ public class KoanComparatorTest extends CommandLineTestCase { + interface Caps { + public String capitalize(String name); + } + @Test public void testThatKomparatorBombsWhenNotFound() throws Exception { Method m = new Object(){ @Koan public void someMethod(){} }.getClass().getDeclaredMethod("someMethod"); - KoanComparator comparator = new KoanComparator("meh"); + KoanComparator comparator = new KoanComparator(); try{ comparator.compare(KoanMethod.getInstance("2",m), KoanMethod.getInstance("1",m)); }catch(RuntimeException fileNotFound){} @@ -35,9 +39,25 @@ public void testComparatorRanksByOrder() throws Exception { KoanMethod m1 = KoanMethod.getInstance("",clazz.getDeclaredMethod("someMethodOne")); KoanMethod m2 = KoanMethod.getInstance("",clazz.getDeclaredMethod("someMethodTwo")); List methods = Arrays.asList(m2,m1); - Collections.sort(methods, new KoanComparator("someMethodOne","someMethodTwo")); + Collections.sort(methods, new KoanComparator()); assertSame(m1,methods.get(0)); assertSame(m2,methods.get(1)); } + + @Test + public void testVariableNamesArentConfusedAsKoanMethodsWhenSorting() throws Exception { + Class clazz = new Object(){ + @SuppressWarnings("unused") + String foo; + @Koan public void bar(){} + @Koan public void foo(){} + }.getClass(); + KoanMethod m1 = KoanMethod.getInstance("", clazz.getDeclaredMethod("bar")); + KoanMethod m2 = KoanMethod.getInstance("", clazz.getDeclaredMethod("foo")); + List methods = Arrays.asList(m2,m1); + Collections.sort(methods, new KoanComparator()); + assertSame(m1,methods.get(0)); + assertSame(m2,methods.get(1)); + } } diff --git a/lib/src/test/java/com/sandwich/util/io/FileOperationTest.java b/lib/src/test/java/com/sandwich/util/io/FileOperationTest.java new file mode 100644 index 00000000..f24a8b5a --- /dev/null +++ b/lib/src/test/java/com/sandwich/util/io/FileOperationTest.java @@ -0,0 +1,96 @@ +package com.sandwich.util.io; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import com.sandwich.util.io.directories.DirectoryManager; + +public class FileOperationTest { + + @Test + public void givenAnExistingFileNoFilterIsNotIgnored() throws Exception { + assertFalse(new FileOperation() { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenAnExistingFileWithNonMatchingFilterIsNotIgnored() throws Exception { + assertFalse(new FileOperation("nowayimpartofafoldername") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenAnExistingFileWithMatchingFilterIsIgnored() throws Exception { + assertTrue(new FileOperation("bin") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenAnExistingFileWithFilterMatchingOnParentFolderIsIgnored() throws Exception { + assertTrue(new FileOperation("app") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenAnExistingFileWithPartiallyMatchingFilterIsNotIgnored() throws Exception { + assertFalse(new FileOperation("bi") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenAnExistingFileWithRegexMatchingFilterIsIgnored() throws Exception { + assertTrue(new FileOperation("b.n") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenAnExistingFileWithRegexMatchingFilterIsIgnored_compliment() throws Exception { + assertFalse(new FileOperation("nowayimpart..afoldername") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File(DirectoryManager.getBinDir()))); + } + + @Test + public void givenIntellijFoldersSpecificallyFileInIdeaFolderAreIgnored() throws Exception { + // not sure why idea ide's would be a problem... TODO: testing this specifically smells like a bigger problem... + assertTrue(new FileOperation(".*\\.idea") { + public void onDirectory(File dir) throws IOException {} + public void onFile(File file) throws IOException {} + public void onNull(File nullFile) throws IOException {} + public void onNew(File newFile) throws IOException {} + }.isIgnored(new File("/java-dojo/labs/01-koans/java-koans\\koans.idea/workspace.xml___jb_old___"))); + } + +}