Skip to content

Commit

Permalink
Issue #3989: UTs should not use ROOT locale when they test violation/…
Browse files Browse the repository at this point in the history
…error message
  • Loading branch information
Luolc authored and romani committed Mar 14, 2017
1 parent c35ac64 commit 7c2f448
Show file tree
Hide file tree
Showing 13 changed files with 113 additions and 52 deletions.
Expand Up @@ -361,7 +361,7 @@ public String getSourceName() {
* @param locale the locale to use for localization
*/
public static void setLocale(Locale locale) {
BUNDLE_CACHE.clear();
clearCache();
if (Locale.ENGLISH.getLanguage().equals(locale.getLanguage())) {
sLocale = Locale.ROOT;
}
Expand Down Expand Up @@ -392,12 +392,12 @@ public int compareTo(LocalizedMessage other) {
/**
* <p>
* Custom ResourceBundle.Control implementation which allows explicitly read
* the properties files as UTF-8
* the properties files as UTF-8.
* </p>
*
* @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
*/
protected static class Utf8Control extends Control {
public static class Utf8Control extends Control {
@Override
public ResourceBundle newBundle(String aBaseName, Locale aLocale, String aFormat,
ClassLoader aLoader, boolean aReload) throws IOException {
Expand Down
@@ -1,5 +1,5 @@
indentation.error.multi=''{0}'' 缩进了{1}个缩进符,应为以下缩进之一:{2}。
indentation.child.error.multi=''{0}'' 子元素进了{1}个缩进符,应为以下缩进之一:{2}。
indentation.child.error.multi=''{0}'' 子元素缩进了{1}个缩进符,应为以下缩进之一:{2}。
indentation.error=''{0}'' 缩进了{1}个缩进符,应为{2}个。
indentation.child.error=''{0}'' 子元素缩进了{1}个缩进符,应为{2}个。
comments.indentation.single=注释应与第{0}行代码同样缩进{2}个缩进符,而不是{1}个。
Expand Down
Expand Up @@ -39,13 +39,14 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;

public class BaseCheckTestSupport {
protected final ByteArrayOutputStream stream = new ByteArrayOutputStream();
Expand All @@ -64,11 +65,6 @@ public Checker createChecker(Configuration checkConfig)
throws Exception {
final DefaultConfiguration dc = createCheckerConfig(checkConfig);
final Checker checker = new Checker();
// make sure the tests always run with default error messages (language-invariant)
// so the tests don't fail in supported locales like German
final Locale locale = Locale.ROOT;
checker.setLocaleCountry(locale.getCountry());
checker.setLocaleLanguage(locale.getLanguage());
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(dc);
checker.addListener(new BriefUtLogger(stream));
Expand Down Expand Up @@ -362,15 +358,54 @@ private Map<String, List<String>> getActualViolations(int errorCount) throws IOE
* @param arguments the arguments of message in 'messages.properties' file.
*/
protected String getCheckMessage(String messageKey, Object... arguments) {
final Properties pr = new Properties();
try {
pr.load(getClass().getResourceAsStream("messages.properties"));
}
catch (IOException ex) {
return null;
}
final MessageFormat formatter = new MessageFormat(pr.getProperty(messageKey),
Locale.ROOT);
return internalGetCheckMessage(getMessageBundle(), messageKey, arguments);
}

/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param clazz the related check class.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
*/
protected String getCheckMessage(
Class<?> clazz, String messageKey, Object... arguments) {
return internalGetCheckMessage(getMessageBundle(clazz.getName()), messageKey, arguments);
}

/**
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
* @param messageBundle the bundle name.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
*/
protected String internalGetCheckMessage(
String messageBundle, String messageKey, Object... arguments) {
final ResourceBundle resourceBundle = ResourceBundle.getBundle(
messageBundle,
Locale.getDefault(),
Thread.currentThread().getContextClassLoader(),
new LocalizedMessage.Utf8Control());
final String pattern = resourceBundle.getString(messageKey);
final MessageFormat formatter = new MessageFormat(pattern, Locale.ROOT);
return formatter.format(arguments);
}

private String getMessageBundle() {
final String className = getClass().getName();
return getMessageBundle(className);
}

private static String getMessageBundle(String className) {
final int endIndex = className.lastIndexOf('.');
final String messages = "messages";
if (endIndex < 0) {
return messages;
}
final String packageName = className.substring(0, endIndex);
return packageName + "." + messages;
}
}
Expand Up @@ -767,9 +767,6 @@ public void testHaltOnExceptionOff() throws Exception {
checkerConfig.addAttribute("haltOnException", "false");

final Checker checker = new Checker();
final Locale locale = Locale.ROOT;
checker.setLocaleCountry(locale.getCountry());
checker.setLocaleLanguage(locale.getLanguage());
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
checker.addListener(new BriefUtLogger(stream));
Expand Down
Expand Up @@ -19,6 +19,7 @@

package com.puppycrawl.tools.checkstyle;

import static com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck.MSG_INVALID_PATTERN;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

Expand Down Expand Up @@ -62,7 +63,8 @@ public void testProperFileExtension() throws Exception {
writer.write(content);
}
final String[] expected1 = {
"1:45: Name 'k' must match pattern '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'.",
"1:45: " + getCheckMessage(ConstantNameCheck.class,
MSG_INVALID_PATTERN, "k", "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"),
};
verify(checkConfig, file.getPath(), expected1);
}
Expand Down
Expand Up @@ -20,6 +20,7 @@
package com.puppycrawl.tools.checkstyle.checks;

import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_NO_NEWLINE_EOF;
import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_UNABLE_OPEN;
import static java.util.Locale.ENGLISH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
Expand Down Expand Up @@ -188,7 +189,7 @@ public void testWrongFile() throws Exception {
final Set<LocalizedMessage> messages = check.process(impossibleFile, lines);
assertEquals(1, messages.size());
final Iterator<LocalizedMessage> iterator = messages.iterator();
assertEquals("Unable to open ''.", iterator.next().getMessage());
assertEquals(getCheckMessage(MSG_KEY_UNABLE_OPEN, ""), iterator.next().getMessage());
}

@Test
Expand Down
Expand Up @@ -20,6 +20,7 @@
package com.puppycrawl.tools.checkstyle.checks;

import static com.puppycrawl.tools.checkstyle.checks.TranslationCheck.MSG_KEY;
import static com.puppycrawl.tools.checkstyle.checks.TranslationCheck.MSG_KEY_MISSING_TRANSLATION_FILE;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.junit.Assert.assertThat;
Expand Down Expand Up @@ -133,7 +134,8 @@ public void testDefaultTranslationFileIsMissing() throws Exception {
};

final String[] expected = {
"0: Properties file 'messages_translation.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"messages_translation.properties"),
};
verify(
createChecker(checkConfig),
Expand All @@ -153,7 +155,8 @@ public void testTranslationFilesAreMissing() throws Exception {
};

final String[] expected = {
"0: Properties file 'messages_translation_de.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"messages_translation_de.properties"),
};
verify(
createChecker(checkConfig),
Expand All @@ -172,7 +175,8 @@ public void testBaseNameWithSeparatorDefaultTranslationIsMissing() throws Except
};

final String[] expected = {
"0: Properties file 'messages-translation.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"messages-translation.properties"),
};
verify(
createChecker(checkConfig),
Expand All @@ -192,7 +196,8 @@ public void testBaseNameWithSeparatorTranslationsAreMissing() throws Exception {
};

final String[] expected = {
"0: Properties file 'messages-translation_tr.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"messages-translation_tr.properties"),
};
verify(
createChecker(checkConfig),
Expand Down Expand Up @@ -231,7 +236,8 @@ public void testTranslationFileWithLanguageCountryVariantIsMissing() throws Exce
};

final String[] expected = {
"0: Properties file 'messages_home_de.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"messages_home_de.properties"),
};
verify(
createChecker(checkConfig),
Expand Down Expand Up @@ -276,7 +282,8 @@ public void testBaseNameOption() throws Exception {
};

final String[] expected = {
"0: Properties file 'ButtonLabels_ja.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"ButtonLabels_ja.properties"),
};
verify(
createChecker(checkConfig),
Expand Down Expand Up @@ -305,7 +312,8 @@ public void testFileExtensions() throws Exception {
};

final String[] expected = {
"0: Properties file 'ButtonLabels_ja.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"ButtonLabels_ja.properties"),
};

verify(
Expand Down Expand Up @@ -335,7 +343,8 @@ public void testEqualBaseNamesButDifferentExtensions() throws Exception {
};

final String[] expected = {
"0: Properties file 'ButtonLabels_ja.properties' is missing.",
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE,
"ButtonLabels_ja.properties"),
};

verify(
Expand All @@ -359,9 +368,9 @@ public void testRegexpToMatchPartOfBaseName() throws Exception {
};

final String[] expected = {
"0: Properties file 'MyLabelsI18_fr.properties' is missing.",
"0: Properties file 'MyLabelsI18_ja.properties' is missing.",
};
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE, "MyLabelsI18_fr.properties"),
"0: " + getCheckMessage(MSG_KEY_MISSING_TRANSLATION_FILE, "MyLabelsI18_ja.properties"),
};

verify(
createChecker(checkConfig),
Expand Down
Expand Up @@ -30,7 +30,6 @@
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

import org.junit.Rule;
import org.junit.Test;
Expand Down Expand Up @@ -255,9 +254,6 @@ public void testCacheHeaderFile() throws Exception {
checkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath());

final Checker checker = new Checker();
final Locale locale = Locale.ROOT;
checker.setLocaleCountry(locale.getCountry());
checker.setLocaleLanguage(locale.getLanguage());
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
checker.addListener(new BriefUtLogger(stream));
Expand All @@ -282,9 +278,6 @@ public void testCacheHeaderWithoutFile() throws Exception {
checkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath());

final Checker checker = new Checker();
final Locale locale = Locale.ROOT;
checker.setLocaleCountry(locale.getCountry());
checker.setLocaleLanguage(locale.getLanguage());
checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
checker.configure(checkerConfig);
checker.addListener(new BriefUtLogger(stream));
Expand Down
Expand Up @@ -34,10 +34,12 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand All @@ -49,6 +51,7 @@
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;

/**
Expand Down Expand Up @@ -160,6 +163,9 @@ private void verify(Configuration config, String filePath, String[] expected,
final IndentComment... linesWithWarn) throws Exception {
final Checker checker = createChecker(config);
checker.addListener(new IndentAudit(linesWithWarn));
checker.setLocaleCountry(Locale.ROOT.getCountry());
checker.setLocaleLanguage(Locale.ROOT.getLanguage());
checker.finishLocalSetup();
verify(checker, new File[] {new File(filePath)}, filePath, expected);
}

Expand Down Expand Up @@ -785,8 +791,12 @@ public void testInvalidArrayInitWithChecker()
"112: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"),
};

final Checker checker = createChecker(checkConfig);
checker.setLocaleCountry(Locale.ROOT.getCountry());
checker.setLocaleLanguage(Locale.ROOT.getLanguage());
checker.finishLocalSetup();
//Test input for this test case is not checked due to issue #693.
verify(checkConfig, fileName, expected);
verify(checker, fileName, expected);
}

@Test
Expand Down Expand Up @@ -1737,6 +1747,19 @@ public void testInputAnnotationScopeIndentationCheck() throws Exception {
verifyWarns(checkConfig, fileName, expected);
}

@Override
protected String internalGetCheckMessage(
String messageBundle, String messageKey, Object... arguments) {
final ResourceBundle resourceBundle = ResourceBundle.getBundle(
messageBundle,
Locale.ROOT,
Thread.currentThread().getContextClassLoader(),
new LocalizedMessage.Utf8Control());
final String pattern = resourceBundle.getString(messageKey);
final MessageFormat formatter = new MessageFormat(pattern, Locale.ROOT);
return formatter.format(arguments);
}

private static final class IndentAudit implements AuditListener {
private final IndentComment[] comments;
private int position;
Expand Down
Expand Up @@ -20,8 +20,8 @@
package com.puppycrawl.tools.checkstyle.checks.javadoc;

import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.MSG_JAVADOC_MISSED_HTML_CLOSE;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.MSG_JAVADOC_PARSE_RULE_ERROR;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.MSG_JAVADOC_WRONG_SINGLETON_TAG;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.MSG_KEY_PARSE_ERROR;
import static com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.MSG_KEY_UNRECOGNIZED_ANTLR_ERROR;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
Expand Down Expand Up @@ -62,9 +62,9 @@ protected String getPath(String filename) throws IOException {
public void testNumberFormatException() throws Exception {
final DefaultConfiguration checkConfig = createCheckConfig(TempCheck.class);
final String[] expected = {
"3: " + getCheckMessage(MSG_KEY_PARSE_ERROR, 52, "no viable "
+ "alternative at input '<ul><li>a' {@link EntityEntry} (by way of {@link #;' "
+ "while parsing HTML_TAG"),
"3: " + getCheckMessage(MSG_JAVADOC_PARSE_RULE_ERROR, 52, "no viable "
+ "alternative at input '<ul><li>a' {@link EntityEntry} (by way of {@link #;'",
"HTML_TAG"),
};
verify(checkConfig, getPath("InputTestNumberFormatException.java"), expected);
}
Expand Down
Expand Up @@ -167,8 +167,7 @@ public void testWithoutLogErrors() throws Exception {
}
catch (CheckstyleException ex) {
final IllegalStateException cause = (IllegalStateException) ex.getCause();
assertEquals("Unable to get"
+ " class information for @throws tag 'InvalidExceptionName'.",
assertEquals(getCheckMessage(MSG_CLASS_INFO, "@throws", "InvalidExceptionName"),
cause.getMessage());
}
}
Expand Down

0 comments on commit 7c2f448

Please sign in to comment.