Search in sources :

Example 36 with PrepareForTest

use of org.powermock.core.classloader.annotations.PrepareForTest in project Bukkit_Bungee_PluginLib by GeorgH93.

the class ConfigurationTest method testSaveError.

@Test
@SuppressWarnings("ResultOfMethodCallIgnored")
@PrepareForTest({ ByteStreams.class, Configuration.class })
public void testSaveError() throws Exception {
    final int[] loggerObject = { 0 };
    mockStatic(ByteStreams.class);
    when(ByteStreams.copy(any(FileInputStream.class), any(FileOutputStream.class))).thenReturn((long) 0);
    Logger mockedLogger = mock(Logger.class);
    YAML mockedYAML = mock(YAML.class);
    whenNew(YAML.class).withArguments(File.class).thenReturn(mockedYAML);
    Configuration configuration = spy(new Configuration(mockedLogger, new File(System.getProperty("user.dir")), 1, 10, "NOT_HERE.cfg"));
    new File("NOT_HERE.cfg").delete();
    doReturn(true).when(configuration).newConfigCreated();
    doThrow(new FileNotFoundException()).when(configuration).saveConfig();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            loggerObject[0]++;
            return null;
        }
    }).when(mockedLogger).warning(anyString());
    configuration.reload();
    assertEquals("The error should be logged", 1, loggerObject[0]);
}
Also used : Logger(java.util.logging.Logger) YAML(at.pcgamingfreaks.yaml.YAML) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 37 with PrepareForTest

use of org.powermock.core.classloader.annotations.PrepareForTest in project Bukkit_Bungee_PluginLib by GeorgH93.

the class ConfigurationTest method testUpgrade.

@Test
@PrepareForTest({ Configuration.class, File.class })
public void testUpgrade() throws Exception {
    int version = 3;
    File userDir = new File(System.getProperty("user.dir"));
    Configuration configuration = spy(new Configuration(mockedLogger, userDir, 1));
    doReturn(true).when(configuration).newConfigCreated();
    configuration.set("Version", version);
    configuration.set("TestBoolean", true);
    configuration.set("NewValue", "NotFound");
    assertEquals("The TestBoolean value should be true", true, configuration.getBool("TestBoolean"));
    Configuration oldConfiguration = new Configuration(mockedLogger, userDir, 1);
    configuration.doUpgrade(oldConfiguration);
    assertEquals("The version of the upgraded configuration should match", version, configuration.getVersion());
    assertEquals("The boolean value should be taken from the old configuration", false, configuration.getBool("TestBoolean"));
    Method upgradeConfig = Configuration.class.getDeclaredMethod("upgradeConfig");
    upgradeConfig.setAccessible(true);
    File mockedFile = mock(File.class);
    // noinspection ResultOfMethodCallIgnored
    doReturn(true).when(mockedFile).exists();
    // noinspection ResultOfMethodCallIgnored
    doReturn(false).when(mockedFile).delete();
    Field configFile = TestUtils.setAccessible(Configuration.class, configuration, "configFile", mockedFile);
    // noinspection ResultOfMethodCallIgnored
    doReturn(false).when(mockedFile).renameTo(mockedFile);
    whenNew(File.class).withAnyArguments().thenReturn(mockedFile);
    upgradeConfig.invoke(configuration);
    assertEquals("The version of the config file should match because it has not been upgraded", version, configuration.getVersion());
    // noinspection ResultOfMethodCallIgnored
    doThrow(new NullPointerException()).when(mockedFile).renameTo(mockedFile);
    upgradeConfig.invoke(configuration);
    assertEquals("The version of the config file should be set to -1 if an error occurs", -1, configuration.getVersion());
    // noinspection ResultOfMethodCallIgnored
    doReturn(true).when(mockedFile).delete();
    // noinspection ResultOfMethodCallIgnored
    doReturn(true).when(mockedFile).renameTo(mockedFile);
    doReturn(false).when(configuration).isLoaded();
    upgradeConfig.invoke(configuration);
    assertEquals("The version of the config file should match because it has not been upgraded", -1, configuration.getVersion());
    upgradeConfig.setAccessible(false);
    TestUtils.setUnaccessible(configFile, configuration, true);
}
Also used : Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 38 with PrepareForTest

