Commit 3199a0a5 authored by Adam Blank's avatar Adam Blank
Browse files

Initial commit

parents
No related merge requests found
Pipeline #7869 canceled with stage
Showing with 1139 additions and 0 deletions
+1139 -0
[equity, prow]
[owe, pry, quit]
[owe, quip, try]
[owe, quit, pry]
[owe, try, quip]
[per, quit, yow]
[per, yow, quit]
[pet, quo, wiry]
[pet, wiry, quo]
[pow, quit, rye]
[pow, rye, quit]
[prey, quo, wit]
[prey, wit, quo]
[prow, equity]
[pry, owe, quit]
[pry, quit, owe]
[pry, quit, woe]
[pry, woe, quit]
[pyre, quo, wit]
[pyre, wit, quo]
[quip, owe, try]
[quip, ret, yow]
[quip, row, yet]
[quip, rye, tow]
[quip, rye, two]
[quip, toe, wry]
[quip, tow, rye]
[quip, try, owe]
[quip, try, woe]
[quip, two, rye]
[quip, woe, try]
[quip, wry, toe]
[quip, yet, row]
[quip, yow, ret]
[quit, owe, pry]
[quit, per, yow]
[quit, pow, rye]
[quit, pry, owe]
[quit, pry, woe]
[quit, rep, yow]
[quit, rye, pow]
[quit, rye, wop]
[quit, woe, pry]
[quit, wop, rye]
[quit, yow, per]
[quit, yow, rep]
[quo, pet, wiry]
[quo, prey, wit]
[quo, pyre, wit]
[quo, try, wipe]
[quo, wert, yip]
[quo, wipe, try]
[quo, wiry, pet]
[quo, wit, prey]
[quo, wit, pyre]
[quo, yip, wert]
[rep, quit, yow]
[rep, yow, quit]
[ret, quip, yow]
[ret, yow, quip]
[row, quip, yet]
[row, yet, quip]
[rye, pow, quit]
[rye, quip, tow]
[rye, quip, two]
[rye, quit, pow]
[rye, quit, wop]
[rye, tow, quip]
[rye, two, quip]
[rye, wop, quit]
[toe, quip, wry]
[toe, wry, quip]
[tow, quip, rye]
[tow, rye, quip]
[try, owe, quip]
[try, quip, owe]
[try, quip, woe]
[try, quo, wipe]
[try, wipe, quo]
[try, woe, quip]
[two, quip, rye]
[two, rye, quip]
[wert, quo, yip]
[wert, yip, quo]
[wipe, quo, try]
[wipe, try, quo]
[wiry, pet, quo]
[wiry, quo, pet]
[wit, prey, quo]
[wit, pyre, quo]
[wit, quo, prey]
[wit, quo, pyre]
[woe, pry, quit]
[woe, quip, try]
[woe, quit, pry]
[woe, try, quip]
[wop, quit, rye]
[wop, rye, quit]
[wry, quip, toe]
[wry, toe, quip]
[yet, quip, row]
[yet, row, quip]
[yip, quo, wert]
[yip, wert, quo]
[yow, per, quit]
[yow, quip, ret]
[yow, quit, per]
[yow, quit, rep]
[yow, rep, quit]
[yow, ret, quip]
\ No newline at end of file
listen
silent
tinsel
\ No newline at end of file
mate
meat
tame
team
\ No newline at end of file
one
\ No newline at end of file
plus
\ No newline at end of file
potato
\ No newline at end of file
twelve
\ No newline at end of file
won
\ No newline at end of file
zebra
\ No newline at end of file
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.caltech.cs2.helpers;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.junit.platform.commons.support.ReflectionSupport;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.allOf;
/**
* {@code @CaptureSystemOutput} is a JUnit JUpiter extension for capturing
* output to {@code System.out} and {@code System.err} with expectations
* supported via Hamcrest matchers.
*
* <h4>Example Usage</h4>
*
* <pre style="code">
* {@literal @}Test
* {@literal @}CaptureSystemOutput
* void systemOut(OutputCapture outputCapture) {
* outputCapture.expect(containsString("System.out!"));
*
* System.out.println("Printed to System.out!");
* }
*
* {@literal @}Test
* {@literal @}CaptureSystemOutput
* void systemErr(OutputCapture outputCapture) {
* outputCapture.expect(containsString("System.err!"));
*
* System.err.println("Printed to System.err!");
* }
* </pre>
*
* <p>Based on code from Spring Boot's
* <a href="https://github.com/spring-projects/spring-boot/blob/d3c34ee3d1bfd3db4a98678c524e145ef9bca51c/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/rule/OutputCapture.java">OutputCapture</a>
* rule for JUnit 4 by Phillip Webb and Andy Wilkinson.
*
* @author Sam Brannen
* @author Phillip Webb
* @author Andy Wilkinson
*/
@Target({TYPE, METHOD})
@Retention(RUNTIME)
@ExtendWith(CaptureSystemOutput.Extension.class)
public @interface CaptureSystemOutput {
class Extension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
@Override
public void beforeEach(ExtensionContext context) throws Exception {
getOutputCapture(context).captureOutput();
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
OutputCapture outputCapture = getOutputCapture(context);
try {
if (!outputCapture.matchers.isEmpty()) {
String output = outputCapture.toString();
assertThat(output, allOf(outputCapture.matchers));
}
} finally {
outputCapture.releaseOutput();
}
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
boolean isTestMethodLevel = extensionContext.getTestMethod().isPresent();
boolean isOutputCapture = parameterContext.getParameter().getType() == OutputCapture.class;
return isTestMethodLevel && isOutputCapture;
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return getOutputCapture(extensionContext);
}
private OutputCapture getOutputCapture(ExtensionContext context) {
return getOrComputeIfAbsent(getStore(context), OutputCapture.class);
}
private <V> V getOrComputeIfAbsent(Store store, Class<V> type) {
return store.getOrComputeIfAbsent(type, ReflectionSupport::newInstance, type);
}
private Store getStore(ExtensionContext context) {
return context.getStore(Namespace.create(getClass(), context.getRequiredTestMethod()));
}
}
/**
* {@code OutputCapture} captures output to {@code System.out} and {@code System.err}.
*
* <p>To obtain an instance of {@code OutputCapture}, declare a parameter of type
* {@code OutputCapture} in a JUnit Jupiter {@code @Test}, {@code @BeforeEach},
* or {@code @AfterEach} method.
*
* <p>{@linkplain #expect Expectations} are supported via Hamcrest matchers.
*
* <p>To obtain all output to {@code System.out} and {@code System.err}, simply
* invoke {@link #toString()}.
*
* @author Phillip Webb
* @author Andy Wilkinson
* @author Sam Brannen
*/
static class OutputCapture {
private final List<Matcher<? super String>> matchers = new ArrayList<>();
private CaptureOutputStream captureOut;
private CaptureOutputStream captureErr;
private ByteArrayOutputStream copy;
void captureOutput() {
this.copy = new ByteArrayOutputStream();
this.captureOut = new CaptureOutputStream(System.out, this.copy);
this.captureErr = new CaptureOutputStream(System.err, this.copy);
System.setOut(new PrintStream(this.captureOut));
System.setErr(new PrintStream(this.captureErr));
}
void releaseOutput() {
System.setOut(this.captureOut.getOriginal());
System.setErr(this.captureErr.getOriginal());
this.copy = null;
}
private void flush() {
try {
this.captureOut.flush();
this.captureErr.flush();
} catch (IOException ex) {
// ignore
}
}
/**
* Verify that the captured output is matched by the supplied {@code matcher}.
*
* <p>Verification is performed after the test method has executed.
*
* @param matcher the matcher
*/
public void expect(Matcher<? super String> matcher) {
this.matchers.add(matcher);
}
/**
* Return all captured output to {@code System.out} and {@code System.err}
* as a single string.
*/
@Override
public String toString() {
flush();
return this.copy.toString();
}
private static class CaptureOutputStream extends OutputStream {
private final PrintStream original;
private final OutputStream copy;
CaptureOutputStream(PrintStream original, OutputStream copy) {
this.original = original;
this.copy = copy;
}
PrintStream getOriginal() {
return this.original;
}
@Override
public void write(int b) throws IOException {
this.copy.write(b);
//this.original.write(b);
//this.original.flush();
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.copy.write(b, off, len);
//this.original.write(b, off, len);
}
@Override
public void flush() throws IOException {
this.copy.flush();
this.original.flush();
}
}
}
}
package edu.caltech.cs2.helpers;
import org.junit.jupiter.params.provider.ArgumentsSource;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@ArgumentsSource(FileSourceProvider.class)
public @interface FileSource {
String[] inputs();
String[] outputFiles();
}
package edu.caltech.cs2.helpers;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.support.AnnotationConsumer;
import org.junit.platform.commons.util.Preconditions;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.fail;
public class FileSourceProvider implements ArgumentsProvider, AnnotationConsumer<FileSource> {
private String[] inputs;
private String[] outputFiles;
@Override
public void accept(FileSource source) {
this.inputs = source.inputs();//Stream.of(source.inputs()).map((x) -> Arrays.asList(x.split("\\|"))).collect(Collectors.toList());
this.outputFiles = source.outputFiles();
}
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
Arguments[] args = new Arguments[this.outputFiles.length];
for (int i = 0; i < this.outputFiles.length; i++) {
String inputArgs = this.inputs[i];
Scanner in = getScanner(this.outputFiles[i]);
String output = in.useDelimiter("\\Z").next();
args[i] = Arguments.arguments(inputArgs, output);
}
return Stream.of(args);
}
private Scanner getScanner(String resource) {
Preconditions.notBlank(resource, "Test file " + resource + " must not be null or blank");
try {
return new Scanner(new File("tests/data/" + resource));
} catch (FileNotFoundException e) {
fail("Test file " + resource + " does not exist");
}
return null;
}
}
package edu.caltech.cs2.helpers;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.fail;
public class Reflection {
public static <T> T getFieldValue(Class clazz, String name, Object o) {
T result = null;
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return (T) field.get(o);
} catch (NoSuchFieldException | IllegalAccessException e) {
fail("Could not find field " + name + " in class " + clazz.getName());
return null;
}
}
public static <T> void setFieldValue(Class clazz, String name, Object o, Object v) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
field.set(o, v);
} catch (NoSuchFieldException | IllegalAccessException e) {
fail("Could not find field " + name + " in class " + clazz.getName());
}
}
public static Method getMethod(Class clazz, String name, Class<?>... params) {
Method method = null;
try {
method = clazz.getDeclaredMethod(name, params);
method.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
fail("Could not find method " + name + " in class " + clazz.getName());
return null;
}
return method;
}
public static Constructor getConstructor(Class clazz, Class<?>... params) {
Constructor c = null;
try {
c = clazz.getDeclaredConstructor(params);
c.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
fail("Could not find constructor " + clazz.getName() + "(" + String.join(", ", (String[])Stream.of(params).map(x -> x.getName()).collect(Collectors.toList()).toArray()) + ")" + " in class " + clazz.getName());
return null;
}
return c;
}
public static <T> T invoke(Method m, Object... args) {
T result = null;
try {
result = (T) m.invoke(args[0], Arrays.copyOfRange(args, 1, args.length));
} catch (IllegalAccessException | InvocationTargetException e) {
fail(e.getCause());
}
return result;
}
public static <T> T invokeStatic(Method m, Object... args) {
T result = null;
try {
result = (T) m.invoke(null, args);
} catch (IllegalAccessException | InvocationTargetException e) {
fail(e.getCause());
}
return result;
}
public static <T> T newInstance(Constructor c, Object... args) {
T result = null;
try {
result = (T) c.newInstance(args);
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException)e.getCause();
}
else {
fail(cause);
}
}
return result;
}
public static Stream<Field> getFields(Class clazz) {
return Stream.of(clazz.getDeclaredFields());
}
private static int stringToIntModifier(String modifier) {
switch (modifier.toLowerCase()) {
case "private": return Modifier.PRIVATE;
case "public": return Modifier.PUBLIC;
case "protected": return Modifier.PROTECTED;
case "static": return Modifier.STATIC;
case "final": return Modifier.FINAL;
default: fail("Unknown modifier test.");
}
/* Should never reach here... */
return -1;
}
public static Predicate<Member> hasModifier(String modifier) {
return (Member f) -> (f.getModifiers() & stringToIntModifier(modifier)) != 0;
}
public static Predicate<Member> doesNotHaveModifier(String modifier) {
return (Member f) -> (f.getModifiers() & stringToIntModifier(modifier)) == 0;
}
public static Predicate<Field> hasType(Class clazz) {
return (Field f) -> f.getType().equals(clazz);
}
public static Predicate<Field> doesNotHaveType(Class clazz) {
return (Field f) -> !f.getType().equals(clazz);
}
public static void assertFieldsLessThan(Class clazz, Class FieldType, int x) {
assertFieldsLessThan(clazz, null, FieldType, x );
}
public static void assertFieldsLessThan(Class clazz, String modifier, int x) {
assertFieldsLessThan(clazz, modifier, null, x);
}
public static void assertFieldsLessThan(Class clazz, Stream<Field> fields, int x) {
assertFieldsLessThan(clazz, fields, null, null, x );
}
public static void assertFieldsLessThan(Class clazz, String modifier, Class FieldType, int x) {
assertFieldsLessThan(clazz, getFields(clazz), modifier, FieldType, x);
}
public static void assertFieldsLessThan(Class clazz, Stream<Field> fields, String modifier, Class FieldType, int x) {
if (modifier != null) {
fields = fields.filter(hasModifier(modifier)).filter(doesNotHaveModifier("static"));
}
if (FieldType != null) {
fields = fields.filter(hasType(FieldType));
}
if (fields.count() >= x) {
fail(clazz.getName() + " has too many fields" +
(modifier != null ? " with modifier " + modifier : "") + "" +
(FieldType != null ? " of type " + FieldType.getName() : "")
);
}
}
public static void assertFieldsGreaterThan(Class clazz, Class FieldType, int x) {
assertFieldsGreaterThan(clazz, null, FieldType, x );
}
public static void assertFieldsGreaterThan(Class clazz, String modifier, int x) {
assertFieldsGreaterThan(clazz, modifier, null, x);
}
public static void assertFieldsGreaterThan(Class clazz, Stream<Field> fields, int x) {
assertFieldsGreaterThan(clazz, fields, null, null, x );
}
public static void assertFieldsGreaterThan(Class clazz, String modifier, Class FieldType, int x) {
assertFieldsGreaterThan(clazz, getFields(clazz), modifier, FieldType, x);
}
public static void assertFieldsGreaterThan(Class clazz, Stream<Field> fields, String modifier, Class FieldType, int x) {
if (modifier != null) {
fields = fields.filter(hasModifier(modifier));
}
if (FieldType != null) {
fields = fields.filter(hasType(FieldType));
}
if (fields.count() <= x) {
fail(clazz.getName() + " has too few fields" +
(modifier != null ? " with modifier " + modifier : "") + " " +
(FieldType != null ? " of type " + FieldType.getName() : "")
);
}
}
public static void assertFieldsEqualTo(Class clazz, Class FieldType, int x) {
assertFieldsEqualTo(clazz, null, FieldType, x );
}
public static void assertFieldsEqualTo(Class clazz, String modifier, int x) {
assertFieldsEqualTo(clazz, modifier, null, x );
}
public static void assertFieldsEqualTo(Class clazz, Stream<Field> fields, int x) {
assertFieldsEqualTo(clazz, fields, null, null, x );
}
public static void assertFieldsEqualTo(Class clazz, String modifier, Class FieldType, int x) {
assertFieldsEqualTo(clazz, getFields(clazz), modifier, FieldType, x);
}
public static void assertFieldsEqualTo(Class clazz, Stream<Field> fields, String modifier, Class FieldType, int x) {
if (modifier != null) {
fields = fields.filter(hasModifier(modifier));
}
if (FieldType != null) {
fields = fields.filter(hasType(FieldType));
}
if (fields.count() != x) {
fail(clazz.getName() + " has the wrong number of fields" +
(modifier != null ? " with modifier " + modifier : "") + " " +
(FieldType != null ? " of type " + FieldType.getName() : "")
);
}
}
public static void assertNoPublicFields(Class clazz) {
assertFieldsEqualTo(clazz, getFields(clazz).filter(doesNotHaveModifier("static")),
"public", null, 0);
}
public static Field getFieldByName(Class clazz, String name) {
try {
return clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
fail(clazz.getName() + " should have a field named '" + name + "', but does not.");
// Should not reach here!
return null;
}
}
public static Field getNonStaticFieldByType(Class clazz, Class FieldType) {
Stream<Field> fields = getFields(clazz).filter(hasType(FieldType)).filter(doesNotHaveModifier("static"));
List<Field> fieldsList = fields.collect(Collectors.toList());
if (fieldsList.isEmpty()) {
fail(clazz.getName() +
" should have a field with the type '" + FieldType.getName() +
"', but does not."
);
// Should not reach here!
return null;
}
if (fieldsList.size() > 1) {
fail(clazz.getName() +
" should only have one field with the type '" +
FieldType.getName() +
"', but has more."
);
// Should not reach here
return null;
}
return fieldsList.get(0);
}
public static Field getFieldByType(Class clazz, Class FieldType) {
Stream<Field> fields = getFields(clazz).filter(hasType(FieldType));
List<Field> fieldsList = fields.collect(Collectors.toList());
if (fieldsList.isEmpty()) {
fail(clazz.getName() +
" should have a field with the type '" + FieldType.getName() +
"', but does not."
);
// Should not reach here!
return null;
}
if (fieldsList.size() > 1) {
fail(clazz.getName() +
" should only have one field with the type '" +
FieldType.getName() +
"', but has more."
);
// Should not reach here
return null;
}
return fieldsList.get(0);
}
public static Field getFieldByModifiers(Class clazz, String modifier) {
return getFieldByModifiers(clazz, List.of(modifier));
}
public static Field getFieldByModifiers(Class clazz, List<String> modifiers) {
Stream<Field> fields = getFields(clazz);
for (String m : modifiers) {
fields = fields.filter(hasModifier(m));
}
List<Field> fieldsList = fields.collect(Collectors.toList());
if (fieldsList.isEmpty()) {
fail(clazz.getName() +
" should have a field with the modifiers '" +
String.join(", ", modifiers) +
"', but does not."
);
// Should not reach here!
return null;
}
if (fieldsList.size() > 1) {
fail(clazz.getName() +
" should only have one field with the modifiers '" +
String.join(", ", modifiers) +
"', but has more."
);
// Should not reach here
return null;
}
return fieldsList.get(0);
}
public static void checkFieldModifiers(Field f, String modifier) {
checkFieldModifiers(f, List.of(modifier));
}
public static void checkFieldModifiers(Field f, List<String> modifiers) {
if (!modifiers.stream().allMatch(m -> hasModifier(m).test(f))) {
fail(f.getName() + " is missing at least one of the modifiers: " + String.join(", ", modifiers));
}
}
public static void assertPublicInterface(Class clazz, List<String> methods) {
SortedSet<String> expected = new TreeSet<>(methods);
SortedSet<String> actual = new TreeSet<>(Stream.of(clazz.getDeclaredMethods())
.filter(hasModifier("public"))
.map(x -> x.getName())
.collect(Collectors.toList()));
if (!expected.equals(actual)) {
String diff = "expected: " + expected + "\nactual: " + actual;
fail("The public interface of " + clazz.getName() + " has incorrect functionality.\n" + diff);
}
}
public static void assertMethodCorrectlyOverridden(Class clazz, String method, Class<?>... params) {
Method studentc = getMethod(clazz, method, params);
Method superc = getMethod(clazz.getSuperclass(), method, params);
if (!studentc.getReturnType().equals(superc.getReturnType())) {
fail("You should be overriding the " + method + "method, but your signature wasn't correct.");
}
}
}
package edu.caltech.cs2.lab06;
import edu.caltech.cs2.helpers.CaptureSystemOutput;
import edu.caltech.cs2.helpers.FileSource;
import edu.caltech.cs2.helpers.Reflection;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@CaptureSystemOutput
public class PhraseAnagramsTests {
private static List getDictionary() throws FileNotFoundException {
Scanner input = new Scanner(new File("dictionaries/dictionary.txt"));
// Read dictionary into a List
List<String> dictionary = new ArrayList<String>();
while (input.hasNextLine()) {
dictionary.add(input.nextLine());
}
return dictionary;
}
private static List getDictionaryEleven() throws FileNotFoundException {
Scanner input = new Scanner(new File("dictionaries/eleven.txt"));
// Read dictionary into a List
List<String> dictionary = new ArrayList<String>();
while (input.hasNextLine()) {
dictionary.add(input.nextLine());
}
return dictionary;
}
@Order(1)
@Tag("B")
@DisplayName("AnagramGenerator has no instance fields")
@Test
public void testNoFields() {
Reflection.assertFieldsLessThan(AnagramGenerator.class, "private", 1);
Reflection.assertFieldsLessThan(AnagramGenerator.class, "public", 1);
}
@Order(2)
@Tag("B")
@DisplayName("Test printPhrases method in AnagramGenerator")
@ParameterizedTest(name = "{0}")
@FileSource(
inputs = {
"meat",
"listen",
"magikarp",
"qwertyuiop",
},
outputFiles = {
"phrase_meat.txt",
"phrase_listen.txt",
"phrase_magikarp.txt",
"phrase_qwertyuiop.txt",
}
)
public void testPrintPhrases(String word, String expectedOutput, CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printPhrases(word, dictionary);
assertEquals(expectedOutput.replace("\r\n", "\n").strip(), capture.toString().replace("\r\n", "\n").strip());
}
@Order(3)
@Tag("B")
@DisplayName("Test printPhrases method on empty string")
@Test
public void testPrintPhrasesEmpty(CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printPhrases("", dictionary);
assertEquals("[]", capture.toString().replace("\r\n", "\n").strip());
}
@Order(4)
@Tag("B")
@DisplayName("Test printPhrases method on null string")
@Test
public void testPrintPhrasesNull() {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
final List finalDictionary = dictionary;
assertThrows(NullPointerException.class, ()->{AnagramGenerator.printPhrases(null, finalDictionary);});
}
@Order(5)
@Tag("B")
@DisplayName("Test printPhrases method on string with a space")
@Test
public void testPrintPhrasesSpace(CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printPhrases(" ", dictionary);
assertEquals("[]", capture.toString().replace("\r\n", "\n").strip());
}
@Order(6)
@Tag("B")
@DisplayName("Test printPhrases method on string with no anagrams")
@Test
public void testPrintPhrasesNone(CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printPhrases("xyz", dictionary);
assertEquals("", capture.toString().replace("\r\n", "\n").strip());
}
@Order(7)
@Tag("B")
@DisplayName("Test printPhrases method on a phrase")
@ParameterizedTest(name = "{0}")
@FileSource(
inputs = {
"eleven plus two",
"two plus eleven",
},
outputFiles = {
"phrase_eleven.txt",
"phrase_eleven.txt",
}
)
public void testPrintWordsEleven(String word, String expectedOutput, CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionaryEleven();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printPhrases(word, dictionary);
assertEquals(expectedOutput.replace("\r\n", "\n").strip(), capture.toString().replace("\r\n", "\n").strip());
}
}
\ No newline at end of file
package edu.caltech.cs2.lab06;
import edu.caltech.cs2.helpers.CaptureSystemOutput;
import edu.caltech.cs2.helpers.FileSource;
import edu.caltech.cs2.helpers.Reflection;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@CaptureSystemOutput
public class WordAnagramsTests {
private static List getDictionary() throws FileNotFoundException {
Scanner input = new Scanner(new File("dictionaries/dictionary.txt"));
// Read dictionary into a List
List<String> dictionary = new ArrayList<String>();
while (input.hasNextLine()) {
dictionary.add(input.nextLine());
}
return dictionary;
}
private static List getDictionaryEleven() throws FileNotFoundException {
Scanner input = new Scanner(new File("dictionaries/eleven.txt"));
// Read dictionary into a List
List<String> dictionary = new ArrayList<String>();
while (input.hasNextLine()) {
dictionary.add(input.nextLine());
}
return dictionary;
}
@Order(1)
@Tag("A")
@DisplayName("AnagramGenerator has no instance fields")
@Test
public void testNoFields() {
Reflection.assertFieldsLessThan(AnagramGenerator.class, "private", 1);
Reflection.assertFieldsLessThan(AnagramGenerator.class, "public", 1);
}
@Order(2)
@Tag("A")
@DisplayName("Test printWords method in AnagramGenerator")
@ParameterizedTest(name = "{0}")
@FileSource(
inputs = {
"meat",
"listen",
},
outputFiles = {
"word_meat.txt",
"word_listen.txt",
}
)
public void testPrintWords(String word, String expectedOutput, CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printWords(word, dictionary);
assertEquals(expectedOutput.replace("\r\n", "\n").strip(), capture.toString().replace("\r\n", "\n").strip());
}
@Order(3)
@Tag("A")
@DisplayName("Test printWords method on empty string")
@Test
public void testPrintWordsEmpty(CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printWords("", dictionary);
assertEquals("", capture.toString().replace("\r\n", "\n").strip());
}
@Order(4)
@Tag("A")
@DisplayName("Test printWords method on null string")
@Test
public void testPrintWordsNull() {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
final List finalDictionary = dictionary;
assertThrows(NullPointerException.class, ()->{AnagramGenerator.printWords(null, finalDictionary);});
}
@Order(5)
@Tag("A")
@DisplayName("Test printWords method on string with a space")
@Test
public void testPrintWordsSpace(CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printWords(" ", dictionary);
assertEquals("", capture.toString().replace("\r\n", "\n").strip());
}
@Order(6)
@Tag("A")
@DisplayName("Test printWords method on string with no anagrams")
@Test
public void testPrintWordsNone(CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionary();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printWords("qwertyuiop", dictionary);
assertEquals("", capture.toString().replace("\r\n", "\n").strip());
}
@Order(7)
@Tag("A")
@DisplayName("Test printWords method on smaller dictionary")
@ParameterizedTest(name = "{0}")
@FileSource(
inputs = {
"one",
"plus",
"potato",
"twelve",
"won",
"zebra",
},
outputFiles = {
"word_one.txt",
"word_plus.txt",
"word_potato.txt",
"word_twelve.txt",
"word_won.txt",
"word_zebra.txt",
}
)
public void testPrintWordsEleven(String word, String expectedOutput, CaptureSystemOutput.OutputCapture capture) {
// Load the dictionary from the file
List dictionary = null;
try {
dictionary = getDictionaryEleven();
} catch (FileNotFoundException e) {
fail("Dictionary file not found");
}
AnagramGenerator.printWords(word, dictionary);
assertEquals(expectedOutput.replace("\r\n", "\n").strip(), capture.toString().replace("\r\n", "\n").strip());
}
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment