Search in sources :

Example 1 with ComparisonFailure

use of junit.framework.ComparisonFailure in project junit4 by junit-team.

the class ComparisonFailureTest method testConnection.

// Most of the tests are in ComparisonCompactorTest
public void testConnection() {
    ComparisonFailure failure = new ComparisonFailure("warning", "Mary had a little lamb", "Mary had the little lamb");
    assertEquals("warning expected:<Mary had [a] little lamb> but was:<Mary had [the] little lamb>", failure.getMessage());
}
Also used : ComparisonFailure(junit.framework.ComparisonFailure)

Example 2 with ComparisonFailure

use of junit.framework.ComparisonFailure in project spring-security by spring-projects.

the class SecurityContextHolderMTTests method makeThread.

private Thread makeThread(final String threadIdentifier, final boolean topLevelThread, final boolean injectAuthIntoCurrentThread, final boolean expectAllThreadsToUseIdenticalAuthentication, final boolean expectChildrenToShareAuthenticationWithParent, final String expectedUsername) {
    final Random rnd = new Random();
    Thread t = new Thread(new Runnable() {

        public void run() {
            if (injectAuthIntoCurrentThread) {
                // Set authentication in this thread
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(expectedUsername, "pass"));
            //System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());
            } else {
            //System.out.println(threadIdentifier + " - not set (currently " + SecurityContextHolder.getContext().getAuthentication() + ")");
            }
            // Do some operations in current thread, checking authentication is as expected in the current thread (ie another thread doesn't change it)
            for (int i = 0; i < NUM_OPS; i++) {
                String currentUsername = (SecurityContextHolder.getContext().getAuthentication() == null) ? null : SecurityContextHolder.getContext().getAuthentication().getName();
                if ((i % 7) == 0) {
                    System.out.println(threadIdentifier + " at " + i + " username " + currentUsername);
                }
                try {
                    assertEquals("Failed on iteration " + i + "; Authentication was '" + currentUsername + "' but principal was expected to contain username '" + expectedUsername + "'", expectedUsername, currentUsername);
                } catch (ComparisonFailure err) {
                    errors++;
                    throw err;
                }
                try {
                    Thread.sleep(rnd.nextInt(250));
                } catch (InterruptedException ignore) {
                }
            }
            // Load some children threads, checking the authentication is as expected in the children (ie another thread doesn't change it)
            if (topLevelThread) {
                // Make four children, but we don't want the children to have any more children (so anti-nature, huh?)
                if (injectAuthIntoCurrentThread && expectChildrenToShareAuthenticationWithParent) {
                    loadStartAndWaitForThreads(false, threadIdentifier, 4, expectAllThreadsToUseIdenticalAuthentication, true);
                } else {
                    loadStartAndWaitForThreads(false, threadIdentifier, 4, expectAllThreadsToUseIdenticalAuthentication, false);
                }
            }
        }
    }, threadIdentifier);
    return t;
}
Also used : Random(java.util.Random) ComparisonFailure(junit.framework.ComparisonFailure) UsernamePasswordAuthenticationToken(org.springframework.security.providers.UsernamePasswordAuthenticationToken)

Example 3 with ComparisonFailure

use of junit.framework.ComparisonFailure in project kotlin by JetBrains.

the class AbstractQuickFixMultiFileTest method doTest.

private void doTest(final String beforeFileName, boolean withExtraFile) throws Exception {
    String testDataPath = getTestDataPath();
    File mainFile = new File(testDataPath + beforeFileName);
    final String originalFileText = FileUtil.loadFile(mainFile, true);
    boolean withRuntime = InTextDirectivesUtils.isDirectiveDefined(originalFileText, "// WITH_RUNTIME");
    boolean fullJdk = InTextDirectivesUtils.isDirectiveDefined(originalFileText, "// FULL_JDK");
    if (withRuntime) {
        ConfigLibraryUtil.configureKotlinRuntimeAndSdk(myModule, fullJdk ? PluginTestCaseBase.fullJdk() : PluginTestCaseBase.mockJdk());
    }
    try {
        if (withExtraFile) {
            File mainFileDir = mainFile.getParentFile();
            assert mainFileDir != null;
            final String mainFileName = mainFile.getName();
            File[] extraFiles = mainFileDir.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(@NotNull File dir, @NotNull String name) {
                    return name.startsWith(extraFileNamePrefix(mainFileName)) && !name.equals(mainFileName);
                }
            });
            assert extraFiles != null;
            List<String> testFiles = new ArrayList<String>();
            testFiles.add(beforeFileName);
            ArraysKt.mapTo(extraFiles, testFiles, new Function1<File, String>() {

                @Override
                public String invoke(File file) {
                    return beforeFileName.replace(mainFileName, file.getName());
                }
            });
            configureByFiles(null, ArrayUtil.toStringArray(testFiles));
        } else {
            configureByFiles(null, beforeFileName);
        }
        CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {

            @Override
            public void run() {
                try {
                    PsiFile psiFile = getFile();
                    Pair<String, Boolean> pair = LightQuickFixTestCase.parseActionHint(psiFile, originalFileText);
                    String text = pair.getFirst();
                    boolean actionShouldBeAvailable = pair.getSecond();
                    if (psiFile instanceof KtFile) {
                        DirectiveBasedActionUtils.INSTANCE.checkForUnexpectedErrors((KtFile) psiFile);
                    }
                    doAction(text, actionShouldBeAvailable, beforeFileName);
                    if (actionShouldBeAvailable) {
                        String afterFilePath = beforeFileName.replace(".before.Main.", ".after.");
                        try {
                            checkResultByFile(afterFilePath);
                        } catch (ComparisonFailure e) {
                            KotlinTestUtils.assertEqualsToFile(new File(afterFilePath), getEditor());
                        }
                        PsiFile mainFile = myFile;
                        String mainFileName = mainFile.getName();
                        for (PsiFile file : mainFile.getContainingDirectory().getFiles()) {
                            String fileName = file.getName();
                            if (fileName.equals(mainFileName) || !fileName.startsWith(extraFileNamePrefix(myFile.getName())))
                                continue;
                            String extraFileFullPath = beforeFileName.replace(mainFileName, fileName);
                            File afterFile = new File(extraFileFullPath.replace(".before.", ".after."));
                            if (afterFile.exists()) {
                                KotlinTestUtils.assertEqualsToFile(afterFile, file.getText());
                            } else {
                                KotlinTestUtils.assertEqualsToFile(new File(extraFileFullPath), file.getText());
                            }
                        }
                    }
                } catch (ComparisonFailure e) {
                    throw e;
                } catch (AssertionError e) {
                    throw e;
                } catch (Throwable e) {
                    e.printStackTrace();
                    fail(getTestName(true));
                }
            }
        }, "", "");
    } finally {
        if (withRuntime) {
            ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(myModule, fullJdk ? PluginTestCaseBase.fullJdk() : PluginTestCaseBase.mockJdk());
        }
    }
}
Also used : FilenameFilter(java.io.FilenameFilter) ComparisonFailure(junit.framework.ComparisonFailure) PsiFile(com.intellij.psi.PsiFile) KtFile(org.jetbrains.kotlin.psi.KtFile) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFile(com.intellij.psi.PsiFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) Pair(com.intellij.openapi.util.Pair)

Example 4 with ComparisonFailure

use of junit.framework.ComparisonFailure in project intellij-community by JetBrains.

the class LightQuickFixTestCase method doTestFor.

private static void doTestFor(@NotNull String testName, @NotNull QuickFixTestCase quickFixTestCase) {
    final String relativePath = ObjectUtils.notNull(quickFixTestCase.getBasePath(), "") + "/" + BEFORE_PREFIX + testName;
    final String testFullPath = quickFixTestCase.getTestDataPath().replace(File.separatorChar, '/') + relativePath;
    final File testFile = new File(testFullPath);
    CommandProcessor.getInstance().executeCommand(quickFixTestCase.getProject(), () -> {
        try {
            String contents = StringUtil.convertLineSeparators(FileUtil.loadFile(testFile, CharsetToolkit.UTF8_CHARSET));
            quickFixTestCase.configureFromFileText(testFile.getName(), contents);
            quickFixTestCase.bringRealEditorBack();
            final ActionHint actionHint = quickFixTestCase.parseActionHintImpl(quickFixTestCase.getFile(), contents);
            quickFixTestCase.beforeActionStarted(testName, contents);
            try {
                myWrapper = quickFixTestCase;
                quickFixTestCase.doAction(actionHint, testFullPath, testName);
            } finally {
                myWrapper = null;
                quickFixTestCase.afterActionCompleted(testName, contents);
            }
        } catch (ComparisonFailure e) {
            throw e;
        } catch (Throwable e) {
            e.printStackTrace();
            Assert.fail(testName + " failed");
        }
    }, "", "");
}
Also used : ComparisonFailure(junit.framework.ComparisonFailure) File(java.io.File) PsiFile(com.intellij.psi.PsiFile)

Example 5 with ComparisonFailure

use of junit.framework.ComparisonFailure in project intellij-plugins by JetBrains.

the class DartStyleTest method runTestInDirectory.

/**
   * Run a test defined in "*.unit" or "*.stmt" file inside directory <code>dirName</code>.
   * Only signal failures for tests that fail and are not listed in <code>knownFailures.</code>
   */