use of org.powermock.core.classloader.annotations.PrepareForTest in project Bukkit_Bungee_PluginLib by GeorgH93.

the class UUIDConverterTest method testNameHistory.

@Test
@PrepareForTest({ URL.class, UUIDConverter.class })
public void testNameHistory() throws Exception {
    UUIDConverter.NameChange[] nameChanges = UUIDConverter.getNamesFromUUID(TEST_USER2_UUID);
    assertTrue("There should be at least 2 name changes (2 are already known)", nameChanges.length >= 2);
    assertEquals("The first name of the user should match", TEST_USER2_NAME_OG, nameChanges[0].name);
    assertEquals("The username after the fifth name change should match", TEST_USER2_NAME_NEW, nameChanges[5].name);
    nameChanges = UUIDConverter.getNamesFromUUID(TEST_USER2_UUID_AS_UUID);
    assertTrue("There should be at least 2 name changes (2 are already known)", nameChanges.length >= 2);
    assertEquals("The first name of the user should match", TEST_USER2_NAME_OG, nameChanges[0].name);
    assertEquals("The username after the fifth name change should match", TEST_USER2_NAME_NEW, nameChanges[5].name);
    assertNull("The invalid UUID should return null", UUIDConverter.getNamesFromUUID("123456"));
    URL mockedURL = PowerMockito.mock(URL.class);
    whenNew(URL.class).withAnyArguments().thenReturn(mockedURL);
    PowerMockito.doThrow(new IOException("HTTP response code: 429")).when(mockedURL).openConnection();
    UUIDConverter.getNamesFromUUID(TEST_USER2_UUID_AS_UUID);
    int outputStreamSize = outputStream.size();
    int errorStreamSize = errorStream.size();
    assertTrue("A message should be written to the console if an error occurs", outputStreamSize > 0);
    assertTrue("An exception should be thrown if an error occurs", errorStreamSize > 0);
    PowerMockito.doThrow(new IOException("HTTP response code: 400")).when(mockedURL).openConnection();
    UUIDConverter.getNamesFromUUID(TEST_USER2_UUID_AS_UUID);
    assertTrue("A message should be written to the console if an error occurs", outputStream.size() > outputStreamSize);
    assertTrue("An exception should be thrown if an error occurs", errorStream.size() > errorStreamSize);
}
Also used : URL(java.net.URL) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 39 with PrepareForTest

use of org.powermock.core.classloader.annotations.PrepareForTest in project Bukkit_Bungee_PluginLib by GeorgH93.

the class UUIDConverterTest method testGetOnlineUUIDFromName.

