use of com.puppycrawl.tools.checkstyle.utils.CommonUtil in project checkstyle by checkstyle.
the class PropertyCacheFileTest method testPutNonExistentExternalResource.
/**
* This test invokes {@code putExternalResources} twice to invalidate cache.
* And asserts that two different exceptions produces different content,
* but two exceptions with same message produces one shared content.
*
* @param rawMessages exception messages separated by ';'
*/
@ParameterizedTest
@ValueSource(strings = { "Same;Same", "First;Second" })
public void testPutNonExistentExternalResource(String rawMessages) throws Exception {
final File cacheFile = File.createTempFile("junit", null, temporaryFolder);
final String[] messages = rawMessages.split(";");
// throw CheckstyleException with the specific content.
try (MockedStatic<CommonUtil> commonUtil = mockStatic(CommonUtil.class)) {
final int numberOfRuns = messages.length;
final String[] configHashes = new String[numberOfRuns];
final String[] externalResourceHashes = new String[numberOfRuns];
for (int i = 0; i < numberOfRuns; i++) {
commonUtil.when(() -> CommonUtil.getUriByFilename(any(String.class))).thenThrow(new CheckstyleException(messages[i]));
final Configuration config = new DefaultConfiguration("myConfig");
final PropertyCacheFile cache = new PropertyCacheFile(config, cacheFile.getPath());
cache.load();
configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY);
assertWithMessage("Config hash key should not be null").that(configHashes[i]).isNotNull();
final Set<String> nonExistentExternalResources = new HashSet<>();
final String externalResourceFileName = "non_existent_file.xml";
nonExistentExternalResources.add(externalResourceFileName);
cache.putExternalResources(nonExistentExternalResources);
externalResourceHashes[i] = cache.get(PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX + externalResourceFileName);
assertWithMessage("External resource hashes should not be null").that(externalResourceHashes[i]).isNotNull();
cache.persist();
final Properties cacheDetails = new Properties();
try (BufferedReader reader = Files.newBufferedReader(cacheFile.toPath())) {
cacheDetails.load(reader);
}
assertWithMessage("Unexpected number of objects in cache").that(cacheDetails).hasSize(2);
}
assertWithMessage("Invalid config hash").that(configHashes[0]).isEqualTo(configHashes[1]);
final boolean sameException = messages[0].equals(messages[1]);
assertWithMessage("Invalid external resource hashes").that(externalResourceHashes[0].equals(externalResourceHashes[1])).isEqualTo(sameException);
}
}
Aggregations