protected void runTestInDirectory(String dirName, Set knownFailures) throws Exception {
    Pattern indentPattern = Pattern.compile("^.*\\s\\(indent (\\d+)\\)\\s*");
    String testName = getTestName(true);
    if (Character.isLetter(testName.charAt(0)) && Character.isDigit(testName.charAt(testName.length() - 1))) {
        testName = testName.substring(0, testName.length() - 1);
    }
    File dir = new File(new File(getTestDataPath(), getBasePath()), dirName);
    boolean found = false;
    final StringBuilder combinedActualResult = new StringBuilder();
    final StringBuilder combinedExpectedResult = new StringBuilder();
    for (String ext : new String[] { ".stmt", ".unit" }) {
        String testFileName = testName + ext;
        File entry = new File(dir, testFileName);
        if (!entry.exists()) {
            continue;
        }
        found = true;
        String[] lines = ArrayUtil.toStringArray(FileUtil.loadLines(entry, "UTF-8"));
        boolean isCompilationUnit = entry.getName().endsWith(".unit");
        // The first line may have a "|" to indicate the page width.
        int pageWidth = 80;
        int i = 0;
        if (lines[0].endsWith("|")) {
            // As it happens, this is always 40 except for some files in 'regression'
            pageWidth = lines[0].indexOf("|");
            i = 1;
        }
        // Adjust for indent in case test is near margin.
        if (!isCompilationUnit)
            pageWidth += 2;
        System.out.println("\nTest: " + dirName + "/" + testFileName + ", Right margin: " + pageWidth);
        final CommonCodeStyleSettings settings = getSettings(DartLanguage.INSTANCE);
        settings.RIGHT_MARGIN = pageWidth;
        // TODO Decide whether this should be the default -- risky!
        settings.KEEP_LINE_BREAKS = false;
        settings.KEEP_BLANK_LINES_IN_CODE = 1;
        while (i < lines.length) {
            String description = (dirName + "/" + testFileName + ":" + (i + 1) + " " + lines[i++].replaceAll(">>>", "")).trim();
            // Let the test specify a leading indentation. This is handy for
            // regression tests which often come from a chunk of nested code.
            int leadingIndent = 0;
            Matcher matcher = indentPattern.matcher(description);
            if (matcher.matches()) {
                // The leadingIndent is only used by some tests in 'regression'.
                leadingIndent = Integer.parseInt(matcher.group(1));
                settings.RIGHT_MARGIN = pageWidth - leadingIndent;
            }
            String input = "";
            // The formatter fails horribly otherwise.
            if (!isCompilationUnit)
                input += "m() {\n";
            while (!lines[i].startsWith("<<<")) {
                String line = lines[i++];
                if (leadingIndent > 0 && leadingIndent < line.length())
                    line = line.substring(leadingIndent);
                if (!isCompilationUnit && !line.isEmpty())
                    line = "  " + line;
                input += line + "\n";
            }
            if (!isCompilationUnit)
                input += "}\n";
            String expectedOutput = "";
            if (!isCompilationUnit)
                expectedOutput += "m() {\n";
            i++;
            while (i < lines.length && !lines[i].startsWith(">>>")) {
                String line = lines[i++];
                if (leadingIndent > 0 && leadingIndent < line.length())
                    line = line.substring(leadingIndent);
                if (!isCompilationUnit && !line.isEmpty())
                    line = "  " + line;
                expectedOutput += line + "\n";
            }
            if (!isCompilationUnit)
                expectedOutput += "}\n";
            SourceCode inputCode = extractSourceSelection(input, expectedOutput, isCompilationUnit);
            SourceCode expected = extractSelection(expectedOutput, isCompilationUnit);
            try {
                doTextTest(inputCode.text, expected.text);
                if (knownFailures.contains(description)) {
                    fail("The test passed, but was expected to fail: " + description);
                }
                System.out.println("TEST PASSED: " + (description.isEmpty() ? "(unnamed)" : description));
            } catch (ComparisonFailure failure) {
                if (!knownFailures.contains(description.replace('"', '\''))) {
                    combinedExpectedResult.append("TEST: ").append(description).append("\n").append(failure.getExpected()).append("\n");
                    combinedActualResult.append("TEST: ").append(description).append("\n").append(failure.getActual()).append("\n");
                }
            }
        }
    }
    if (!found) {
        fail("No test data for " + testName);
    }
    assertEquals(combinedExpectedResult.toString(), combinedActualResult.toString());
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ComparisonFailure(junit.framework.ComparisonFailure) CommonCodeStyleSettings(com.intellij.psi.codeStyle.CommonCodeStyleSettings) File(java.io.File)

Aggregations

ComparisonFailure (junit.framework.ComparisonFailure)10 File (java.io.File)5 PsiFile (com.intellij.psi.PsiFile)4 KtFile (org.jetbrains.kotlin.psi.KtFile)3 Pair (com.intellij.openapi.util.Pair)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 EditorWindow (com.intellij.injected.editor.EditorWindow)1 com.intellij.openapi.fileEditor (com.intellij.openapi.fileEditor)1 Project (com.intellij.openapi.project.Project)1 CommonCodeStyleSettings (com.intellij.psi.codeStyle.CommonCodeStyleSettings)1 BaseRefactoringProcessor (com.intellij.refactoring.BaseRefactoringProcessor)1 CommonRefactoringUtil (com.intellij.refactoring.util.CommonRefactoringUtil)1 FileComparisonFailure (com.intellij.rt.execution.junit.FileComparisonFailure)1 FilenameFilter (java.io.FilenameFilter)1 Map (java.util.Map)1 Random (java.util.Random)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 AssertionFailedError (junit.framework.AssertionFailedError)1 Ptg (org.apache.poi.ss.formula.ptg.Ptg)1