@Test
@PrepareForTest({ URL.class, UUIDConverter.class })
public void testGetOnlineUUIDFromName() throws Exception {
    Field uuidCache = UUIDConverter.class.getDeclaredField("UUID_CACHE");
    uuidCache.setAccessible(true);
    Field modifiers = uuidCache.getClass().getDeclaredField("modifiers");
    modifiers.setAccessible(true);
    modifiers.setInt(uuidCache, uuidCache.getModifiers() & ~Modifier.FINAL);
    UUIDCacheMap currentCacheMap = (UUIDCacheMap) uuidCache.get(this);
    UUIDCacheMap mockedUUIDCacheMap = mock(UUIDCacheMap.class);
    mockedUUIDCacheMap.clear();
    uuidCache.set(this, mockedUUIDCacheMap);
    assertEquals("Username with no time given and no cache should match the current username", TEST_USER_UUID, UUIDConverter.getUUIDFromName(TEST_USER_NAME, true, null));
    assertEquals("Username at the current time with no cache should match the current username", TEST_USER_UUID, UUIDConverter.getUUIDFromName(TEST_USER_NAME, true, TODAY));
    when(mockedUUIDCacheMap.containsKey(TEST_USER_NAME)).thenReturn(true);
    when(mockedUUIDCacheMap.get(TEST_USER_NAME)).thenReturn(TEST_USER_UUID);
    assertEquals("Username with no time given and available cache should match the current username", TEST_USER_UUID, UUIDConverter.getUUIDFromName(TEST_USER_NAME, true, null));
    assertEquals("Username at the current time and available cache should match the current username", TEST_USER_UUID, UUIDConverter.getUUIDFromName(TEST_USER_NAME, true, TODAY));
    reset(mockedUUIDCacheMap);
    URL mockedURL = PowerMockito.mock(URL.class);
    whenNew(URL.class).withArguments(anyString()).thenThrow(new MalformedURLException());
    UUIDConverter.getUUIDFromName(TEST_USER_NAME, true, null);
    assertTrue("An error should be printed when a malformed URL occurs", errorStream.toString().contains("MalformedURLException"));
    PowerMockito.doThrow(new IOException("HTTP response code: 429")).when(mockedURL).openStream();
    whenNew(URL.class).withAnyArguments().thenReturn(mockedURL);
    UUIDConverter.getUUIDFromName(TEST_USER_NAME, true, null);
    assertTrue("An error should be printed when the URL can't open the stream", errorStream.toString().contains("IOException"));
    PowerMockito.doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return null;
        }
    }).when(mockedURL).openStream();
    UUIDConverter.getUUIDFromName(TEST_USER2_NAME_NEW, true, TEST_USER2_LAST_SEEN);
    assertTrue("A message should be printed when there doesn't exist a user at the given time", outputStream.size() > 0);
    uuidCache.set(this, currentCacheMap);
    uuidCache.setAccessible(false);
}
Also used : Field(java.lang.reflect.Field) MalformedURLException(java.net.MalformedURLException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) URL(java.net.URL) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 40 with PrepareForTest

use of org.powermock.core.classloader.annotations.PrepareForTest in project Bukkit_Bungee_PluginLib by GeorgH93.

the class UUIDConverterTest method testGetUUIDsFromNames.

@Test
@SuppressWarnings("SpellCheckingInspection")
@PrepareForTest({ URL.class, UUIDConverter.class })
public void testGetUUIDsFromNames() throws Exception {
    final Map<String, String> testNames = new TreeMap<>();
    testNames.put(TEST_USER_NAME, TEST_USER_UUID);
    testNames.put("Phei", "8abb0b91429b41e49be8bd659923acd6");
    testNames.put("AFKMaster", "175c57e4cd4b4fb3bfea1c28d094f5dc");
    testNames.put("CleoMalika", "fc4b363ba4474ab98778d0ee353151ee");
    testNames.put("Ghetto1996", "5d44a19304d94ebaaa3f630b8c95b48a");
    final Map<String, String> testNamesSeparators = new TreeMap<>();
    testNamesSeparators.put(TEST_USER_NAME, TEST_USER_UUID_SEPARATORS);
    testNamesSeparators.put("Phei", "8abb0b91-429b-41e4-9be8-bd659923acd6");
    testNamesSeparators.put("AFKMaster", "175c57e4-cd4b-4fb3-bfea-1c28d094f5dc");
    testNamesSeparators.put("CleoMalika", "fc4b363b-a447-4ab9-8778-d0ee353151ee");
    testNamesSeparators.put("Ghetto1996", "5d44a193-04d9-4eba-aa3f-630b8c95b48a");
    Field uuidCache = UUIDConverter.class.getDeclaredField("UUID_CACHE");
    uuidCache.setAccessible(true);
    Field modifiers = uuidCache.getClass().getDeclaredField("modifiers");
    modifiers.setAccessible(true);
    modifiers.setInt(uuidCache, uuidCache.getModifiers() & ~Modifier.FINAL);
    UUIDCacheMap currentCacheMap = (UUIDCacheMap) uuidCache.get(this);
    UUIDCacheMap mockedUUIDCacheMap = mock(UUIDCacheMap.class);
    when(mockedUUIDCacheMap.containsKey(anyString())).thenAnswer(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable {
            // noinspection SuspiciousMethodCalls
            return testNamesSeparators.containsKey(invocationOnMock.getArguments()[0]);
        }
    });
    when(mockedUUIDCacheMap.get(anyString())).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocationOnMock) throws Throwable {
            // noinspection SuspiciousMethodCalls
            return testNamesSeparators.get(invocationOnMock.getArguments()[0]);
        }
    });
    uuidCache.set(this, mockedUUIDCacheMap);
    Map<String, String> namesUUIDs = UUIDConverter.getUUIDsFromNames(testNamesSeparators.keySet(), true, true);
    assertEquals("The user count of online mode users should match the given amount of users", testNamesSeparators.size(), namesUUIDs.size());
    assertTrue("All user UUIDs should match the given ones with separators", namesUUIDs.equals(testNamesSeparators));
    when(mockedUUIDCacheMap.containsKey(anyString())).thenAnswer(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable {
            // noinspection SuspiciousMethodCalls
            return testNames.containsKey(invocationOnMock.getArguments()[0]);
        }
    });
    when(mockedUUIDCacheMap.get(anyString())).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocationOnMock) throws Throwable {
            // noinspection SuspiciousMethodCalls
            return testNames.get(invocationOnMock.getArguments()[0]);
        }
    });
    namesUUIDs = UUIDConverter.getUUIDsFromNames(testNames.keySet(), true, false);
    assertEquals("The user count of online mode users should match the given amount of users", testNames.size(), namesUUIDs.size());
    assertTrue("All user UUIDs should match the given ones", namesUUIDs.equals(testNames));
    namesUUIDs = UUIDConverter.getUUIDsFromNames(testNames.keySet(), false, false);
    assertEquals("The user count of offline mode users should match the given amount of users", testNames.size(), namesUUIDs.size());
    assertTrue("All user names should exist in the map", namesUUIDs.keySet().containsAll(testNames.keySet()));
    uuidCache.set(this, currentCacheMap);
    namesUUIDs = UUIDConverter.getUUIDsFromNames(testNames.keySet(), true, false);
    assertEquals("The user count of online mode users should match the given amount of users", testNames.size(), namesUUIDs.size());
    assertTrue("All user names should exist in the map when using no cache", namesUUIDs.keySet().containsAll(testNames.keySet()));
    URL mockedURL = PowerMockito.mock(URL.class);
    whenNew(URL.class).withArguments(anyString()).thenReturn(mockedURL);
    HttpURLConnection mockedHttpURLConnection = mock(HttpURLConnection.class);
    PowerMockito.doReturn(429).doThrow(new IOException()).when(mockedHttpURLConnection).getResponseCode();
    PowerMockito.doThrow(new IOException()).when(mockedHttpURLConnection).getOutputStream();
    PowerMockito.doReturn(mockedHttpURLConnection).when(mockedURL).openConnection();
    Field queryRetryTime = TestUtils.setAccessible(UUIDConverter.class, null, "MOJANG_QUERY_RETRY_TIME", 10);
    UUIDConverter.getUUIDsFromNames(testNames.keySet(), true, false);
    TestUtils.setUnaccessible(queryRetryTime, null, true);
    assertTrue("A message should be written to System.out when an error occurs", outputStream.size() > 0);
    uuidCache.setAccessible(false);
}
Also used : TreeMap(java.util.TreeMap) URL(java.net.URL) Field(java.lang.reflect.Field) HttpURLConnection(java.net.HttpURLConnection) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)188 Test (org.junit.Test)186 HttpServletRequest (javax.servlet.http.HttpServletRequest)30 HttpServletResponse (javax.servlet.http.HttpServletResponse)30 StringWriter (java.io.StringWriter)28 PrintWriter (java.io.PrintWriter)27 File (java.io.File)21 ArrayList (java.util.ArrayList)15 LogChannelInterface (org.pentaho.di.core.logging.LogChannelInterface)14 Method (java.lang.reflect.Method)13 Config (com.twitter.heron.spi.common.Config)12 DialogInterface (android.content.DialogInterface)11 Intent (android.content.Intent)11 SchedulerStateManagerAdaptor (com.twitter.heron.spi.statemgr.SchedulerStateManagerAdaptor)11 Job (hudson.model.Job)11 Point (org.pentaho.di.core.gui.Point)10 Date (java.util.Date)9 HashMap (java.util.HashMap)9 Matchers.anyString (org.mockito.Matchers.anyString)9 InvocationOnMock (org.mockito.invocation.InvocationOnMock)9