method2testcases
stringlengths 118
6.63k
|
---|
### Question:
WlsDomainConfig implements WlsDomain { public synchronized WlsServerConfig getServerConfig(String serverName) { WlsServerConfig result = null; if (serverName != null && servers != null) { for (WlsServerConfig serverConfig : servers) { if (serverConfig.getName().equals(serverName)) { result = serverConfig; break; } } } return result; } WlsDomainConfig(); WlsDomainConfig(String name); WlsDomainConfig(
String name,
String adminServerName,
Map<String, WlsClusterConfig> wlsClusterConfigs,
Map<String, WlsServerConfig> wlsServerConfigs,
Map<String, WlsServerConfig> wlsServerTemplates,
Map<String, WlsMachineConfig> wlsMachineConfigs); static WlsDomainConfig create(String jsonResult); static String getRetrieveServersSearchUrl(); static String getRetrieveServersSearchPayload(); String getClusterName(String serverName); String getName(); String getAdminServerName(); void setAdminServerName(String adminServerName); synchronized Map<String, WlsClusterConfig> getClusterConfigs(); List<WlsClusterConfig> getConfiguredClusters(); void setConfiguredClusters(List<WlsClusterConfig> configuredClusters); synchronized Map<String, WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); List<WlsServerConfig> getServerTemplates(); void setServerTemplates(List<WlsServerConfig> serverTemplates); synchronized Map<String, WlsMachineConfig> getMachineConfigs(); synchronized WlsClusterConfig getClusterConfig(String clusterName); synchronized WlsServerConfig getServerConfig(String serverName); synchronized boolean containsCluster(String clusterName); synchronized boolean containsServer(String serverName); synchronized WlsMachineConfig getMachineConfig(String machineName); @Override @Nonnull String[] getClusterNames(); @Override int getReplicaLimit(String clusterName); WlsDomainConfig withAdminServer(String adminServerName, String listenAddress, int port); WlsDomainConfig addWlsServer(String name, String listenAddress, int port); WlsDomainConfig withCluster(WlsClusterConfig clusterConfig); Map<String, Object> toTopology(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void processDynamicClusters(); }### Answer:
@Test public void verifySslConfigsLoadedFromJsonString() { createDomainConfig(JSON_STRING_1_CLUSTER); WlsServerConfig serverConfig = wlsDomainConfig.getServerConfig("ms-0"); assertEquals(new Integer(8101), serverConfig.getSslListenPort()); assertTrue(serverConfig.isSslPortEnabled()); serverConfig = wlsDomainConfig.getServerConfig("ms-1"); assertNull(serverConfig.getSslListenPort()); assertFalse(serverConfig.isSslPortEnabled()); }
@Test public void verifyGetServerConfigsReturnNullIfNotFound() { assertNull(wlsDomainConfig.getServerConfig("noSuchServer")); }
|
### Question:
WlsDomainConfig implements WlsDomain { public synchronized WlsMachineConfig getMachineConfig(String machineName) { WlsMachineConfig result = null; if (machineName != null && wlsMachineConfigs != null) { result = wlsMachineConfigs.get(machineName); } return result; } WlsDomainConfig(); WlsDomainConfig(String name); WlsDomainConfig(
String name,
String adminServerName,
Map<String, WlsClusterConfig> wlsClusterConfigs,
Map<String, WlsServerConfig> wlsServerConfigs,
Map<String, WlsServerConfig> wlsServerTemplates,
Map<String, WlsMachineConfig> wlsMachineConfigs); static WlsDomainConfig create(String jsonResult); static String getRetrieveServersSearchUrl(); static String getRetrieveServersSearchPayload(); String getClusterName(String serverName); String getName(); String getAdminServerName(); void setAdminServerName(String adminServerName); synchronized Map<String, WlsClusterConfig> getClusterConfigs(); List<WlsClusterConfig> getConfiguredClusters(); void setConfiguredClusters(List<WlsClusterConfig> configuredClusters); synchronized Map<String, WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); List<WlsServerConfig> getServerTemplates(); void setServerTemplates(List<WlsServerConfig> serverTemplates); synchronized Map<String, WlsMachineConfig> getMachineConfigs(); synchronized WlsClusterConfig getClusterConfig(String clusterName); synchronized WlsServerConfig getServerConfig(String serverName); synchronized boolean containsCluster(String clusterName); synchronized boolean containsServer(String serverName); synchronized WlsMachineConfig getMachineConfig(String machineName); @Override @Nonnull String[] getClusterNames(); @Override int getReplicaLimit(String clusterName); WlsDomainConfig withAdminServer(String adminServerName, String listenAddress, int port); WlsDomainConfig addWlsServer(String name, String listenAddress, int port); WlsDomainConfig withCluster(WlsClusterConfig clusterConfig); Map<String, Object> toTopology(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void processDynamicClusters(); }### Answer:
@Test public void verifyGetMachineConfigsReturnNullIfNotFound() { assertNull(wlsDomainConfig.getMachineConfig("noSuchMachine")); }
|
### Question:
WlsDomainConfig implements WlsDomain { @Override @Nonnull public String[] getClusterNames() { return getClusterConfigs().keySet().toArray(new String[0]); } WlsDomainConfig(); WlsDomainConfig(String name); WlsDomainConfig(
String name,
String adminServerName,
Map<String, WlsClusterConfig> wlsClusterConfigs,
Map<String, WlsServerConfig> wlsServerConfigs,
Map<String, WlsServerConfig> wlsServerTemplates,
Map<String, WlsMachineConfig> wlsMachineConfigs); static WlsDomainConfig create(String jsonResult); static String getRetrieveServersSearchUrl(); static String getRetrieveServersSearchPayload(); String getClusterName(String serverName); String getName(); String getAdminServerName(); void setAdminServerName(String adminServerName); synchronized Map<String, WlsClusterConfig> getClusterConfigs(); List<WlsClusterConfig> getConfiguredClusters(); void setConfiguredClusters(List<WlsClusterConfig> configuredClusters); synchronized Map<String, WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); List<WlsServerConfig> getServerTemplates(); void setServerTemplates(List<WlsServerConfig> serverTemplates); synchronized Map<String, WlsMachineConfig> getMachineConfigs(); synchronized WlsClusterConfig getClusterConfig(String clusterName); synchronized WlsServerConfig getServerConfig(String serverName); synchronized boolean containsCluster(String clusterName); synchronized boolean containsServer(String serverName); synchronized WlsMachineConfig getMachineConfig(String machineName); @Override @Nonnull String[] getClusterNames(); @Override int getReplicaLimit(String clusterName); WlsDomainConfig withAdminServer(String adminServerName, String listenAddress, int port); WlsDomainConfig addWlsServer(String name, String listenAddress, int port); WlsDomainConfig withCluster(WlsClusterConfig clusterConfig); Map<String, Object> toTopology(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void processDynamicClusters(); }### Answer:
@Test public void whenTwoClustersDefined_returnBothNames() { WlsDomainConfigSupport support = new WlsDomainConfigSupport("test-domain"); support.addWlsCluster("cluster1", "ms1", "ms2", "ms3"); support.addWlsCluster("cluster2", "ms4", "ms5"); assertThat( support.createDomainConfig().getClusterNames(), arrayContainingInAnyOrder("cluster1", "cluster2")); }
|
### Question:
WlsDomainConfig implements WlsDomain { @Override public int getReplicaLimit(String clusterName) { if (!getClusterConfigs().containsKey(clusterName)) { return 0; } return getClusterConfigs().get(clusterName).getMaxClusterSize(); } WlsDomainConfig(); WlsDomainConfig(String name); WlsDomainConfig(
String name,
String adminServerName,
Map<String, WlsClusterConfig> wlsClusterConfigs,
Map<String, WlsServerConfig> wlsServerConfigs,
Map<String, WlsServerConfig> wlsServerTemplates,
Map<String, WlsMachineConfig> wlsMachineConfigs); static WlsDomainConfig create(String jsonResult); static String getRetrieveServersSearchUrl(); static String getRetrieveServersSearchPayload(); String getClusterName(String serverName); String getName(); String getAdminServerName(); void setAdminServerName(String adminServerName); synchronized Map<String, WlsClusterConfig> getClusterConfigs(); List<WlsClusterConfig> getConfiguredClusters(); void setConfiguredClusters(List<WlsClusterConfig> configuredClusters); synchronized Map<String, WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); List<WlsServerConfig> getServerTemplates(); void setServerTemplates(List<WlsServerConfig> serverTemplates); synchronized Map<String, WlsMachineConfig> getMachineConfigs(); synchronized WlsClusterConfig getClusterConfig(String clusterName); synchronized WlsServerConfig getServerConfig(String serverName); synchronized boolean containsCluster(String clusterName); synchronized boolean containsServer(String serverName); synchronized WlsMachineConfig getMachineConfig(String machineName); @Override @Nonnull String[] getClusterNames(); @Override int getReplicaLimit(String clusterName); WlsDomainConfig withAdminServer(String adminServerName, String listenAddress, int port); WlsDomainConfig addWlsServer(String name, String listenAddress, int port); WlsDomainConfig withCluster(WlsClusterConfig clusterConfig); Map<String, Object> toTopology(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void processDynamicClusters(); }### Answer:
@Test public void whenTwoClustersDefined_returnReplicaLimits() { WlsDomainConfigSupport support = new WlsDomainConfigSupport("test-domain"); support.addWlsCluster("cluster1", "ms1", "ms2", "ms3"); support.addWlsCluster("cluster2", "ms4", "ms5"); assertThat(support.createDomainConfig().getReplicaLimit("cluster1"), equalTo(3)); assertThat(support.createDomainConfig().getReplicaLimit("cluster2"), equalTo(2)); }
@Test public void whenUnknownClusterName_returnZeroReplicaLimit() { WlsDomainConfigSupport support = new WlsDomainConfigSupport("test-domain"); assertThat(support.createDomainConfig().getReplicaLimit("cluster3"), equalTo(0)); }
|
### Question:
WlsDomainConfig implements WlsDomain { public Map<String, Object> toTopology() { Map<String, Object> topology = new HashMap<>(); topology.put("domainValid", "true"); topology.put("domain", createDomainTopology()); return topology; } WlsDomainConfig(); WlsDomainConfig(String name); WlsDomainConfig(
String name,
String adminServerName,
Map<String, WlsClusterConfig> wlsClusterConfigs,
Map<String, WlsServerConfig> wlsServerConfigs,
Map<String, WlsServerConfig> wlsServerTemplates,
Map<String, WlsMachineConfig> wlsMachineConfigs); static WlsDomainConfig create(String jsonResult); static String getRetrieveServersSearchUrl(); static String getRetrieveServersSearchPayload(); String getClusterName(String serverName); String getName(); String getAdminServerName(); void setAdminServerName(String adminServerName); synchronized Map<String, WlsClusterConfig> getClusterConfigs(); List<WlsClusterConfig> getConfiguredClusters(); void setConfiguredClusters(List<WlsClusterConfig> configuredClusters); synchronized Map<String, WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); List<WlsServerConfig> getServerTemplates(); void setServerTemplates(List<WlsServerConfig> serverTemplates); synchronized Map<String, WlsMachineConfig> getMachineConfigs(); synchronized WlsClusterConfig getClusterConfig(String clusterName); synchronized WlsServerConfig getServerConfig(String serverName); synchronized boolean containsCluster(String clusterName); synchronized boolean containsServer(String serverName); synchronized WlsMachineConfig getMachineConfig(String machineName); @Override @Nonnull String[] getClusterNames(); @Override int getReplicaLimit(String clusterName); WlsDomainConfig withAdminServer(String adminServerName, String listenAddress, int port); WlsDomainConfig addWlsServer(String name, String listenAddress, int port); WlsDomainConfig withCluster(WlsClusterConfig clusterConfig); Map<String, Object> toTopology(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void processDynamicClusters(); }### Answer:
@Test public void whenTopologyGenerated_containsDomainValidFlag() { WlsDomainConfig domainConfig = new WlsDomainConfig(); assertThat(domainConfig.toTopology(), hasJsonPath("domainValid", equalTo("true"))); }
@Test public void whenTopologyGenerated_containsDomainName() { WlsDomainConfig domainConfig = new WlsDomainConfig("test-domain"); assertThat(domainConfig.toTopology(), hasJsonPath("domain.name", equalTo("test-domain"))); }
|
### Question:
WlsClusterConfig { public synchronized int getClusterSize() { return servers.size(); } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyClusterSizeIs0IfNoServers() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1"); assertEquals(0, wlsClusterConfig.getClusterSize()); }
|
### Question:
WlsClusterConfig { public synchronized boolean hasStaticServers() { return !servers.isEmpty(); } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyHasStaticServersIsFalseIfNoServers() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1"); assertFalse(wlsClusterConfig.hasStaticServers()); }
@Test public void verifyHasStaticServersIsFalseForDynamicCluster() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1", createDynamicServersConfig(2, 5, 1, "ms-", "clsuter1")); assertFalse(wlsClusterConfig.hasStaticServers()); }
|
### Question:
WlsClusterConfig { public boolean hasDynamicServers() { return dynamicServersConfig != null; } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyHasDynamicServersIsFalsefNoDynamicServers() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1"); assertFalse(wlsClusterConfig.hasDynamicServers()); }
@Test public void verifyHasDynamicServersIsTrueForDynamicCluster() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1", createDynamicServersConfig(2, 5, 1, "ms-", "clsuter1")); assertTrue(wlsClusterConfig.hasDynamicServers()); }
|
### Question:
WlsClusterConfig { public synchronized int getMaxClusterSize() { return hasDynamicServers() ? getClusterSize() + getMaxDynamicClusterSize() : getClusterSize(); } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyMaxClusterSizeIsSameAsDynamicSizeForDynamicCluster() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1", createDynamicServersConfig(2, 5, 1, "ms-", "clsuter1")); assertEquals(5, wlsClusterConfig.getMaxClusterSize()); }
@Test public void verifyMaxClusterSizeForDynamicCluster() { WlsDynamicServersConfig wlsDynamicServersConfig = createDynamicServersConfig(1, 1, 1, "ms-", "cluster1"); WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1", wlsDynamicServersConfig); assertThat(wlsClusterConfig.getMaxClusterSize(), equalTo(1)); }
|
### Question:
WlsClusterConfig { public int getDynamicClusterSize() { return dynamicServersConfig != null ? dynamicServersConfig.getDynamicClusterSize() : -1; } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyDynamicClusterSizeIsNeg1IfNoDynamicServers() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1"); assertEquals(-1, wlsClusterConfig.getDynamicClusterSize()); }
|
### Question:
WlsClusterConfig { public int getMinDynamicClusterSize() { return dynamicServersConfig != null ? dynamicServersConfig.getMinDynamicClusterSize() : -1; } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyMinDynamicClusterSizeIsNeg1IfNoDynamicServers() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1"); assertEquals(-1, wlsClusterConfig.getMinDynamicClusterSize()); }
|
### Question:
WlsClusterConfig { public String getUpdateDynamicClusterSizeUrl() { return "/management/weblogic/latest/edit/clusters/" + name + "/dynamicServers"; } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyGetUpdateDynamicClusterSizeUrlIncludesClusterName() { WlsDynamicServersConfig wlsDynamicServersConfig = createDynamicServersConfig(1, 1, 1, "ms-", "cluster1"); WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1", wlsDynamicServersConfig); assertEquals( wlsClusterConfig.getUpdateDynamicClusterSizeUrl(), "/management/weblogic/latest/edit/clusters/cluster1/dynamicServers"); }
|
### Question:
WlsClusterConfig { public String getUpdateDynamicClusterSizePayload(final int clusterSize) { return "{ dynamicClusterSize: " + clusterSize + " }"; } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void verifyGetUpdateDynamicClusterSizePayload() { WlsDynamicServersConfig wlsDynamicServersConfig = createDynamicServersConfig(1, 5, 1, "ms-", "cluster1"); WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("cluster1", wlsDynamicServersConfig); assertEquals( wlsClusterConfig.getUpdateDynamicClusterSizePayload(2), "{ dynamicClusterSize: 2 }"); }
|
### Question:
WlsClusterConfig { static boolean checkUpdateDynamicClusterSizeJsonResult(String jsonResult) { final String expectedResult = "{}"; boolean result = false; if (expectedResult.equals(jsonResult)) { result = true; } return result; } WlsClusterConfig(); WlsClusterConfig(String clusterName); WlsClusterConfig(String clusterName, WlsDynamicServersConfig dynamicServersConfig); boolean hasNamedServer(String serverName); synchronized WlsClusterConfig addServerConfig(WlsServerConfig wlsServerConfig); synchronized int getClusterSize(); synchronized int getMaxClusterSize(); int getMinClusterSize(); String getClusterName(); String getName(); void setName(String name); WlsDynamicServersConfig getDynamicServersConfig(); void setDynamicServersConfig(WlsDynamicServersConfig dynamicServersConfig); WlsDomainConfig getWlsDomainConfig(); void setWlsDomainConfig(WlsDomainConfig wlsDomainConfig); synchronized List<WlsServerConfig> getServerConfigs(); List<WlsServerConfig> getServers(); void setServers(List<WlsServerConfig> servers); synchronized boolean hasStaticServers(); boolean hasDynamicServers(); int getDynamicClusterSize(); int getMaxDynamicClusterSize(); int getMinDynamicClusterSize(); String getUpdateDynamicClusterSizeUrl(); String getUpdateDynamicClusterSizePayload(final int clusterSize); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void checkDynamicClusterSizeJsonResultReturnsFalseOnNull() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("someCluster"); assertFalse(wlsClusterConfig.checkUpdateDynamicClusterSizeJsonResult(null)); }
@Test public void checkDynamicClusterSizeJsonResultReturnsFalseOnUnexpectedString() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("someCluster"); assertFalse(wlsClusterConfig.checkUpdateDynamicClusterSizeJsonResult("{ xyz }")); }
@Test public void checkDynamicClusterSizeJsonResultReturnsTrueWithExpectedString() { WlsClusterConfig wlsClusterConfig = new WlsClusterConfig("someCluster"); assertTrue(wlsClusterConfig.checkUpdateDynamicClusterSizeJsonResult("{}")); }
|
### Question:
MacroSubstitutor { String substituteMacro(String inputValue) { if (inputValue == null) { return inputValue; } int start = 0; int idx = inputValue.indexOf(START_MACRO); if (idx == -1) { return inputValue; } StringBuilder retStr = new StringBuilder(); while (idx != -1) { retStr.append(inputValue.substring(start, idx)); int macroIdx = idx; int end = inputValue.indexOf(END_MACRO, macroIdx); if (end == -1) { start = idx; idx = -1; continue; } String macro = inputValue.substring(macroIdx + 2, end); String macroVal = resolveMacroValue(macro); if (macroVal != null) { retStr.append(macroVal); } start = end + 1; idx = inputValue.indexOf(START_MACRO, start); } retStr.append(inputValue.substring(start)); return retStr.toString(); } MacroSubstitutor(
int id, String serverName, String clusterName, String domainName, String machineName); }### Answer:
@Test public void testMacros() { final int ID = 123; final String server = "ms-1"; final String cluster = "cluster-1"; final String domain = "base_domain"; final String machine = "slc08urp"; final MacroSubstitutor macroSubstitutor = new MacroSubstitutor(ID, server, cluster, domain, machine); assertEquals( "empty input string should return an empty string", "", macroSubstitutor.substituteMacro("")); assertEquals( "null input string should return null", null, macroSubstitutor.substituteMacro(null)); assertEquals( "string without macro should remains unchanged", "abcdefg 1", macroSubstitutor.substituteMacro("abcdefg 1")); assertEquals( "string with ${id} macro", "myserver-" + ID, macroSubstitutor.substituteMacro("myserver-${id}")); assertEquals( "string with ${serverName} macro", "test-" + server, macroSubstitutor.substituteMacro("test-${serverName}")); assertEquals( "string with ${clusterName} macro", "test-" + cluster, macroSubstitutor.substituteMacro("test-${clusterName}")); assertEquals( "string with ${domainName} macro", "test-" + domain, macroSubstitutor.substituteMacro("test-${domainName}")); assertEquals( "string with only macro", server, macroSubstitutor.substituteMacro("${serverName}")); assertEquals( "string with multiple macros", server + "-" + domain + "-" + cluster + "-" + ID, macroSubstitutor.substituteMacro("${serverName}-${domainName}-${clusterName}-${id}")); System.setProperty("oracle.macrosubstitutortest", "myEnv Value"); assertEquals( "string with system property macro", "myEnv Value", macroSubstitutor.substituteMacro("${oracle.macrosubstitutortest}")); Properties systemProperties = System.getProperties(); systemProperties.remove("oracle.macrosubstitutortest"); assertEquals( "string with system property macro but system property not set", "test--1", macroSubstitutor.substituteMacro("test-${oracle.macrosubstitutortest}-1")); assertEquals( "string without complete macro", "test${", macroSubstitutor.substituteMacro("test${")); }
|
### Question:
DomainCondition implements Comparable<DomainCondition>, PatchableComponent<DomainCondition> { public DateTime getLastTransitionTime() { return lastTransitionTime; } DomainCondition(DomainConditionType conditionType); DomainCondition(DomainCondition other); DateTime getLastProbeTime(); void setLastProbeTime(DateTime lastProbeTime); DomainCondition withLastProbeTime(DateTime lastProbeTime); DateTime getLastTransitionTime(); String getMessage(); DomainCondition withMessage(String message); String getReason(); DomainCondition withReason(String reason); String getStatus(); DomainCondition withStatus(String status); DomainConditionType getType(); boolean hasType(DomainConditionType type); @Override boolean isPatchableFrom(DomainCondition other); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(DomainCondition o); }### Answer:
@Test public void whenCreated_conditionHasLastTransitionTime() { assertThat(new DomainCondition(Available).getLastTransitionTime(), SystemClockTestSupport.isDuringTest()); }
|
### Question:
WatchBuilder { public WatchI<Domain> createDomainWatch(String namespace) throws ApiException { return FACTORY.createWatch( ClientPool.getInstance(), callParams, Domain.class, new ListDomainsCall(namespace)); } WatchBuilder(); WatchI<V1Service> createServiceWatch(String namespace); WatchI<V1Pod> createPodWatch(String namespace); WatchI<V1Job> createJobWatch(String namespace); WatchI<V1Event> createEventWatch(String namespace); WatchI<Domain> createDomainWatch(String namespace); WatchI<V1ConfigMap> createConfigMapWatch(String namespace); WatchI<V1Namespace> createNamespacesWatch(); WatchBuilder withFieldSelector(String fieldSelector); WatchBuilder withLabelSelector(String labelSelector); WatchBuilder withLabelSelectors(String... labelSelectors); WatchBuilder withResourceVersion(String resourceVersion); WatchBuilder withTimeoutSeconds(Integer timeoutSeconds); }### Answer:
@Test public void whenDomainWatchReceivesAddResponse_returnItFromIterator() throws Exception { Domain domain = new Domain() .withApiVersion(API_VERSION) .withKind("Domain") .withMetadata(createMetaData("domain1", NAMESPACE)); defineHttpResponse(DOMAIN_RESOURCE, withResponses(createAddedResponse(domain))); WatchI<Domain> domainWatch = new WatchBuilder().createDomainWatch(NAMESPACE); assertThat(domainWatch, contains(addEvent(domain))); }
@Test public void afterWatchClosed_returnClientToPool() throws Exception { Domain domain = new Domain() .withApiVersion(API_VERSION) .withKind("Domain") .withMetadata(createMetaData("domain1", NAMESPACE)); defineHttpResponse(DOMAIN_RESOURCE, withResponses(createAddedResponse(domain))); try (WatchI<Domain> domainWatch = new WatchBuilder().createDomainWatch(NAMESPACE)) { domainWatch.next(); } assertThat(ClientPoolStub.getPooledClients(), not(empty())); }
@Test public void afterWatchError_closeDoesNotReturnClientToPool() throws Exception { defineHttpResponse(DOMAIN_RESOURCE, withResponses()); try (WatchI<Domain> domainWatch = new WatchBuilder().createDomainWatch(NAMESPACE)) { domainWatch.next(); fail("Should have thrown an exception"); } catch (Throwable ignore) { } assertThat(ClientPoolStub.getPooledClients(), is(empty())); }
@Test public void whenDomainWatchReceivesModifyAndDeleteResponses_returnBothFromIterator() throws Exception { Domain domain1 = new Domain() .withApiVersion(API_VERSION) .withKind("Domain") .withMetadata(createMetaData("domain1", NAMESPACE)); Domain domain2 = new Domain() .withApiVersion(API_VERSION) .withKind("Domain") .withMetadata(createMetaData("domain2", NAMESPACE)); defineHttpResponse( DOMAIN_RESOURCE, withResponses(createModifiedResponse(domain1), createDeletedResponse(domain2))); WatchI<Domain> domainWatch = new WatchBuilder().createDomainWatch(NAMESPACE); assertThat(domainWatch, contains(modifyEvent(domain1), deleteEvent(domain2))); }
@Test public void whenDomainWatchReceivesErrorResponse_returnItFromIterator() throws Exception { defineHttpResponse(DOMAIN_RESOURCE, withResponses(createErrorResponse(HTTP_ENTITY_TOO_LARGE))); WatchI<Domain> domainWatch = new WatchBuilder().createDomainWatch(NAMESPACE); assertThat(domainWatch, contains(errorEvent(HTTP_ENTITY_TOO_LARGE))); }
|
### Question:
WatchBuilder { public WatchI<V1Pod> createPodWatch(String namespace) throws ApiException { return FACTORY.createWatch( ClientPool.getInstance(), callParams, V1Pod.class, new ListPodCall(namespace)); } WatchBuilder(); WatchI<V1Service> createServiceWatch(String namespace); WatchI<V1Pod> createPodWatch(String namespace); WatchI<V1Job> createJobWatch(String namespace); WatchI<V1Event> createEventWatch(String namespace); WatchI<Domain> createDomainWatch(String namespace); WatchI<V1ConfigMap> createConfigMapWatch(String namespace); WatchI<V1Namespace> createNamespacesWatch(); WatchBuilder withFieldSelector(String fieldSelector); WatchBuilder withLabelSelector(String labelSelector); WatchBuilder withLabelSelectors(String... labelSelectors); WatchBuilder withResourceVersion(String resourceVersion); WatchBuilder withTimeoutSeconds(Integer timeoutSeconds); }### Answer:
@Test public void whenPodWatchFindsNoData_hasNextReturnsFalse() throws Exception { defineHttpResponse(POD_RESOURCE, NO_RESPONSES); WatchI<V1Pod> podWatch = new WatchBuilder().createPodWatch(NAMESPACE); assertThat(podWatch.hasNext(), is(false)); }
|
### Question:
PodWatcher extends Watcher<V1Pod> implements WatchListener<V1Pod>, PodAwaiterStepFactory { public Step waitForReady(V1Pod pod, Step next) { return new WaitForPodReadyStep(pod, next); } private PodWatcher(
String namespace,
String initialResourceVersion,
WatchTuning tuning,
WatchListener<V1Pod> listener,
AtomicBoolean isStopping); static PodWatcher create(
ThreadFactory factory,
String ns,
String initialResourceVersion,
WatchTuning tuning,
WatchListener<V1Pod> listener,
AtomicBoolean isStopping); @Override WatchI<V1Pod> initiateWatch(WatchBuilder watchBuilder); @Override String getNamespace(); void receivedResponse(Watch.Response<V1Pod> item); Step waitForReady(V1Pod pod, Step next); Step waitForDelete(V1Pod pod, Step next); }### Answer:
@Test public void waitForReady_returnsAStep() { AtomicBoolean stopping = new AtomicBoolean(true); PodWatcher watcher = createWatcher(stopping); assertThat(watcher.waitForReady(createPod(), null), Matchers.instanceOf(Step.class)); }
@Test public void whenPodInitiallyReady_waitForReadyProceedsImmediately() { AtomicBoolean stopping = new AtomicBoolean(false); PodWatcher watcher = createWatcher(stopping); V1Pod pod = createPod(); markPodReady(pod); try { testSupport.runSteps(watcher.waitForReady(pod, terminalStep)); assertThat(terminalStep.wasRun(), is(true)); } finally { stopping.set(true); } }
|
### Question:
PodWatcher extends Watcher<V1Pod> implements WatchListener<V1Pod>, PodAwaiterStepFactory { public Step waitForDelete(V1Pod pod, Step next) { return new WaitForPodDeleteStep(pod, next); } private PodWatcher(
String namespace,
String initialResourceVersion,
WatchTuning tuning,
WatchListener<V1Pod> listener,
AtomicBoolean isStopping); static PodWatcher create(
ThreadFactory factory,
String ns,
String initialResourceVersion,
WatchTuning tuning,
WatchListener<V1Pod> listener,
AtomicBoolean isStopping); @Override WatchI<V1Pod> initiateWatch(WatchBuilder watchBuilder); @Override String getNamespace(); void receivedResponse(Watch.Response<V1Pod> item); Step waitForReady(V1Pod pod, Step next); Step waitForDelete(V1Pod pod, Step next); }### Answer:
@Test public void whenPodDeletedOnFirstRead_runNextStep() { AtomicBoolean stopping = new AtomicBoolean(false); PodWatcher watcher = createWatcher(stopping); try { testSupport.runSteps(watcher.waitForDelete(createPod(), terminalStep)); assertThat(terminalStep.wasRun(), is(true)); } finally { stopping.set(true); } }
@Test public void whenPodNotDeletedOnFirstRead_dontRunNextStep() { AtomicBoolean stopping = new AtomicBoolean(false); PodWatcher watcher = createWatcher(stopping); testSupport.defineResources(createPod()); try { testSupport.runSteps(watcher.waitForDelete(createPod(), terminalStep)); assertThat(terminalStep.wasRun(), is(false)); } finally { stopping.set(true); } }
|
### Question:
DomainCondition implements Comparable<DomainCondition>, PatchableComponent<DomainCondition> { public boolean hasType(DomainConditionType type) { return type == this.type; } DomainCondition(DomainConditionType conditionType); DomainCondition(DomainCondition other); DateTime getLastProbeTime(); void setLastProbeTime(DateTime lastProbeTime); DomainCondition withLastProbeTime(DateTime lastProbeTime); DateTime getLastTransitionTime(); String getMessage(); DomainCondition withMessage(String message); String getReason(); DomainCondition withReason(String reason); String getStatus(); DomainCondition withStatus(String status); DomainConditionType getType(); boolean hasType(DomainConditionType type); @Override boolean isPatchableFrom(DomainCondition other); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(DomainCondition o); }### Answer:
@Test public void predicateDetectsType() { assertThat(new DomainCondition(Failed).hasType(Failed), is(true)); assertThat(new DomainCondition(Progressing).hasType(Available), is(false)); }
|
### Question:
JsonSchemaMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { main.defineClasspath(toUrls(compileClasspathElements)); main.setIncludeAdditionalProperties(includeAdditionalProperties); main.setSupportObjectReferences(supportObjectReferences); addExternalSchemas(); if (rootClass == null) { throw new MojoExecutionException("No root class specified"); } URL classUrl = main.getResource(toClassFileName(rootClass)); if (classUrl == null) { throw new MojoExecutionException("Class " + rootClass + " not found"); } if (updateNeeded(new File(classUrl.getPath()), getSchemaFile())) { getLog().info("Changes detected -- generating schema for " + rootClass + "."); generate(); } else { getLog().info("Schema up-to-date. Skipping generation."); } } @Override void execute(); }### Answer:
@Test public void whenKubernetesVersionSpecified_passToGenerator() throws Exception { setMojoParameter("kubernetesVersion", "1.9.0"); mojo.execute(); assertThat(main.getKubernetesVersion(), equalTo("1.9.0")); }
@Test public void whenKubernetesVersionNotSpecified_passToGenerator() throws Exception { setMojoParameter("kubernetesVersion", null); mojo.execute(); assertThat(main.getKubernetesVersion(), nullValue()); }
@Test public void whenExternalSchemaSpecified_passToGenerator() throws Exception { setMojoParameter( "externalSchemas", singletonList(new ExternalSchema("http: mojo.execute(); assertThat( main.getCacheFor(new URL("http: equalTo(toModuleUrl("src/cache/schema.json"))); }
@Test(expected = MojoExecutionException.class) public void whenUnableToUseDefineSchema_haltTheBuild() throws Exception { setMojoParameter( "externalSchemas", singletonList(new ExternalSchema("abcd: mojo.execute(); }
@Test(expected = MojoExecutionException.class) public void whenNoClassSpecified_haltTheBuild() throws Exception { setMojoParameter("rootClass", null); mojo.execute(); }
@Test public void whenLookingForClassFile_specifyRelativeFilePath() throws Exception { mojo.execute(); assertThat(main.getResourceName(), equalTo(classNameToPath(TEST_ROOT_CLASS) + ".class")); }
@Test(expected = MojoExecutionException.class) public void whenRootClassNotFound_haltTheBuild() throws Exception { main.setClasspathResource(null); mojo.execute(); }
@Test public void useSpecifiedClasspath() throws Exception { String[] classpathElements = new String[] {"a", "b", "c"}; setMojoParameter("compileClasspathElements", Arrays.asList(classpathElements)); URL[] classPathUrls = new URL[] {new URL("file:abc"), new URL("file:bcd"), new URL("file:cde")}; for (int i = 0; i < classpathElements.length; i++) { fileSystem.defineUrl(new File(classpathElements[i]), classPathUrls[i]); } mojo.execute(); assertThat(main.getClasspath(), arrayContaining(classPathUrls)); }
@Test public void whenGenerateMarkdownSpecified_useGeneratedSchemaForMarkdown() throws Exception { ImmutableMap<String, Object> generatedSchema = ImmutableMap.of(); main.setGeneratedSchema(generatedSchema); setMojoParameter("generateMarkdown", true); mojo.execute(); assertThat(main.getMarkdownSchema(), sameInstance(generatedSchema)); }
@Test public void whenIncludeAdditionalPropertiesSet_setOnMain() throws Exception { setMojoParameter("includeAdditionalProperties", true); mojo.execute(); assertThat(main.isIncludeAdditionalProperties(), is(true)); }
@Test public void whenSupportObjectReferencesSet_setOnMain() throws Exception { setMojoParameter("supportObjectReferences", true); mojo.execute(); assertThat(main.isSupportObjectReferences(), is(true)); }
|
### Question:
DomainStatus { DateTime getStartTime() { return startTime; } DomainStatus(); DomainStatus(DomainStatus that); @Nonnull List<DomainCondition> getConditions(); DomainStatus addCondition(DomainCondition newCondition); boolean hasConditionWith(Predicate<DomainCondition> predicate); void removeConditionIf(Predicate<DomainCondition> predicate); String getMessage(); void setMessage(String message); DomainStatus withMessage(String message); String getReason(); void setReason(String reason); DomainStatus withReason(String reason); Integer getReplicas(); void setReplicas(Integer replicas); DomainStatus withReplicas(Integer replicas); List<ServerStatus> getServers(); void setServers(List<ServerStatus> servers); DomainStatus withServers(List<ServerStatus> servers); DomainStatus addServer(ServerStatus server); List<ClusterStatus> getClusters(); void setClusters(List<ClusterStatus> clusters); DomainStatus addCluster(ClusterStatus cluster); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void createPatchFrom(JsonPatchBuilder builder, @Nullable DomainStatus oldStatus); }### Answer:
@Test public void whenCreated_statusHasCreationTime() { assertThat(domainStatus.getStartTime(), SystemClockTestSupport.isDuringTest()); }
|
### Question:
AdminServer extends Server { public AdminService getAdminService() { return adminService; } AdminServer withChannel(String channelName, int nodePort); List<String> getChannelNames(); List<Channel> getChannels(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); AdminService createAdminService(); AdminService getAdminService(); }### Answer:
@Test public void whenConstructedWithAdminService_mayAddLabels() { configureAdminServer() .configureAdminService() .withServiceLabel(NAME1, VALUE1) .withServiceLabel(NAME2, VALUE2); assertThat( domain.getAdminServerSpec().getAdminService().getLabels(), both(hasEntry(NAME1, VALUE1)).and(hasEntry(NAME2, VALUE2))); }
@Test public void whenConstructedWithAdminService_mayAddAnnotations() { configureAdminServer() .configureAdminService() .withServiceAnnotation(NAME1, VALUE1) .withServiceAnnotation(NAME2, VALUE2); assertThat( domain.getAdminServerSpec().getAdminService().getAnnotations(), both(hasEntry(NAME1, VALUE1)).and(hasEntry(NAME2, VALUE2))); }
@Test public void callingGetAdminService_doesNotChangeTheObject() { server1.getAdminService(); assertThat(server1, equalTo(server2)); }
|
### Question:
YamlDocGenerator { String generateForProperty(String fieldName, Map<String, Object> subSchema) { return "| " + "`" + fieldName + "`" + " | " + emptyIfNull(getType(fieldName, subSchema)) + " | " + emptyIfNull(getDescription(fieldName, subSchema)) + " |"; } YamlDocGenerator(Map<String, Object> schema); String generate(String schemaName); String generate(String reference, Map<String, Object> schema); void useKubernetesVersion(String k8sVersion); String getKubernetesSchemaMarkdown(); String getKubernetesSchemaMarkdownFile(); }### Answer:
@Test public void generateMarkdownForProperty() throws NoSuchFieldException { String markdown = generateForProperty(getClass().getDeclaredField("annotatedDouble")); assertThat( markdown, containsString(tableEntry("`annotatedDouble`", "number", "An annotated field"))); }
@Test public void whenSchemaHasUknownTypeAndNoReference_useAsSpecified() throws NoSuchFieldException { Map<String, Object> schema = ImmutableMap.of("anInt", of("type", "integer")); String markdown = new YamlDocGenerator(schema).generateForProperty("anInt", schema); assertThat(markdown, containsString(tableEntry("`anInt`", "integer", ""))); }
@Test public void whenPropertyTypeIsDateTime_doNotGenerateReference() throws NoSuchFieldException { String markdown = generateForProperty(getClass().getDeclaredField("dateTime")); assertThat(markdown, containsString(tableEntry("`dateTime`", "DateTime", ""))); }
@Test public void whenPropertyTypeIsMap_doNotGenerateReference() throws NoSuchFieldException { String markdown = generateForProperty(getClass().getDeclaredField("notes")); assertThat(markdown, containsString(tableEntry("`notes`", "Map", ""))); }
@Test public void whenPropertyTypeIsArrayOfStrings_generateType() throws NoSuchFieldException { String markdown = generateForProperty(getClass().getDeclaredField("myList")); assertThat(markdown, containsString(tableEntry("`myList`", "array of string", ""))); }
@Test public void whenPropertyTypeIsReferenceWithDescription_includeBoth() throws NoSuchFieldException { String markdown = generateForProperty(getClass().getDeclaredField("simpleUsage")); assertThat( markdown, containsString( tableEntry("`simpleUsage`", linkTo("Simple Object", "#simple-object"), "An example"))); }
@Test public void whenPropertyTypeIsReferenceArrayWithDescription_includeBoth() throws NoSuchFieldException { String markdown = generateForProperty(getClass().getDeclaredField("simpleArray")); assertThat( markdown, containsString( tableEntry( "`simpleArray`", "array of " + linkTo("Simple Object", "#simple-object"), "An array"))); }
|
### Question:
YamlDocGenerator { String generateForClass(Map<String, Object> classSchema) { StringBuilder sb = new StringBuilder(CLASS_TABLE_HEADER); Map<String, Object> properties = Optional.ofNullable(subMap(classSchema, "properties")).orElse(new HashMap<>()); for (String propertyName : getSortedKeys(properties)) { sb.append("\n").append(generateForProperty(propertyName, properties)); } return sb.toString(); } YamlDocGenerator(Map<String, Object> schema); String generate(String schemaName); String generate(String reference, Map<String, Object> schema); void useKubernetesVersion(String k8sVersion); String getKubernetesSchemaMarkdown(); String getKubernetesSchemaMarkdownFile(); }### Answer:
@Test public void generateMarkdownForSimpleObject() { YamlDocGenerator generator = new YamlDocGenerator(new HashMap<>()); String markdown = generator.generateForClass(generateSchema(SimpleObject.class)); assertThat( markdown, containsString( String.join( "\n", tableHeader(), tableEntry("`aaBoolean`", "Boolean", "A flag"), tableEntry("`aaString`", "string", "A string"), tableEntry("`depth`", "number", "")))); }
|
### Question:
YamlDocGenerator { public String generate(String schemaName) { return generate(schemaName, schema); } YamlDocGenerator(Map<String, Object> schema); String generate(String schemaName); String generate(String reference, Map<String, Object> schema); void useKubernetesVersion(String k8sVersion); String getKubernetesSchemaMarkdown(); String getKubernetesSchemaMarkdownFile(); }### Answer:
@Test public void generateMarkdownForSimpleObjectWithHeader() { Map<String, Object> schema = generateSchema(SimpleObject.class); YamlDocGenerator generator = new YamlDocGenerator(schema); String markdown = generator.generate("simpleObject"); assertThat( markdown, containsString( String.join( "\n", "### Simple Object", "", tableHeader(), tableEntry("`aaBoolean`", "Boolean", "A flag"), tableEntry("`aaString`", "string", "A string"), tableEntry("`depth`", "number", "")))); }
@Test public void generateMarkdownForObjectWithReferences() { Map<String, Object> schema = generateSchema(ReferencingObject.class); YamlDocGenerator generator = new YamlDocGenerator(schema); String markdown = generator.generate("start"); assertThat( markdown, containsString( String.join( "\n", "### Start", "", tableHeader(), tableEntry("`deprecatedField`", "number", ""), tableEntry("`derived`", linkTo("Derived Object", "#derived-object"), ""), tableEntry("`simple`", linkTo("Simple Object", "#simple-object"), "")))); }
@Test public void generateMarkdownWithReferencedSections() { Map<String, Object> schema = generateSchema(ReferencingObject.class); YamlDocGenerator generator = new YamlDocGenerator(schema); String markdown = generator.generate("start"); assertThat( markdown, containsString( String.join( "\n", "### Start", "", tableHeader(), tableEntry("`deprecatedField`", "number", ""), tableEntry("`derived`", linkTo("Derived Object", "#derived-object"), ""), tableEntry("`simple`", linkTo("Simple Object", "#simple-object"), ""), "", "### Derived Object", "", "A simple object used for testing", "", tableHeader(), tableEntry("`aaBoolean`", "Boolean", "A flag"), tableEntry("`aaString`", "string", "A string")))); }
|
### Question:
SchemaGenerator { public void useKubernetesVersion(String version) throws IOException { KubernetesSchemaReference reference = KubernetesSchemaReference.create(version); URL cacheUrl = reference.getKubernetesSchemaCacheUrl(); if (cacheUrl == null) { throw new IOException("No schema cached for Kubernetes " + version); } addExternalSchema(reference.getKubernetesSchemaUrl(), cacheUrl); } static String prettyPrint(Object schema); void useKubernetesVersion(String version); void addExternalSchema(URL schemaUrl, URL cacheUrl); void setIncludeAdditionalProperties(boolean includeAdditionalProperties); void setSupportObjectReferences(boolean supportObjectReferences); void setIncludeSchemaReference(boolean includeSchemaReference); void addPackageToSuppressDescriptions(String packageName); Map<String, Object> generate(Class someClass); }### Answer:
@Test(expected = IOException.class) public void whenNonCachedK8sVersionSpecified_throwException() throws IOException { generator.useKubernetesVersion("1.12.0"); }
|
### Question:
KubernetesApiNames { public static boolean matches(String className, Class<?> candidateClass) { if (!candidateClass.getName().startsWith("io.kubernetes.client")) { return false; } String[] parts = className.split("\\."); if (parts.length < 2) { return false; } String last = parts[parts.length - 1]; String nextToLast = parts[parts.length - 2]; String simpleName = candidateClass.getSimpleName(); return matches(simpleName, nextToLast, last); } static boolean matches(String className, Class<?> candidateClass); }### Answer:
@Test public void matchTopLevelClass() { assertThat(KubernetesApiNames.matches("io.k8s.api.core.v1.EnvVar", V1EnvVar.class), is(true)); }
@Test public void matchNestedClass() { assertThat(KubernetesApiNames.matches("io.k8s.api.core.v1.EnvVar", V1.EnvVar.class), is(true)); }
@Test public void dontMatchOthers() { assertThat(KubernetesApiNames.matches("abc", V1EnvVarSource.class), is(false)); assertThat( KubernetesApiNames.matches("io.k8s.api.core.v1.EnvVar", V1EnvVarSource.class), is(false)); }
|
### Question:
DomainStatus { public boolean hasConditionWith(Predicate<DomainCondition> predicate) { return !getConditionsMatching(predicate).isEmpty(); } DomainStatus(); DomainStatus(DomainStatus that); @Nonnull List<DomainCondition> getConditions(); DomainStatus addCondition(DomainCondition newCondition); boolean hasConditionWith(Predicate<DomainCondition> predicate); void removeConditionIf(Predicate<DomainCondition> predicate); String getMessage(); void setMessage(String message); DomainStatus withMessage(String message); String getReason(); void setReason(String reason); DomainStatus withReason(String reason); Integer getReplicas(); void setReplicas(Integer replicas); DomainStatus withReplicas(Integer replicas); List<ServerStatus> getServers(); void setServers(List<ServerStatus> servers); DomainStatus withServers(List<ServerStatus> servers); DomainStatus addServer(ServerStatus server); List<ClusterStatus> getClusters(); void setClusters(List<ClusterStatus> clusters); DomainStatus addCluster(ClusterStatus cluster); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void createPatchFrom(JsonPatchBuilder builder, @Nullable DomainStatus oldStatus); }### Answer:
@Test public void beforeConditionAdded_statusFailsPredicate() { assertThat(domainStatus.hasConditionWith(c -> c.hasType(Available)), is(false)); }
|
### Question:
AdminServer extends Server { public AdminService createAdminService() { if (adminService == null) { adminService = new AdminService(); } return adminService; } AdminServer withChannel(String channelName, int nodePort); List<String> getChannelNames(); List<Channel> getChannels(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); AdminService createAdminService(); AdminService getAdminService(); }### Answer:
@Test public void whenHaveSameAdminServiceLabels_objectsAreEqual() { server1.createAdminService().withServiceLabel(NAME1, VALUE1).withServiceLabel(NAME2, VALUE2); server2.createAdminService().withServiceLabel(NAME2, VALUE2).withServiceLabel(NAME1, VALUE1); assertThat(server1, equalTo(server2)); }
@Test public void whenHaveDifferentAdminServiceLabels_objectsAreNotEqual() { server1.createAdminService().withServiceLabel(NAME1, VALUE1).withServiceLabel(NAME2, VALUE2); server2.createAdminService().withServiceLabel(NAME1, VALUE2).withServiceLabel(NAME2, VALUE1); assertThat(server1, not(equalTo(server2))); }
@Test public void whenHaveSameAdminServiceAnnotations_objectsAreEqual() { server1 .createAdminService() .withServiceAnnotation(NAME1, VALUE1) .withServiceAnnotation(NAME2, VALUE2); server2 .createAdminService() .withServiceAnnotation(NAME2, VALUE2) .withServiceAnnotation(NAME1, VALUE1); assertThat(server1, equalTo(server2)); }
@Test public void whenHaveDifferentAdminServiceAnnotations_objectsAreNotEqual() { server1 .createAdminService() .withServiceAnnotation(NAME1, VALUE1) .withServiceAnnotation(NAME2, VALUE2); server2 .createAdminService() .withServiceAnnotation(NAME1, VALUE2) .withServiceAnnotation(NAME2, VALUE1); assertThat(server1, not(equalTo(server2))); }
|
### Question:
DomainStatus { public DomainStatus addServer(ServerStatus server) { synchronized (servers) { for (ListIterator<ServerStatus> it = servers.listIterator(); it.hasNext(); ) { if (Objects.equals(it.next().getServerName(), server.getServerName())) { it.remove(); } } servers.add(server); Collections.sort(servers); } return this; } DomainStatus(); DomainStatus(DomainStatus that); @Nonnull List<DomainCondition> getConditions(); DomainStatus addCondition(DomainCondition newCondition); boolean hasConditionWith(Predicate<DomainCondition> predicate); void removeConditionIf(Predicate<DomainCondition> predicate); String getMessage(); void setMessage(String message); DomainStatus withMessage(String message); String getReason(); void setReason(String reason); DomainStatus withReason(String reason); Integer getReplicas(); void setReplicas(Integer replicas); DomainStatus withReplicas(Integer replicas); List<ServerStatus> getServers(); void setServers(List<ServerStatus> servers); DomainStatus withServers(List<ServerStatus> servers); DomainStatus addServer(ServerStatus server); List<ClusterStatus> getClusters(); void setClusters(List<ClusterStatus> clusters); DomainStatus addCluster(ClusterStatus cluster); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); void createPatchFrom(JsonPatchBuilder builder, @Nullable DomainStatus oldStatus); }### Answer:
@Test public void whenHasServerStatusWithHealth_cloneIsEqual() { domainStatus.addServer(new ServerStatus().withHealth(new ServerHealth().withOverallHealth("peachy"))); DomainStatus clone = new DomainStatus(this.domainStatus); assertThat(clone, equalTo(domainStatus)); }
@Test public void whenHasServerStatusWithoutHealth_cloneIsEqual() { domainStatus.addServer(new ServerStatus().withServerName("myserver")); DomainStatus clone = new DomainStatus(this.domainStatus); assertThat(clone, equalTo(domainStatus)); }
|
### Question:
RestBackendImpl implements RestBackend { @Override public Set<String> getDomainUids() { LOGGER.entering(); authorize(null, Operation.list); Set<String> result = new TreeSet<>(); List<Domain> domains = getDomainsList(); for (Domain domain : domains) { result.add(domain.getDomainUid()); } LOGGER.exiting(result); return result; } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test public void retrieveRegisteredDomainIds() { assertThat(restBackend.getDomainUids(), containsInAnyOrder(NAME1, NAME2)); }
|
### Question:
RestBackendImpl implements RestBackend { @Override public boolean isDomainUid(String domainUid) { return getDomain(domainUid).isPresent(); } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test public void validateKnownUid() { assertThat(restBackend.isDomainUid(NAME2), is(true)); }
@Test public void rejectUnknownUid() { assertThat(restBackend.isDomainUid("no_such_uid"), is(false)); }
|
### Question:
RestBackendImpl implements RestBackend { @Override public void performDomainAction(String domainUid, DomainAction params) { verifyDomain(domainUid); authorize(domainUid, Operation.update); switch (Optional.ofNullable(params.getAction()).orElse(DomainActionType.UNKNOWN)) { case INTROSPECT: introspect(domainUid); break; case RESTART: restartDomain(domainUid); break; default: throw new WebApplicationException(Status.BAD_REQUEST); } } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test(expected = WebApplicationException.class) public void whenUnknownDomain_throwException() { restBackend.performDomainAction("no_such_uid", new DomainAction(DomainActionType.INTROSPECT)); }
@Test(expected = WebApplicationException.class) public void whenUnknownDomainUpdateCommand_throwException() { restBackend.performDomainAction(NAME1, new DomainAction(null)); }
@Test public void whenIntrospectionRequestedWhileNoIntrospectVersionDefined_setIntrospectVersion() { restBackend.performDomainAction(NAME1, createIntrospectRequest()); assertThat(getUpdatedIntrospectVersion(), equalTo(INITIAL_VERSION)); }
@Test public void whenIntrospectionRequestedWhileIntrospectVersionNonNumeric_setNumericVersion() { configurator.withIntrospectVersion("zork"); restBackend.performDomainAction(NAME1, createIntrospectRequest()); assertThat(getUpdatedIntrospectVersion(), equalTo(INITIAL_VERSION)); }
@Test public void whenIntrospectionRequestedWhileIntrospectVersionDefined_incrementIntrospectVersion() { configurator.withIntrospectVersion("17"); restBackend.performDomainAction(NAME1, createIntrospectRequest()); assertThat(getUpdatedIntrospectVersion(), equalTo("18")); }
@Test public void whenClusterRestartRequestedWhileNoRestartVersionDefined_setRestartVersion() { restBackend.performDomainAction(NAME1, createDomainRestartRequest()); assertThat(getUpdatedRestartVersion(), equalTo(INITIAL_VERSION)); }
@Test public void whenRestartRequestedWhileRestartVersionDefined_incrementIntrospectVersion() { configurator.withRestartVersion("23"); restBackend.performDomainAction(NAME1, createDomainRestartRequest()); assertThat(getUpdatedRestartVersion(), equalTo("24")); }
@Test public void whenDomainRestartRequestedWhileNoRestartVersionDefined_setRestartVersion() { restBackend.performDomainAction(NAME1, createDomainRestartRequest()); assertThat(getUpdatedRestartVersion(), equalTo(INITIAL_VERSION)); }
|
### Question:
RestBackendImpl implements RestBackend { @Override public Set<String> getClusters(String domainUid) { LOGGER.entering(domainUid); verifyDomain(domainUid); authorize(domainUid, Operation.get); Map<String, WlsClusterConfig> wlsClusterConfigs = getWlsConfiguredClusters(domainUid); Set<String> result = wlsClusterConfigs.keySet(); LOGGER.exiting(result); return result; } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test public void retrieveDefinedClusters() { configSupport.addWlsCluster("cluster1", "ms1", "ms2", "ms3"); configSupport.addWlsCluster("cluster2", "ms4", "ms5", "ms6"); setupScanCache(); assertThat(restBackend.getClusters(NAME1), containsInAnyOrder("cluster1", "cluster2")); }
|
### Question:
RestBackendImpl implements RestBackend { @Override public boolean isCluster(String domainUid, String cluster) { LOGGER.entering(domainUid, cluster); authorize(domainUid, Operation.list); boolean result = getClusters(domainUid).contains(cluster); LOGGER.exiting(result); return result; } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test public void acceptDefinedClusterName() { configSupport.addWlsCluster("cluster1", "ms1", "ms2", "ms3"); configSupport.addWlsCluster("cluster2", "ms4", "ms5", "ms6"); setupScanCache(); assertThat(restBackend.isCluster(NAME1, "cluster1"), is(true)); }
@Test public void rejectUndefinedClusterName() { configSupport.addWlsCluster("cluster1", "ms1", "ms2", "ms3"); configSupport.addWlsCluster("cluster2", "ms4", "ms5", "ms6"); setupScanCache(); assertThat(restBackend.isCluster(NAME1, "cluster3"), is(false)); }
|
### Question:
RestBackendImpl implements RestBackend { @Override public void scaleCluster(String domainUid, String cluster, int managedServerCount) { LOGGER.entering(domainUid, cluster, managedServerCount); if (managedServerCount < 0) { throw createWebApplicationException( Status.BAD_REQUEST, MessageKeys.INVALID_MANAGE_SERVER_COUNT, managedServerCount); } authorize(domainUid, Operation.update); forDomainDo(domainUid, d -> performScaling(d, cluster, managedServerCount)); LOGGER.exiting(); } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test(expected = WebApplicationException.class) public void whenNegativeScaleSpecified_throwException() { restBackend.scaleCluster(NAME1, "cluster1", -1); }
@Test public void whenPerClusterReplicaSettingMatchesScaleRequest_doNothing() { configureCluster("cluster1").withReplicas(5); restBackend.scaleCluster(NAME1, "cluster1", 5); assertThat(getUpdatedDomain(), nullValue()); }
@Test public void whenPerClusterReplicaSetting_scaleClusterUpdatesSetting() { configureCluster("cluster1").withReplicas(1); restBackend.scaleCluster(NAME1, "cluster1", 5); assertThat(getUpdatedDomain().getReplicaCount("cluster1"), equalTo(5)); }
@Test @Ignore public void whenNoPerClusterReplicaSetting_scaleClusterCreatesOne() { restBackend.scaleCluster(NAME1, "cluster1", 5); assertThat(getUpdatedDomain().getReplicaCount("cluster1"), equalTo(5)); }
@Test public void whenNoPerClusterReplicaSettingAndDefaultMatchesRequest_doNothing() { configureDomain().withDefaultReplicaCount(REPLICA_LIMIT); restBackend.scaleCluster(NAME1, "cluster1", REPLICA_LIMIT); assertThat(getUpdatedDomain(), nullValue()); }
@Test(expected = WebApplicationException.class) public void whenReplaceDomainReturnsError_scaleClusterThrowsException() { testSupport.failOnResource(DOMAIN, NAME2, NS, HTTP_CONFLICT); DomainConfiguratorFactory.forDomain(domain2).configureCluster("cluster1").withReplicas(2); restBackend.scaleCluster(NAME2, "cluster1", 3); }
|
### Question:
RestBackendImpl implements RestBackend { WlsDomainConfig getWlsDomainConfig(String domainUid) { for (String ns : targetNamespaces) { WlsDomainConfig config = INSTANCE.getWlsDomainConfig(ns, domainUid); if (config != null) { return config; } } return new WlsDomainConfig(null); } RestBackendImpl(String principal, String accessToken, Collection<String> targetNamespaces); @Override Set<String> getDomainUids(); @Override boolean isDomainUid(String domainUid); @Override void performDomainAction(String domainUid, DomainAction params); @Override Set<String> getClusters(String domainUid); @Override boolean isCluster(String domainUid, String cluster); @Override void scaleCluster(String domainUid, String cluster, int managedServerCount); static final String INITIAL_VERSION; }### Answer:
@Test public void verify_getWlsDomainConfig_returnsWlsDomainConfig() { WlsDomainConfig wlsDomainConfig = ((RestBackendImpl) restBackend).getWlsDomainConfig(NAME1); assertThat(wlsDomainConfig.getName(), equalTo(NAME1)); }
@Test public void verify_getWlsDomainConfig_doesNotReturnNull_whenNoSuchDomainUid() { WlsDomainConfig wlsDomainConfig = ((RestBackendImpl) restBackend).getWlsDomainConfig("NoSuchDomainUID"); assertThat(wlsDomainConfig, notNullValue()); }
@Test public void verify_getWlsDomainConfig_doesNotReturnNull_whenScanIsNull() { config = null; WlsDomainConfig wlsDomainConfig = ((RestBackendImpl) restBackend).getWlsDomainConfig(NAME1); assertThat(wlsDomainConfig, notNullValue()); }
|
### Question:
HttpAsyncRequestStep extends Step { @Override public NextAction apply(Packet packet) { AsyncProcessing processing = new AsyncProcessing(packet); return doSuspend(processing::process); } private HttpAsyncRequestStep(HttpRequest request, HttpResponseStep responseStep); static HttpAsyncRequestStep createGetRequest(String url, HttpResponseStep responseStep); static HttpAsyncRequestStep create(HttpRequest request, HttpResponseStep responseStep); HttpAsyncRequestStep withTimeoutSeconds(long timeoutSeconds); @Override NextAction apply(Packet packet); }### Answer:
@Test public void whenRequestMade_suspendProcessing() { NextAction action = requestStep.apply(packet); assertThat(FiberTestSupport.isSuspendRequested(action), is(true)); }
@Test public void whenResponseReceived_resumeFiber() { final NextAction nextAction = requestStep.apply(packet); receiveResponseBeforeTimeout(nextAction, response); assertThat(fiber.wasResumed(), is(true)); }
@Test public void whenErrorResponseReceived_logMessage() { final NextAction nextAction = requestStep.apply(packet); receiveResponseBeforeTimeout(nextAction, createStub(HttpResponseStub.class, 500)); assertThat(logRecords, containsFine(HTTP_METHOD_FAILED)); }
@Test public void whenResponseReceived_populatePacket() { NextAction nextAction = requestStep.apply(packet); receiveResponseBeforeTimeout(nextAction, response); assertThat(getResponse(), sameInstance(response)); }
@Test public void whenResponseTimesOut_resumeFiber() { consoleMemento.ignoreMessage(HTTP_REQUEST_TIMED_OUT); NextAction nextAction = requestStep.apply(packet); receiveTimeout(nextAction); assertThat(fiber.wasResumed(), is(true)); }
@Test public void whenResponseTimesOut_packetHasNoResponse() { consoleMemento.ignoreMessage(HTTP_REQUEST_TIMED_OUT); HttpResponseStep.addToPacket(packet, response); NextAction nextAction = requestStep.apply(packet); receiveTimeout(nextAction); assertThat(getResponse(), nullValue()); }
@Test public void whenResponseTimesOut_logWarning() { HttpResponseStep.addToPacket(packet, response); NextAction nextAction = requestStep.apply(packet); receiveTimeout(nextAction); assertThat(logRecords, containsFine(HTTP_REQUEST_TIMED_OUT)); }
|
### Question:
HttpResponseStep extends Step { @Override public NextAction apply(Packet packet) { return Optional.ofNullable(getResponse(packet)).map(r -> doApply(packet, r)).orElse(doNext(packet)); } HttpResponseStep(Step next); @Override NextAction apply(Packet packet); abstract NextAction onSuccess(Packet packet, HttpResponse<String> response); abstract NextAction onFailure(Packet packet, HttpResponse<String> response); }### Answer:
@Test public void whenNoResponseProvided_skipProcessing() { NextAction nextAction = responseStep.apply(new Packet()); assertThat(responseStep.getSuccessResponse(), nullValue()); assertThat(responseStep.getFailureResponse(), nullValue()); assertThat(nextAction.getNext(), sameInstance(terminalStep)); }
|
### Question:
Step { public String getName() { String name = getClass().getName(); int idx = name.lastIndexOf('.'); if (idx >= 0) { name = name.substring(idx + 1); } name = name.endsWith("Step") ? name.substring(0, name.length() - 4) : name; String detail = getDetail(); return detail != null ? name + "(" + detail + ")" : name; } protected Step(); protected Step(Step next); static Step chain(Step... stepGroups); String getName(); @Override String toString(); abstract NextAction apply(Packet packet); Step getNext(); }### Answer:
@Test public void testSuspendAndThrow() throws InterruptedException { final Step stepline = createStepline(Arrays.asList(Step1.class, Step2.class, Step3.class)); Packet p = new Packet(); Map<Class<? extends BaseStep>, Command> commandMap = new HashMap<>(); commandMap.put( Step2.class, new Command(RELEASE_SEMAPHORE, ACQUIRE_SEMAPHORE, SUSPEND_AND_THROW)); p.put(NA, commandMap); Semaphore releaseSemaphore = new Semaphore(0); Semaphore acquireSemaphore = new Semaphore(0); p.put(Step2.class.getName() + RELEASE_SEMAPHORE_SUFFIX, releaseSemaphore); p.put(Step2.class.getName() + ACQUIRE_SEMAPHORE_SUFFIX, acquireSemaphore); Semaphore signal = new Semaphore(0); List<Throwable> throwables = new ArrayList<>(); engine .createFiber() .start( stepline, p, new CompletionCallback() { @Override public void onCompletion(Packet packet) { signal.release(); } @Override public void onThrowable(Packet packet, Throwable throwable) { throwables.add(throwable); signal.release(); } }); releaseSemaphore.acquire(); acquireSemaphore.release(); @SuppressWarnings({"unchecked", "rawtypes"}) List<Step> called = (List) p.get(MARK); boolean result = signal.tryAcquire(1, TimeUnit.SECONDS); assertFalse(result); assertEquals(2, called.size()); assertTrue(called.get(0) instanceof Step1); assertTrue(called.get(1) instanceof Step2); }
@Test public void testCancel() throws InterruptedException { final Step stepline = createStepline(Arrays.asList(Step1.class, Step2.class, Step3.class)); Packet p = new Packet(); Map<Class<? extends BaseStep>, Command> commandMap = new HashMap<>(); commandMap.put(Step2.class, new Command(RELEASE_SEMAPHORE, ACQUIRE_SEMAPHORE, INVOKE_NEXT)); p.put(NA, commandMap); Semaphore releaseSemaphore = new Semaphore(0); Semaphore acquireSemaphore = new Semaphore(0); p.put(Step2.class.getName() + RELEASE_SEMAPHORE_SUFFIX, releaseSemaphore); p.put(Step2.class.getName() + ACQUIRE_SEMAPHORE_SUFFIX, acquireSemaphore); Semaphore signal = new Semaphore(0); List<Throwable> throwables = new ArrayList<>(); Fiber f = engine.createFiber(); f.start( stepline, p, new CompletionCallback() { @Override public void onCompletion(Packet packet) { signal.release(); } @Override public void onThrowable(Packet packet, Throwable throwable) { throwables.add(throwable); signal.release(); } }); releaseSemaphore.acquire(); f.cancel(false); acquireSemaphore.release(); @SuppressWarnings({"unchecked", "rawtypes"}) final List<Step> called = (List) p.get(MARK); boolean result = signal.tryAcquire(1, TimeUnit.SECONDS); assertFalse(result); assertTrue(f.isCancelled()); assertFalse(f.isDone()); assertEquals(2, called.size()); assertTrue(called.get(0) instanceof Step1); assertTrue(called.get(1) instanceof Step2); assertTrue(throwables.isEmpty()); }
|
### Question:
WeightedBinaryTree { public static int getMinimumTreeWeight(int[] array) { if ((array == null) || (array.length == 0)) { throw new IllegalArgumentException("Input array is null or empty"); } int level = 0; int weight = 0; Arrays.sort(array); for (int i = 0; i < array.length; i++) { if (((i + 1) & i) == 0) { level++; } weight += level * array[array.length - 1 - i]; } return weight; } static int getMinimumTreeWeight(int[] array); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testWeightedBinaryTreeNullArray() { getMinimumTreeWeight(null); }
@Test(expected = IllegalArgumentException.class) public void testWeightedBinaryTreeEmptyArray() { getMinimumTreeWeight(new int[0]); }
@Test public void testWeightedBinaryTree1() { assertThat(getMinimumTreeWeight(new int[] { 5 }), is(5)); }
@Test public void testWeightedBinaryTree2() { assertThat(getMinimumTreeWeight(new int[] { 5, 3 }), is(11)); }
@Test public void testWeightedBinaryTree3() { assertThat(getMinimumTreeWeight(new int[] { 4, 5, 3 }), is(19)); }
@Test public void testWeightedBinaryTree4() { assertThat(getMinimumTreeWeight(new int[] { 4, 5, 3, 4 }), is(30)); }
@Test public void testWeightedBinaryTree5() { assertThat(getMinimumTreeWeight(new int[] { 4, 5, 3, 7, 4 }), is(46)); }
@Test public void testWeightedBinaryTree6() { assertThat( getMinimumTreeWeight(new int[] { 4, 5, 100, 3, 7, 4, 5, 7 }), is(194)); }
@Test public void testWeightedBinaryTree7() { assertThat(getMinimumTreeWeight(new int[] { 1, 1, 1, 1, 1, 1, 1, 1 }), is(21)); }
|
### Question:
Anagram { public static boolean isAnagram(String first, String second) { if (first == null || second == null) { throw new IllegalArgumentException("Input arguments cannot be null"); } if (first.length() != second.length()) { return false; } int[] occurrences = new int[256]; for (int i = 0; i < first.length(); i++) { int pos = first.charAt(i); if (pos < 0 || pos > 255) { throw new IllegalArgumentException("First string contains non-ASCII code at position #" + i); } occurrences[pos]++; } for (int i = 0; i < second.length(); i++) { int pos = second.charAt(i); if (pos < 0 || pos > 255) { throw new IllegalArgumentException("Second string contains non-ASCII code at position #" + i); } occurrences[pos]--; if (occurrences[pos] < 0) { return false; } } return true; } static boolean isAnagram(String first, String second); }### Answer:
@Test public void testIsAnagram4() { assertTrue(isAnagram("abcda", "aabdc")); }
@Test public void testIsAnagram5() { assertTrue(isAnagram("abcdaxzx", "axabzdcx")); }
@Test public void testIsAnagram6() { assertFalse(isAnagram("abc123daxzxx", "213axabzdcx1")); }
@Test public void testIsAnagram7() { assertTrue(isAnagram("" + (char) (0) + (char) (255), "" + (char) (0) + (char) (255))); }
@Test(expected = IllegalArgumentException.class) public void testIsAnagramNullFirstArgument() { isAnagram(null, "abc"); }
@Test(expected = IllegalArgumentException.class) public void testIsAnagramNullSecondArgument() { isAnagram("abc", null); }
@Test(expected = IllegalArgumentException.class) public void testIsAnagramFirstArgumentNonASCII() { isAnagram("abc" + NON_ASCII_CHAR, "abcd"); }
@Test(expected = IllegalArgumentException.class) public void testIsAnagramSecondArgumentNonASCII() { isAnagram("abcd", "abc" + NON_ASCII_CHAR); }
@Test public void testIsAnagramDifferentLenght() { assertFalse(isAnagram("abcd", "abcde")); }
@Test public void testIsAnagram1() { assertFalse(isAnagram("abcd", "abcde")); }
@Test public void testIsAnagram2() { assertFalse(isAnagram("abcd", "xbcd")); }
@Test public void testIsAnagram3() { assertFalse(isAnagram("abcd", "abCd")); }
|
### Question:
BinaryTreesCount { public static BigInteger findBinaryTreesCount(int n) { if (n <= 0) { throw new IllegalArgumentException("Input number of vertices is not positive"); } return findBinaryTreesCount(n, new BigInteger[n + 1]); } static BigInteger findBinaryTreesCount(int n); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindBinaryTreesCountNegativeN() { findBinaryTreesCount(-1); }
@Test public void testFindBinaryTrees1() { assertThat(findBinaryTreesCount(1), is(BigInteger.valueOf(1))); }
@Test public void testFindBinaryTrees2() { assertThat(findBinaryTreesCount(2), is(BigInteger.valueOf(2))); }
@Test public void testFindBinaryTrees3() { assertThat(findBinaryTreesCount(3), is(BigInteger.valueOf(5))); }
@Test public void testFindBinaryTrees4() { assertThat(findBinaryTreesCount(4), is(BigInteger.valueOf(14))); }
@Test public void testFindBinaryTrees5() { assertThat(findBinaryTreesCount(14), is(BigInteger.valueOf(2674440))); }
@Test public void testFindBinaryTrees6() { assertThat(findBinaryTreesCount(20), is(BigInteger.valueOf(6564120420L))); }
@Test public void testFindBinaryTrees7() { assertThat(findBinaryTreesCount(30), is(BigInteger.valueOf(3814986502092304L))); }
|
### Question:
JosephusProblem { public static int getLastPerson(int n, int k) { if (n <= 0 || k <= 0) { throw new IllegalArgumentException("Input arguments should be positive"); } int lastPerson = 0; for (int i = 2; i <= n; i++) { lastPerson += k; lastPerson %= i; } return lastPerson; } static int getLastPerson(int n, int k); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetLastPersonNonPositiveN() { getLastPerson(0, 10); }
@Test(expected = IllegalArgumentException.class) public void testGetLastPersonNonPositiveK() { getLastPerson(10, 0); }
@Test public void testGetLastPerson1() { assertThat(getLastPerson(10, 1), is(9)); }
@Test public void testGetLastPerson2() { assertThat(getLastPerson(10, 2), is(4)); }
@Test public void testGetLastPerson3() { assertThat(getLastPerson(10, 3), is(3)); }
@Test public void testGetLastPerson4() { assertThat(getLastPerson(10, 4), is(4)); }
@Test public void testGetLastPerson5() { assertThat(getLastPerson(10, 5), is(2)); }
@Test public void testGetLastPerson6() { assertThat(getLastPerson(10, 6), is(2)); }
@Test public void testGetLastPerson7() { assertThat(getLastPerson(10, 7), is(8)); }
@Test public void testGetLastPerson8() { assertThat(getLastPerson(10, 8), is(0)); }
@Test public void testGetLastPerson9() { assertThat(getLastPerson(10, 9), is(6)); }
@Test public void testGetLastPerson10() { assertThat(getLastPerson(10, 10), is(7)); }
|
### Question:
CharsReplacer { public static Set<String> generatePasswords(String word, Map<Character, char[]> replacer) { if (word == null) { throw new IllegalArgumentException("Input word should be not null"); } if (replacer == null) { throw new IllegalArgumentException("Input replacer should be not null"); } Set<String> passwords = new HashSet<>(); passwords.add(word); generatePasswords(word, replacer, 0, passwords); return passwords; } static Set<String> generatePasswords(String word, Map<Character, char[]> replacer); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGeneratePasswordsNullWord() { generatePasswords(null, replacer); }
@Test(expected = IllegalArgumentException.class) public void testGeneratePasswordsNullReplacer() { generatePasswords("ab", null); }
@Test public void testGeneratePasswords1() { Set<String> actual = generatePasswords("z", replacer); Set<String> expected = new HashSet<>(singletonList("z")); assertThat(actual, is(expected)); }
@Test public void testGeneratePasswords2() { Set<String> actual = generatePasswords("e", replacer); Set<String> expected = new HashSet<>(asList("e", "9", "0")); assertThat(actual, is(expected)); }
@Test public void testGeneratePasswords3() { Set<String> actual = generatePasswords("xey", replacer); Set<String> expected = new HashSet<>(asList("xey", "x9y", "x0y")); assertThat(actual, is(expected)); }
@Test public void testGeneratePasswords4() { Set<String> actual = generatePasswords("ab", replacer); Set<String> expected = new HashSet<>(asList("ab", "1b", "2b", "a3", "a4", "13", "14", "23", "24")); assertThat(actual, is(expected)); }
@Test public void testGeneratePasswords5() { Set<String> actual = generatePasswords("azb", replacer); Set<String> expected = new HashSet<>(asList("azb", "1zb", "2zb", "az3", "az4", "1z3", "1z4", "2z3", "2z4")); assertThat(actual, is(expected)); }
|
### Question:
ValidNumber { public static boolean isValid(String number) { if (number == null || number.isEmpty()) { throw new IllegalArgumentException( "Input string should be not null and not empty"); } if (number.length() == 1 && number.charAt(0) - '0' >= 0 && number.charAt(0) - '0' <= 9) { return true; } int illegalSymbol = -1; boolean invalid = false; boolean[] digits = new boolean[10]; for (int i = 0; i < number.length(); i++) { int digit = number.charAt(i) - '0'; if (digit < 0 || digit > 9) { illegalSymbol = i; break; } invalid |= digit == 0 || digit == 1 || digits[digit]; digits[digit] = true; } if (illegalSymbol > -1) { throw new IllegalArgumentException("Digit #" + illegalSymbol + " is not valid"); } if (invalid) { return false; } return !(digits[2] && digits[3] && digits[6]) && !(digits[2] && digits[4] && digits[8]) && !(digits[3] && digits[4] && digits[6] && digits[8]); } static boolean isValid(String number); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testIsValidNullString() { isValid(null); }
@Test(expected = IllegalArgumentException.class) public void testIsValidEmptyNull() { isValid(""); }
@Test(expected = IllegalArgumentException.class) public void testIsValidStringIsNotANumber1() { isValid(" "); }
@Test(expected = IllegalArgumentException.class) public void testIsValidStringIsNotANumber2() { isValid("2342 23"); }
@Test(expected = IllegalArgumentException.class) public void testIsValidStringIsNotANumber3() { isValid("2342s23"); }
@Test public void testIsValidString() { assertTrue(isValid("0")); assertTrue(isValid("1")); assertFalse(isValid("12")); assertTrue(isValid("2")); assertFalse(isValid("1248")); assertFalse(isValid("248")); assertTrue(isValid("48")); assertFalse(isValid("77")); assertTrue(isValid("75468")); assertFalse(isValid("375468")); assertFalse(isValid("3625")); assertFalse(isValid("3525")); assertTrue(isValid("3425")); }
|
### Question:
TripletInSequenceWithSpecialProperty { public static int[] findTriplet(int[] a) { if ((a == null) || (a.length < 3)) { throw new IllegalArgumentException( "Array should have at least 3 elements"); } if ((a[0] < a[1]) || (a[a.length - 1] < a[a.length - 2])) { throw new IllegalArgumentException( "Array does not have special property"); } if (a.length == 3) { return new int[] { a[0], a[1], a[2] }; } int left = 0; int right = a.length - 2; while (left < right) { int middle = left + ((right - left) >> 1); if (a[middle + 1] - a[middle] < 0) { left = middle + 1; } else { right = middle; } } return new int[] { a[left - 1], a[left], a[left + 1] }; } static int[] findTriplet(int[] a); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindTripletWithNullArray() { findTriplet(null); }
@Test(expected = IllegalArgumentException.class) public void testFindTripletWithEmptyArray() { findTriplet(null); }
@Test(expected = IllegalArgumentException.class) public void testFindTripletWithTwoElementArray() { findTriplet(new int[] { 1, 2 }); }
@Test(expected = IllegalArgumentException.class) public void testFindTripletWithThreeElementsNonSpecialArray() { findTriplet(new int[] { 1, 2, 3 }); }
@Test(expected = IllegalArgumentException.class) public void testFindTripletWithFourElementsNonSpecialArray() { findTriplet(new int[] { 1, 2, 3, 4 }); }
@Test public void testFindTripletWithThreeElementArray() { int[] array = new int[] { 2, 2, 3 }; int[] expected = new int[] { 2, 2, 3 }; int[] res = findTriplet(array); assertThat( "Result is not matched with array " + Arrays.toString(array), res, is(expected)); }
@Test public void testFindTripletWithFourElementArray() { int[] array = new int[] { 2, 2, 1, 3 }; int[] expected = new int[] { 2, 1, 3 }; int[] res = findTriplet(array); assertThat( "Result is not matched with array " + Arrays.toString(array), res, is(expected)); }
@Test public void testFindTripletWithFiveElementArray() { int[] array = new int[] { 2, 2, 1, 3, 5 }; int[] expected = new int[] { 2, 1, 3 }; int[] res = findTriplet(array); assertThat( "Result is not matched with array " + Arrays.toString(array), res, is(expected)); }
@Test public void testFindTripletWithLongArray() { int[] array = new int[] { 9, 8, 5, 4, 3, 2, 6, 7 }; int[] expected = new int[] { 3, 2, 6 }; int[] res = findTriplet(array); assertThat( "Result is not matched with array " + Arrays.toString(array), res, is(expected)); }
|
### Question:
FindNthMaxNumber { public static int findNthMaxNumberUsingSelectionSearch(int[] sequence, int n) { if (sequence == null) { throw new IllegalArgumentException("Input array is null"); } if (n < 1) { throw new IllegalArgumentException("Input n is non-positive"); } if (sequence.length < n) { throw new IllegalArgumentException("Array size is less than input n"); } return findNthMaxNumberUsingSelectionSearch(copyOf(sequence, sequence.length), n - 1, 0, sequence.length - 1); } static int findNthMaxNumberUsingSelectionSearch(int[] sequence, int n); static int findNthMaxNumberUsingBinaryHeap(int[] sequence, int n); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindNthMaxNumberUsingSelectionSearchNullArray() { findNthMaxNumberUsingSelectionSearch(null, 1); }
@Test(expected = IllegalArgumentException.class) public void testFindNthMaxNumberUsingSelectionSearchLowN() { findNthMaxNumberUsingSelectionSearch(new int[]{2, 1, 3, 4, 0}, 0); }
@Test(expected = IllegalArgumentException.class) public void testFindNthMaxNumberUsingSelectionSearchHighN() { findNthMaxNumberUsingSelectionSearch(new int[]{2, 1, 3, 4, 0}, 6); }
@Test public void testFindNthMaxNumberUsingSelectionSearch1() { int[] sequence = new int[]{2, 1, 3, 4, 0, -1, 7, 5}; assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 1), is(7)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 2), is(5)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 3), is(4)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 4), is(3)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 5), is(2)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 6), is(1)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 7), is(0)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 8), is(-1)); }
@Test public void testFindNthMaxNumberUsingSelectionSearch2() { int[] sequence = new int[]{2, -4, 5, 6, 0, 7, -1, 10, 9}; assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 1), is(10)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 2), is(9)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 3), is(7)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 4), is(6)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 5), is(5)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 6), is(2)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 7), is(0)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 8), is(-1)); assertThat(findNthMaxNumberUsingSelectionSearch(sequence, 9), is(-4)); }
|
### Question:
FindNthMaxNumber { public static int findNthMaxNumberUsingBinaryHeap(int[] sequence, int n) { if (sequence == null) { throw new IllegalArgumentException("Input array is null"); } if (n < 1) { throw new IllegalArgumentException("Input n is non-positive"); } if (sequence.length < n) { throw new IllegalArgumentException("Array size is less than input n"); } PriorityQueue<Integer> binaryHeap = new PriorityQueue<>(n); for (int element : sequence) { if (binaryHeap.size() < n) { binaryHeap.add(element); } else { Integer min = binaryHeap.peek(); if (min < element) { binaryHeap.poll(); binaryHeap.add(element); } } } return binaryHeap.peek(); } static int findNthMaxNumberUsingSelectionSearch(int[] sequence, int n); static int findNthMaxNumberUsingBinaryHeap(int[] sequence, int n); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindNthMaxNumberUsingBinaryHeapNullArray() { findNthMaxNumberUsingBinaryHeap(null, 1); }
@Test(expected = IllegalArgumentException.class) public void testFindNthMaxNumberUsingBinaryHeapLowN() { findNthMaxNumberUsingBinaryHeap(new int[]{2, 1, 3, 4, 0}, 0); }
@Test(expected = IllegalArgumentException.class) public void testFindNthMaxNumberUsingBinaryHeapHighN() { findNthMaxNumberUsingBinaryHeap(new int[]{2, 1, 3, 4, 0}, 6); }
@Test public void testFindNthMaxNumberUsingBinaryHeap1() { int[] sequence = new int[]{2, 1, 3, 4, 0, -1, 7, 5}; assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 1), is(7)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 2), is(5)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 3), is(4)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 4), is(3)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 5), is(2)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 6), is(1)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 7), is(0)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 8), is(-1)); }
@Test public void testFindNthMaxNumberUsingBinaryHeap2() { int[] sequence = new int[]{2, -4, 5, 6, 0, 7, -1, 10, 9}; assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 1), is(10)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 2), is(9)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 3), is(7)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 4), is(6)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 5), is(5)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 6), is(2)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 7), is(0)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 8), is(-1)); assertThat(findNthMaxNumberUsingBinaryHeap(sequence, 9), is(-4)); }
|
### Question:
StringMatchesPatternString { public static boolean matches(String str, String pattern) { if (str == null || pattern == null) { throw new IllegalArgumentException("Tested string either pattern string is null"); } Boolean[][] cache = new Boolean[str.length() + 1][pattern.length() + 1]; return matches(str, pattern, 0, 0, cache); } static boolean matches(String str, String pattern); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testMatchesBothParamsNull() { matches(null, null); }
@Test(expected = IllegalArgumentException.class) public void testMatchesInputStrNull() { matches(null, "abc*a"); }
@Test(expected = IllegalArgumentException.class) public void testMatchesInputPatternNull() { matches("abc12", null); }
@Test public void testMatchesBothParamsEmpty() { assertTrue(matches("", "")); }
@Test public void testMatches1() { assertTrue(matches("", "*")); assertTrue(matches("", "**")); assertTrue(matches("", "***")); assertTrue(matches("a", "*")); assertTrue(matches("ab", "*")); assertTrue(matches("abc", "*")); assertTrue(matches("ab", "**")); assertTrue(matches("abc", "***")); assertTrue(matches("abc", "****")); }
@Test public void testMatches2() { assertFalse(matches("", "*?")); assertTrue(matches("b", "*?")); assertTrue(matches("ba", "*?")); assertTrue(matches("cba", "*?")); }
@Test public void testMatches3() { assertTrue(matches("abc", "a*c")); assertFalse(matches("abc", "a*b")); assertTrue(matches("abcdef", "abc?ef")); assertFalse(matches("abcdefa", "abc?ef")); assertTrue(matches("abcdef", "abc*ef")); assertFalse(matches("abcdefa", "abc*ef")); }
@Test public void testMatches4() { assertTrue(matches("abcbca", "ab*cbca")); assertFalse(matches("abcbca", "ab?cbca")); assertTrue(matches("abcbca", "ab*?b*ca*")); assertTrue(matches("cb", "*?*b")); assertFalse(matches("b", "*?*b")); }
@Test public void testMatches5() { assertTrue(matches("abcbca", "abcbca")); assertTrue(matches("abcbca", "******************************abcbca")); assertTrue(matches("abcbca", "******************************abcbca*")); assertFalse(matches("abcbca", "******************************abcbca?")); assertFalse(matches("abcbca", "abcbcab")); assertFalse(matches("abcbca", "abcbc")); assertTrue(matches("abcbca", "?bcbca")); assertFalse(matches("abcbca", "a?cbcab")); assertFalse(matches("abcbca", "abcb?")); }
|
### Question:
RemoveDuplicatesFromArray { public static int[] removeDuplicates(int[] sequence) { if (sequence == null || sequence.length == 0) { return sequence; } Map<Integer, Integer> unique = new HashMap<>(); int cnt = 0; for (int element : sequence) { Integer pos = unique.get(element); if (pos == null) { unique.put(element, cnt); cnt++; } } if (sequence.length == cnt) { return sequence; } int[] result = new int[cnt]; for (Entry<Integer, Integer> entry : unique.entrySet()) { result[entry.getValue()] = entry.getKey(); } return result; } static int[] removeDuplicates(int[] sequence); }### Answer:
@Test public void testRemoveDuplicates() { assertThat(removeDuplicates(actual), is(expected)); }
|
### Question:
GlassesWithWater { public static double getAmountOfWater(int level, int column, double x) { if (x <= 0) { throw new IllegalArgumentException("Amount of water should be positive"); } if (level < 0) { throw new IllegalArgumentException("Level should be non-negative"); } if (column < 0) { throw new IllegalArgumentException("Column should be non-negative"); } if (level < column) { throw new IllegalArgumentException("Level should be greater or equal to column"); } if (level == 0) { return min(MAX_AMOUNT_OF_WATER_IN_GLASS, x); } else if (level == 1) { return max((x - MAX_AMOUNT_OF_WATER_IN_GLASS) / 2, 0); } double[] prevLevelVolumes = new double[]{ max((x - MAX_AMOUNT_OF_WATER_IN_GLASS) / 2, 0), max((x - MAX_AMOUNT_OF_WATER_IN_GLASS) / 2, 0)}; int i = 1; while (true) { i++; double[] levelVolumes = new double[i + 1]; levelVolumes[0] = max((prevLevelVolumes[0] - 1) / 2, 0); levelVolumes[i] = max((prevLevelVolumes[i - 1] - 1) / 2, 0); for (int j = 1; j < levelVolumes.length - 1; j++) { levelVolumes[j] = max((prevLevelVolumes[j - 1] - MAX_AMOUNT_OF_WATER_IN_GLASS) / 2, 0) + max((prevLevelVolumes[j] - MAX_AMOUNT_OF_WATER_IN_GLASS) / 2, 0); } if (i == level) { return levelVolumes[column]; } prevLevelVolumes = levelVolumes; } } static double getAmountOfWater(int level, int column, double x); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetAmountOfWaterNegativeX() { getAmountOfWater(0, 0, -1); }
@Test(expected = IllegalArgumentException.class) public void testGetAmountOfWaterColumnBiggerThanRow() { getAmountOfWater(0, 1, 2); }
@Test(expected = IllegalArgumentException.class) public void testGetAmountOfWaterLevelNegative() { getAmountOfWater(-1, 1, 2); }
@Test(expected = IllegalArgumentException.class) public void testGetAmountOfWaterColumnNegative() { getAmountOfWater(1, -1, 2); }
@Test public void testGetAmountOfWater1() { assertThat(getAmountOfWater(0, 0, 2), is(1.0)); }
@Test public void testGetAmountOfWater2() { assertThat(getAmountOfWater(1, 0, 2), is(0.5)); }
@Test public void testGetAmountOfWater3() { assertThat(getAmountOfWater(1, 1, 2), is(0.5)); }
@Test public void testGetAmountOfWater4() { assertThat(getAmountOfWater(1, 0, 1), is(0.0)); }
@Test public void testGetAmountOfWater5() { assertThat(getAmountOfWater(2, 0, 2), is(0.0)); }
@Test public void testGetAmountOfWater6() { assertThat(getAmountOfWater(2, 0, 4), is(0.25)); }
@Test public void testGetAmountOfWater7() { assertThat(getAmountOfWater(2, 1, 4), is(0.5)); }
@Test public void testGetAmountOfWater8() { assertThat(getAmountOfWater(2, 2, 4), is(0.25)); }
|
### Question:
BinarySearchTreeResolver { public static boolean isBinarySearchTree(BinaryTree tree) { if (tree == null) { throw new IllegalArgumentException("Input binary tree is null"); } if (tree.left != null) { int lValue = max(tree.left); if (lValue >= tree.value) { return false; } } if (tree.right != null) { int rValue = min(tree.right); if (rValue < tree.value) { return false; } } return true; } static boolean isBinarySearchTree(BinaryTree tree); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testIsBinarySearchTree1() { isBinarySearchTree(null); }
@Test public void testIsBinarySearchTree2() { BinaryTree treeLevel0 = new BinaryTree(null, null, 0); assertThat("This binary tree should be BST", isBinarySearchTree(treeLevel0), is(true)); }
@Test public void testIsBinarySearchTree3() { BinaryTree treeLevel10 = new BinaryTree(null, null, -1); BinaryTree treeLevel11 = new BinaryTree(null, null, 5); BinaryTree treeLevel0 = new BinaryTree(treeLevel10, treeLevel11, 0); assertThat("This binary tree should be BST", isBinarySearchTree(treeLevel0), is(true)); }
@Test public void testIsBinarySearchTree4() { BinaryTree treeLevel20 = new BinaryTree(-10); BinaryTree treeLevel21 = new BinaryTree(3); BinaryTree treeLevel22 = new BinaryTree(12); BinaryTree treeLevel10 = new BinaryTree(treeLevel20, null, -1); BinaryTree treeLevel11 = new BinaryTree(treeLevel21, treeLevel22, 5); BinaryTree treeLevel0 = new BinaryTree(treeLevel10, treeLevel11, 0); assertThat("This binary tree should be BST", isBinarySearchTree(treeLevel0), is(true)); }
@Test public void testIsBinarySearchTree5() { BinaryTree treeLevel20 = new BinaryTree(-10); BinaryTree treeLevel21 = new BinaryTree(3); BinaryTree treeLevel22 = new BinaryTree(12); BinaryTree treeLevel10 = new BinaryTree(treeLevel20, null, 1); BinaryTree treeLevel11 = new BinaryTree(treeLevel21, treeLevel22, 5); BinaryTree treeLevel0 = new BinaryTree(treeLevel10, treeLevel11, 0); assertThat("This binary tree should not be BST", isBinarySearchTree(treeLevel0), is(false)); }
|
### Question:
FrogJumping { public static int findShortestWay(int[] array) { if (array == null || array.length == 0) { throw new IllegalArgumentException("Input array is null or empty"); } int[] jumping = new int[array.length - 1]; for (int i = jumping.length - 1; i >= 0; i--) { if (array[i] < 0) { throw new IllegalArgumentException("Element #" + i + " is negative: " + array[i]); } if (i + array[i] >= jumping.length) { jumping[i] = 1; continue; } jumping[i] = MAX_VALUE; if (array[i] == 0) { continue; } for (int j = 1; j <= array[i] && i + j < jumping.length; j++) { if (jumping[i + j] != MAX_VALUE) { jumping[i] = min(1 + jumping[i + j], jumping[i]); } } } return jumping[0] == MAX_VALUE ? -1 : jumping[0]; } static int findShortestWay(int[] array); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayInputArrayIsNull() { findShortestWay(null); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayInputArrayIsEmpty() { findShortestWay(new int[0]); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayInputArrayWithNegativeElements() { findShortestWay(new int[]{1, 2, 3, 2, 9, -1, 5, 7}); }
@Test public void testFindShortestWay1() { assertThat(findShortestWay(new int[]{1, 5, 4, 6, 9, 3, 0, 0, 1, 3}), is(3)); }
@Test public void testFindShortestWay2() { assertThat(findShortestWay(new int[]{1, 5, 4, 6, 9, 3, 0, 0, 0, 0}), is(3)); }
@Test public void testFindShortestWay3() { assertThat(findShortestWay(new int[]{1, 5, 4, 6, 5, 3, 0, 0, 0, 0}), is(3)); }
@Test public void testFindShortestWay4() { assertThat(findShortestWay(new int[]{0, 5, 4, 6, 9, 3, 0, 0, 1, 3}), is(-1)); }
@Test public void testFindShortestWay5() { assertThat(findShortestWay(new int[]{1, 0, 4, 6, 9, 3, 0, 0, 1, 3}), is(-1)); }
@Test public void testFindShortestWay6() { assertThat(findShortestWay(new int[]{2, 7, 3, 6, 9, 3, 0, 0, 1, 3}), is(3)); }
@Test public void testFindShortestWay7() { assertThat(findShortestWay(new int[]{2, 8, 3, 6, 9, 3, 0, 0, 1, 3}), is(2)); }
@Test public void testFindShortestWay8() { assertThat(findShortestWay(new int[]{2, 7, 7, 6, 9, 3, 0, 0, 1, 3}), is(2)); }
|
### Question:
Bishop { public static int findShortestWay(String start, String end) { if (start == null || !BOARD_CELL_PATTERN.matcher(start).matches()) { throw new IllegalArgumentException("Start position should be 2-char string [a-h][1-8], not " + start); } if (end == null || !BOARD_CELL_PATTERN.matcher(end).matches()) { throw new IllegalArgumentException("End position should be 2-char string [a-h][1-8], not " + end); } int sh = start.charAt(0) - 'a'; int sg = start.charAt(1) - '1'; int eh = end.charAt(0) - 'a'; int eg = end.charAt(1) - '1'; NonDirectedGraph graph = new NonDirectedGraph(BOARD_SIZE * BOARD_SIZE); for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { for (int k = 1; k < BOARD_SIZE; k++) { if (i + k < BOARD_SIZE && j + k < BOARD_SIZE) { graph.addEdge(BOARD_SIZE * i + j, BOARD_SIZE * (i + k) + (j + k)); } if (i + k < BOARD_SIZE && j - k >= 0) { graph.addEdge(BOARD_SIZE * i + j, BOARD_SIZE * (i + k) + (j - k)); } } } } return graph.bfs(sh * BOARD_SIZE + sg, eh * BOARD_SIZE + eg); } static int findShortestWay(String start, String end); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartIsNull() { findShortestWay(null, "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartIsEmpty() { findShortestWay("", "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartTooShort() { findShortestWay("a", "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartTooLong() { findShortestWay("a11", "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndIsNull() { findShortestWay("a1", null); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndIsEmpty() { findShortestWay("a1", ""); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndTooShort() { findShortestWay("a1", "h"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndTooLong() { findShortestWay("a11", "h88"); }
@Test public void testFindShortestWay() { assertThat("Shortest way from " + from + " to " + to + " is not expected", findShortestWay(from, to), is(expected)); }
|
### Question:
StockPrices { public static int findBenefit(int[] prices) { if (prices == null || prices.length < 2) { throw new IllegalArgumentException("Prices cannot be null or with length less than 2"); } int[] min = new int[prices.length]; int[] max = new int[prices.length]; min[0] = prices[0]; max[prices.length - 1] = prices[prices.length - 1]; for (int i = 1; i < prices.length; i++) { min[i] = min(min[i - 1], prices[i]); max[prices.length - 1 - i] = max(max[prices.length - i], prices[prices.length - 1 - i]); } int benefit = MIN_VALUE; for (int i = 1; i < max.length; i++) { benefit = max(benefit, max[i] - min[i - 1]); } return benefit; } static int findBenefit(int[] prices); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindBenefitNullArray() { findBenefit(null); }
@Test(expected = IllegalArgumentException.class) public void testFindBenefitZeroArray() { findBenefit(new int[0]); }
@Test(expected = IllegalArgumentException.class) public void testFindBenefitOneElementArray() { findBenefit(new int[]{1}); }
@Test public void testFindBenefit1() { int actual = findBenefit(new int[]{5, 1, 4, 6, 7, 8, 4, 3, 7, 9}); assertThat(actual, is(8)); }
@Test public void testFindBenefit2() { int actual = findBenefit(new int[]{2, 100, 1, 2}); assertThat(actual, is(98)); }
@Test public void testFindBenefit3() { int actual = findBenefit(new int[]{1, 2, 2, 100}); assertThat(actual, is(99)); }
@Test public void testFindBenefit4() { int actual = findBenefit(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); assertThat(actual, is(9)); }
@Test public void testFindBenefit5() { int actual = findBenefit(new int[]{3, 2, 1}); assertThat(actual, is(-1)); }
|
### Question:
TreeContainsSubtree { public static boolean containsTree(BinaryTree haystack, BinaryTree needle) { if ((haystack == needle) || (needle == null)) { return true; } return subTree(haystack, needle); } static boolean containsTree(BinaryTree haystack, BinaryTree needle); }### Answer:
@Test public void testContainsTree1() { BinaryTree haystack = new BinaryTree(1, new BinaryTree(2, new BinaryTree(3, null, null), null), new BinaryTree(2, new BinaryTree(3, null, null), null)); BinaryTree needle = new BinaryTree(3, null, null); assertThat("Expected result: contains = true", containsTree(haystack, needle), is(true)); }
@Test public void testContainsTree2() { BinaryTree haystack = new BinaryTree(1, new BinaryTree(2, new BinaryTree(3, null, null), null), new BinaryTree(2, new BinaryTree(3, null, null), null)); BinaryTree needle = new BinaryTree(2, null, null); assertThat("Expected result: contains = false", containsTree(haystack, needle), is(false)); }
@Test public void testContainsTree3() { BinaryTree haystack = new BinaryTree(1, new BinaryTree(2, new BinaryTree(3, null, null), new BinaryTree(4, null, null)), new BinaryTree(2, new BinaryTree(3, null, null), null)); BinaryTree needle = new BinaryTree(4, null, null); assertThat("Expected result: contains = true", containsTree(haystack, needle), is(true)); }
@Test public void testContainsTree4() { BinaryTree haystack = new BinaryTree(1, new BinaryTree(2, new BinaryTree(3, null, null), new BinaryTree(4, null, null)), new BinaryTree(2, new BinaryTree(3, null, null), null)); BinaryTree needle = new BinaryTree(4, null, new BinaryTree(5, null, null)); assertThat("Expected result: contains = false", containsTree(haystack, needle), is(false)); }
|
### Question:
AbsoluteDifferenceInTwoSortedArrays { public static Triple findMinimumDifference(int[] first, int[] second) { if (first == null || first.length == 0) { throw new IllegalArgumentException("First array is null or empty"); } if (second == null || second.length == 0) { throw new IllegalArgumentException("Second array is null or empty"); } if (first.length != second.length) { throw new IllegalArgumentException("Arrays have different sizes"); } int diff = Integer.MAX_VALUE; int i = 0; int j = 0; int posInFirst = 0; int posInSecond = 0; while (i < first.length && j < second.length) { if (diff > Math.abs(first[i] - second[j])) { diff = Math.abs(first[i] - second[j]); posInFirst = i; posInSecond = j; } if (first[i] <= second[j]) { i++; } else { j++; } } return new Triple(diff, posInFirst, posInSecond); } static Triple findMinimumDifference(int[] first, int[] second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindMinimumDifferenceFirstIsNull() { findMinimumDifference(null, new int[]{1, 2, 3}); }
@Test(expected = IllegalArgumentException.class) public void testFindMinimumDifferenceSecondIsNull() { findMinimumDifference(new int[]{1, 2, 3}, null); }
@Test(expected = IllegalArgumentException.class) public void testFindMinimumDifferenceBothAreNull() { findMinimumDifference(null, null); }
@Test(expected = IllegalArgumentException.class) public void testFindMinimumDifferenceDifferentLength() { findMinimumDifference(new int[]{1, 2, 3, 4}, new int[]{2, 4, 5}); }
@Test public void testFindMinimumDifference1() { Triple res = findMinimumDifference(new int[]{1}, new int[]{2}); assertThat(res, is(new Triple(1, 0, 0))); }
@Test public void testFindMinimumDifference2() { Triple res = findMinimumDifference(new int[]{1, 2}, new int[]{2, 3}); assertThat(res, is(new Triple(0, 1, 0))); }
@Test public void testFindMinimumDifference3() { Triple res = findMinimumDifference(new int[]{1, 5, 10, 17}, new int[]{18, 19, 25, 27}); assertThat(res, is(new Triple(1, 3, 0))); }
@Test public void testFindMinimumDifference4() { Triple res = findMinimumDifference(new int[]{1, 2, 3, 4}, new int[]{2, 4, 5, 7}); assertThat(res, is(new Triple(0, 1, 0))); }
|
### Question:
LongestConsecutiveNumbers { public static int[] findLongestConsecutiveNumbers(int[] sequence) { if (sequence == null || sequence.length == 0) { throw new IllegalArgumentException("Input sequence is null or empty"); } Arrays.sort(sequence); int longest = 0; int i = 0; int start = -1; int end = -1; while (i < sequence.length) { int pos = i; while (pos < sequence.length && pos - i == sequence[pos] - sequence[i]) { pos++; } if (pos - i >= longest) { start = i; end = pos; longest = pos - i; } i = pos; } return Arrays.copyOfRange(sequence, start, end); } static int[] findLongestConsecutiveNumbers(int[] sequence); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindLongestConsecutiveNumbersNullArray() { assertNull(findLongestConsecutiveNumbers(null)); }
@Test(expected = IllegalArgumentException.class) public void testFindLongestConsecutiveNumbersEmptyArray() { assertNull(findLongestConsecutiveNumbers(new int[0])); }
@Test public void testFindLongestConsecutiveNumbersOneElementArray() { assertThat(findLongestConsecutiveNumbers(new int[]{5}), is(new int[]{5})); }
@Test public void testFindLongestConsecutiveNumbers1() { assertThat(findLongestConsecutiveNumbers(new int[]{10, 1}), is(new int[]{10})); }
@Test public void testFindLongestConsecutiveNumbers2() { assertThat(findLongestConsecutiveNumbers(new int[]{10, 9}), is(new int[]{9, 10})); }
@Test public void testFindLongestConsecutiveNumbers3() { assertThat(findLongestConsecutiveNumbers(new int[]{10, 8, 9}), is(new int[]{8, 9, 10})); }
@Test public void testFindLongestConsecutiveNumbers4() { assertThat(findLongestConsecutiveNumbers(new int[]{8, 2, 3, 7, 4, 0}), is(new int[]{2, 3, 4})); }
@Test public void testFindLongestConsecutiveNumbers5() { assertThat(findLongestConsecutiveNumbers(new int[]{2, 4, 7, 9, 8, 4}), is(new int[]{7, 8, 9})); }
@Test public void testFindLongestConsecutiveNumbers6() { assertThat(findLongestConsecutiveNumbers(new int[]{0, 1, 5, 2, 5}), is(new int[]{0, 1, 2})); }
@Test public void testFindLongestConsecutiveNumbers7() { assertThat(findLongestConsecutiveNumbers(new int[]{10, 8, 6, 4, 2}), is(new int[]{10})); }
@Test public void testFindLongestConsecutiveNumbers8() { assertThat(findLongestConsecutiveNumbers(new int[]{100, 99, 97, 201, 200, 1}), is(new int[]{200, 201})); }
|
### Question:
BSTFromInOrderAndPreOrder { public static BinarySearchTree constructTree(int[] inOrder, int[] preOrder) { if (inOrder == null || inOrder.length == 0) { throw new IllegalArgumentException("InOrder array cannot be null or empty"); } if (preOrder == null || preOrder.length == 0) { throw new IllegalArgumentException("PreOrder array cannot be null or empty"); } if (inOrder.length != preOrder.length) { throw new IllegalArgumentException("InOrder and PreOrder arrays have different sizes"); } return constructTree(inOrder, 0, inOrder.length, preOrder, 0, preOrder.length); } static BinarySearchTree constructTree(int[] inOrder, int[] preOrder); }### Answer:
@Test public void testConstructTree1() { int[] inOrder = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] preOrder = new int[]{3, 2, 1, 7, 4, 6, 5, 8, 9}; BinarySearchTree tree = BSTFromInOrderAndPreOrder.constructTree(inOrder, preOrder); assertThat("PreOrder check failed", tree.preOrderTraverse().toArray(), is(new Object[]{3, 2, 1, 7, 4, 6, 5, 8, 9})); assertThat("InOrder check failed", tree.inOrderTraverse().toArray(), is(new Object[]{1, 2, 3, 4, 5, 6, 7, 8, 9})); assertThat("PostOrder check failed", tree.postOrderTraverse().toArray(), is(new Object[]{1, 2, 5, 6, 4, 9, 8, 7, 3})); }
@Test public void testConstructTree2() { int[] inOrder = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; int[] preOrder = new int[]{9, 3, 1, 2, 7, 5, 4, 6, 8}; BinarySearchTree tree = BSTFromInOrderAndPreOrder.constructTree(inOrder, preOrder); assertThat("PreOrder check failed", tree.preOrderTraverse().toArray(), is(new Object[]{9, 3, 1, 2, 7, 5, 4, 6, 8})); assertThat("InOrder check failed", tree.inOrderTraverse().toArray(), is(new Object[]{1, 2, 3, 4, 5, 6, 7, 8, 9})); assertThat("PostOrder check failed", tree.postOrderTraverse().toArray(), is(new Object[]{2, 1, 4, 6, 5, 8, 7, 3, 9})); }
|
### Question:
StackWithQuickMinOperation { public Integer peekMin() { return minStack.peekFirst(); } StackWithQuickMinOperation(); void push(Integer value); Integer pop(); Integer peek(); Integer peekMin(); int size(); }### Answer:
@Test public void testPeekMin() { StackWithQuickMinOperation stack = new StackWithQuickMinOperation(); stack.push(10); assertThat(stack.peekMin(), is(10)); stack.push(11); assertThat(stack.peekMin(), is(10)); stack.push(12); assertThat(stack.peekMin(), is(10)); stack.push(9); assertThat(stack.peekMin(), is(9)); stack.push(8); assertThat(stack.peekMin(), is(8)); stack.push(15); assertThat(stack.peekMin(), is(8)); stack.push(1); stack.push(2); assertThat(stack.peekMin(), is(1)); }
|
### Question:
Trie { public boolean insertWord(String s) { if (s == null) { throw new IllegalArgumentException("Input string is null"); } TrieNode node = parent; for (int i = 0; i < s.length(); i++) { node = node.getChild(s.charAt(i)); } if (node.endOfWord) { return false; } node.endOfWord = true; size++; return true; } Trie(); boolean insertWord(String s); boolean containsWord(String s); boolean containsAsPrefix(String s); boolean containsPrefixOf(String s); int getSize(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testInsertWordWithNull() { Trie trie = new Trie(); trie.insertWord(null); }
@Test(expected = IllegalArgumentException.class) public void testInsertWordIncorrectChar1() { Trie trie = new Trie(); trie.insertWord("cash$"); }
@Test(expected = IllegalArgumentException.class) public void testInsertWordIncorrectChar2() { Trie trie = new Trie(); trie.insertWord("Two words"); }
@Test(expected = IllegalArgumentException.class) public void testInsertWordIncorrectChar3() { Trie trie = new Trie(); trie.insertWord("Two,words"); }
@Test(expected = IllegalArgumentException.class) public void testInsertWordIncorrectChar4() { Trie trie = new Trie(); trie.insertWord("I am a sentence"); }
@Test public void testInsertWordWithEmpty() { Trie trie = new Trie(); assertTrue("First insertion of empty string to Trie should return true", trie.insertWord("")); }
@Test public void testInsertWordEmptyTwice() { Trie trie = new Trie(); assertTrue("First insertion of empty string to Trie should return true", trie.insertWord("")); assertFalse("Second insertion of empty string to empty Trie should return false", trie.insertWord("")); }
@Test public void testInsertWordUniqueArray() { Trie trie = new Trie(); String[] sequence = new String[]{"a", "", "stv", "aa", "bb", "b", "a9", "aA9"}; for (String element : sequence) { assertTrue("Insertion should be ok", trie.insertWord(element)); } }
|
### Question:
Trie { public int getSize() { return size; } Trie(); boolean insertWord(String s); boolean containsWord(String s); boolean containsAsPrefix(String s); boolean containsPrefixOf(String s); int getSize(); }### Answer:
@Test public void testGetSizeEmptyTrie() { Trie trie = new Trie(); assertThat(trie.getSize(), is(0)); }
|
### Question:
Knight { public static int findShortestWay(String start, String end) { if (start == null || !BOARD_CELL_PATTERN.matcher(start).matches()) { throw new IllegalArgumentException("Start position should be 2-char string [a-h][1-8], not " + start); } if (end == null || !BOARD_CELL_PATTERN.matcher(end).matches()) { throw new IllegalArgumentException("End position should be 2-char string [a-h][1-8], not " + end); } int sh = start.charAt(0) - 'a'; int sg = start.charAt(1) - '1'; int eh = end.charAt(0) - 'a'; int eg = end.charAt(1) - '1'; NonDirectedGraph graph = new NonDirectedGraph(BOARD_SIZE * BOARD_SIZE); for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { if (i - 2 >= 0 && j - 1 >= 0) { graph.addEdge(BOARD_SIZE * (i - 2) + (j - 1), BOARD_SIZE * i + j); } if (i - 2 >= 0 && j + 1 < BOARD_SIZE) { graph.addEdge(BOARD_SIZE * (i - 2) + (j + 1), BOARD_SIZE * i + j); } if (i - 1 >= 0 && j - 2 >= 0) { graph.addEdge(BOARD_SIZE * (i - 1) + (j - 2), BOARD_SIZE * i + j); } if (i - 1 >= 0 && j + 2 < BOARD_SIZE) { graph.addEdge(BOARD_SIZE * (i - 1) + (j + 2), BOARD_SIZE * i + j); } } } return graph.bfs(sh * BOARD_SIZE + sg, eh * BOARD_SIZE + eg); } static int findShortestWay(String start, String end); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartIsNull() { findShortestWay(null, "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartIsEmpty() { findShortestWay("", "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartTooShort() { findShortestWay("a", "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayStartTooLong() { findShortestWay("a11", "h8"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndIsNull() { findShortestWay("a1", null); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndIsEmpty() { findShortestWay("a1", ""); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndTooShort() { findShortestWay("a1", "h"); }
@Test(expected = IllegalArgumentException.class) public void testFindShortestWayEndTooLong() { findShortestWay("a11", "h88"); }
@Test public void testFindShortestWay() { assertThat("Shortest way from " + from + " to " + to + " is not expected", findShortestWay(from, to), is(expected)); }
|
### Question:
DictionaryWordsInTiles { public static String[] findDictionaryWords(String tiles, String[] dictionary) { if (tiles == null || tiles.isEmpty() || dictionary == null || dictionary.length == 0) { return new String[0]; } Map<Character, Integer> tilesMap = new HashMap<>(); for (int i = 0; i < tiles.length(); i++) { Integer cnt = tilesMap.get(tiles.charAt(i)); if (cnt == null) { cnt = 0; } tilesMap.put(tiles.charAt(i), cnt + 1); } List<String> correctWords = new ArrayList<>(); for (String word : dictionary) { boolean accepted = true; Map<Character, Integer> words = new HashMap<>(); for (int j = 0; j < word.length(); j++) { Integer cnt = tilesMap.get(word.charAt(j)); if (cnt == null) { accepted = false; break; } Integer cntInDictionary = words.get(word.charAt(j)); if (cntInDictionary == null) { cntInDictionary = 0; } cntInDictionary++; if (cntInDictionary > cnt) { accepted = false; break; } words.put(word.charAt(j), cntInDictionary); } if (accepted) { correctWords.add(word); } } return correctWords.toArray(new String[correctWords.size()]); } static String[] findDictionaryWords(String tiles, String[] dictionary); }### Answer:
@Test public void testFindDictionaryWords() { String[] acceptedWords = findDictionaryWords(tiles, dictionary); sort(acceptedWords); assertThat("Result does not match for tiles = " + tiles + " and dictionary = " + Arrays.toString(dictionary), acceptedWords, is(expected)); }
|
### Question:
MultithreadedSumCalculation { public static long getSum(final long[] array, int nThreads) { if (array == null) { throw new IllegalArgumentException("Input array should be not null"); } if (nThreads <= 0) { throw new IllegalArgumentException("Number of threads should be positive"); } if (array.length == 0) { return 0; } else if (array.length == 1) { return array[0]; } nThreads = min(nThreads, array.length); final ExecutorService executor = Executors.newFixedThreadPool(nThreads); int step = array.length / nThreads; if (array.length % nThreads > 0) { step++; } Future<Long>[] futures = new Future[nThreads]; for (int i = 0; i < nThreads; i++) { int fromInclusive = i * step; int toExclusive = min(fromInclusive + step, array.length); futures[i] = executor.submit(() -> calculate(array, fromInclusive, toExclusive)); } executor.shutdown(); long totalSum = 0; for (int i = 0; i < nThreads; i++) { try { totalSum += futures[i].get(); } catch (ExecutionException ex) { Throwable t = ex.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw (Error) t; } } catch (InterruptedException ignored) { throw new RuntimeException("Execution was interrupted"); } } return totalSum; } static long getSum(final long[] array, int nThreads); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetSumNullArray() { getSum(null, 5); }
@Test(expected = IllegalArgumentException.class) public void testGetSumNonPositiveThreads() { getSum(new long[]{1, 2}, 0); }
@Test public void testGetSum() { assertThat(getSum(new long[0], 5), is(0L)); assertThat(getSum(new long[]{2}, 5), is(2L)); assertThat(getSum(new long[]{2, 3, 5}, 100), is(10L)); long[] array = new long[1000]; for (int i = 0; i < array.length; i++) { array[i] = i; } for (int i = 1; i <= 100; i++) { assertThat(getSum(array, i), is(499500L)); } }
|
### Question:
LRUCache extends LinkedHashMap<K, V> { public int getMaxSize() { return maxSize; } LRUCache(int maxSize); int getMaxSize(); }### Answer:
@Test public void testLRUCachePut() { LRUCache<String, Integer> cache = new LRUCache<String, Integer>(5); assertThat(cache.getMaxSize(), is(5)); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.put("4", 4); cache.put("5", 5); assertThat(cache.size(), is(5)); cache.put("6", 6); assertThat(cache.size(), is(5)); assertNull(cache.get("1")); assertThat(cache.getMaxSize(), is(5)); }
@Test public void testLRUCachePutGet() { LRUCache<String, Integer> cache = new LRUCache<String, Integer>(5); assertThat(cache.getMaxSize(), is(5)); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.put("4", 4); cache.put("5", 5); assertThat(cache.size(), is(5)); assertThat(cache.get("1"), is(1)); cache.put("6", 6); assertThat(cache.size(), is(5)); assertNull(cache.get("2")); assertThat(cache.get("1"), is(1)); assertThat(cache.getMaxSize(), is(5)); }
@Test public void testLRUCachePutGet2() { LRUCache<String, Integer> cache = new LRUCache<String, Integer>(5); assertThat(cache.getMaxSize(), is(5)); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.put("4", 4); cache.put("5", 5); assertThat(cache.size(), is(5)); assertThat(cache.get("2"), is(2)); assertThat(cache.get("1"), is(1)); cache.put("6", 6); assertThat(cache.size(), is(5)); assertNull(cache.get("3")); assertThat(cache.get("2"), is(2)); assertThat(cache.get("1"), is(1)); assertThat(cache.getMaxSize(), is(5)); }
@Test public void testLRUCachePutGet3() { LRUCache<String, Integer> cache = new LRUCache<String, Integer>(5); assertThat(cache.getMaxSize(), is(5)); cache.put("1", 1); cache.put("2", 2); cache.put("3", 3); cache.put("4", 4); cache.put("5", 5); assertThat(cache.size(), is(5)); cache.put("6", 6); cache.put("7", 7); cache.put("8", 8); cache.put("9", 9); cache.put("10", 10); assertNull(cache.get("1")); assertNull(cache.get("2")); assertNull(cache.get("3")); assertNull(cache.get("4")); assertNull(cache.get("5")); cache.remove("10"); assertThat(cache.size(), is(4)); assertThat(cache.getMaxSize(), is(5)); }
@Test public void testLRUCachePutGet4() { LRUCache<String, Integer> cache = new LRUCache<String, Integer>(1); assertThat(cache.size(), is(0)); cache.put("1", 1); assertThat(cache.get("1"), is(1)); cache.put("2", 2); assertThat(cache.size(), is(1)); assertNull(cache.get("1")); assertThat(cache.get("2"), is(2)); assertThat(cache.getMaxSize(), is(1)); }
|
### Question:
SimpleSpinlock { public V executeWithSpinLock(Callable<V> e) throws Exception { while (true) { while (alreadyLocked()) { } if (!lock()) { continue; } try { return e.call(); } finally { unlock(); } } } V executeWithSpinLock(Callable<V> e); }### Answer:
@Test public void testExecuteWithSpinlockReturnLong() throws Exception { final int THREAD_COUNT = 10; final AtomicInteger cnt = new AtomicInteger(); final ExecutorService executor = Executors .newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executor.submit(new Callable<Long>() { public Long call() throws Exception { long res = simpleSpinlock .executeWithSpinLock(new CallableWithLong()); assertThat("Result is not matched", res, is(0L)); cnt.incrementAndGet(); return res; } }); } executor.shutdown(); executor.awaitTermination(THREAD_COUNT, TimeUnit.SECONDS); assertThat("Only " + cnt.get() + " internal threads were executed", cnt.get(), is(THREAD_COUNT)); }
@Test public void testExecuteWithSpinlockThrowsException() throws Exception { final int THREAD_COUNT = 10; final AtomicInteger cnt = new AtomicInteger(); final ExecutorService executor = Executors .newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executor.submit(new Callable<Long>() { public Long call() throws Exception { try { simpleSpinlock .executeWithSpinLock(new CallableWithException()); fail("Exception should be thrown in CallableWithException.call() invocation"); } catch (Exception ex) { } cnt.incrementAndGet(); return 0L; } }); } executor.shutdown(); executor.awaitTermination(THREAD_COUNT, TimeUnit.SECONDS); assertThat("Only " + cnt.get() + " internal threads were executed", cnt.get(), is(THREAD_COUNT)); }
|
### Question:
ObjectSizeCalculator { public static long sizeOf(Object o) throws IllegalAccessException { return sizeOf(o, CURRENT_JVM_64_BIT); } static long sizeOf(Object o); static long sizeOf(Object o, boolean jvm64bit); }### Answer:
@Test public void testSizeOf() throws IllegalAccessException { long size64bit = sizeOf(object, true); assertThat("SizeOf for " + tcName + " and 64-bit JVM does not match", size64bit, is(result64bit)); long size32bit = sizeOf(object, false); assertThat("SizeOf for " + tcName + " and 32-bit JVM does not match", size32bit, is(result32bit)); }
|
### Question:
UnionFind { public int find(int i) { if (i < 0 || i >= n) { throw new IllegalArgumentException("Input element " + "should be between 0 (inclusive) " + "and " + n + " (exclusive)"); } while (i != roots[i]) { roots[i] = roots[roots[i]]; i = roots[i]; } return i; } UnionFind(int n); int find(int i); int union(int i, int j); int getSubsetSize(int i); int getSubsetsCount(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindIllegalArgument1() { UnionFind unionFind = new UnionFind(5); unionFind.find(-1); }
@Test(expected = IllegalArgumentException.class) public void testFindIllegalArgument2() { UnionFind unionFind = new UnionFind(5); unionFind.find(5); }
|
### Question:
UnionFind { public int union(int i, int j) { int firstRoot = find(i); int secondRoot = find(j); if (firstRoot == secondRoot) { return firstRoot; } if (ranks[firstRoot] < ranks[secondRoot]) { roots[firstRoot] = secondRoot; sizes[secondRoot] += sizes[firstRoot]; } else if (ranks[firstRoot] > ranks[secondRoot]) { roots[secondRoot] = firstRoot; sizes[firstRoot] += sizes[secondRoot]; } else { roots[firstRoot] = secondRoot; sizes[secondRoot] += sizes[firstRoot]; ranks[secondRoot]++; } subsetsCount--; return roots[firstRoot]; } UnionFind(int n); int find(int i); int union(int i, int j); int getSubsetSize(int i); int getSubsetsCount(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testUnionIllegalArgument1() { UnionFind unionFind = new UnionFind(5); unionFind.union(0, -1); }
@Test(expected = IllegalArgumentException.class) public void testUnionIllegalArgument2() { UnionFind unionFind = new UnionFind(5); unionFind.union(1, 5); }
|
### Question:
UnionFind { public int getSubsetSize(int i) { return sizes[find(i)]; } UnionFind(int n); int find(int i); int union(int i, int j); int getSubsetSize(int i); int getSubsetsCount(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSubsetSizeIllegalArgument1() { UnionFind unionFind = new UnionFind(5); unionFind.getSubsetSize(-1); }
@Test(expected = IllegalArgumentException.class) public void testSubsetSizeIllegalArgument2() { UnionFind unionFind = new UnionFind(5); unionFind.getSubsetSize(5); }
|
### Question:
NumberUtils { public static List<long[]> findFactoring(long b) { List<long[]> divs = new ArrayList<>(); if (BigInteger.valueOf(b).isProbablePrime(100)) { divs.add(new long[]{b, 1}); return divs; } for (long i = 2; i <= b; i++) { if (b % i == 0) { int deg = 0; while (b % i == 0) { deg++; b /= i; } divs.add(new long[]{i, deg}); if (BigInteger.valueOf(b).isProbablePrime(100)) { divs.add(new long[]{b, 1}); return divs; } } } return divs; } static List<long[]> findFactoring(long b); }### Answer:
@Test public void testFindFactoring() { List<long[]> factoring = findFactoring(value); assertEquals(expected.size(), factoring.size()); for (int i = 0; i < factoring.size(); i++) { assertArrayEquals(expected.get(i), factoring.get(i)); } }
|
### Question:
BasicEditDistance { public static double getEditDistance(CharSequence s, CharSequence t) { return getEditDistance(s, t, DEFAULT_OPERATIONS_WEIGHTS); } private BasicEditDistance(); static double getEditDistance(CharSequence s, CharSequence t); static double getEditDistance(CharSequence s,
CharSequence t,
OperationsWeights operationsWeights); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetEditDistanceFirstIsNull() { getEditDistance(null, "abc"); }
@Test(expected = IllegalArgumentException.class) public void testGetEditDistanceSecondIsNull() { getEditDistance("abc", null); }
@Test public void testGetEditDistance1() { CharSequence s = "abc"; CharSequence t = ""; assertEquals(3.0, getEditDistance(s, t), EPSILON); assertEquals(3.0, getEditDistance(t, s), EPSILON); }
@Test public void testGetEditDistance2() { CharSequence s = "abc"; CharSequence t = "b"; assertEquals(2.0, getEditDistance(s, t), EPSILON); assertEquals(2.0, getEditDistance(t, s), EPSILON); }
@Test public void testGetEditDistance3() { CharSequence s = "abc"; CharSequence t = "abc"; assertEquals(0.0, getEditDistance(s, t), EPSILON); assertEquals(0.0, getEditDistance(t, s), EPSILON); }
@Test public void testGetEditDistance4() { CharSequence s = "abc"; CharSequence t = "dce"; assertEquals(3.0, getEditDistance(s, t), EPSILON); assertEquals(3.0, getEditDistance(t, s), EPSILON); }
@Test public void testGetEditDistance5() { CharSequence s = "abc"; CharSequence t = "dec"; assertEquals(2.0, getEditDistance(s, t), EPSILON); assertEquals(2.0, getEditDistance(t, s), EPSILON); }
@Test public void testGetEditDistance6() { CharSequence s = "abc"; CharSequence t = "dce"; assertEquals(3.5, getEditDistance(s, t, hugeSubstitutionOperationsWeights), EPSILON); assertEquals(3.5, getEditDistance(t, s, hugeSubstitutionOperationsWeights), EPSILON); }
@Test public void testGetEditDistance7() { CharSequence s = "abcdefg"; CharSequence t = "xbcdefg"; assertEquals(1.5, getEditDistance(s, t, hugeSubstitutionOperationsWeights), EPSILON); assertEquals(1.5, getEditDistance(t, s, hugeSubstitutionOperationsWeights), EPSILON); }
@Test public void testGetEditDistance8() { CharSequence s = "abcdefg"; CharSequence t = "xbcdeg"; assertEquals(2.5, getEditDistance(s, t, hugeSubstitutionOperationsWeights), EPSILON); assertEquals(2.5, getEditDistance(t, s, hugeSubstitutionOperationsWeights), EPSILON); }
|
### Question:
SequenceOfDivisibleNumbers { public static BigInteger getNthNumber(int n) { if (n <= 0) { throw new IllegalArgumentException("Input parameter should be positive"); } TreeSet<BigInteger> set = new TreeSet<>(); set.add(ONE); BigInteger nthNumber = ONE; while (n > 0) { nthNumber = set.ceiling(nthNumber); set.remove(nthNumber); set.add(nthNumber.multiply(TWO)); set.add(nthNumber.multiply(THREE)); set.add(nthNumber.multiply(FIVE)); n--; } return nthNumber; } static BigInteger getNthNumber(int n); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetNthNumberNegativeInput() { getNthNumber(-1); }
@Test(expected = IllegalArgumentException.class) public void testGetNthNumberZeroInput() { getNthNumber(0); }
@Test public void testGetNthNumberWithOne() { assertThat(getNthNumber(1), is(ONE)); }
@Test public void testGetNthNumberWithTwo() { assertThat(getNthNumber(2), is(valueOf(2))); }
@Test public void testGetNthNumberWithThree() { assertThat(getNthNumber(3), is(valueOf(3))); }
@Test public void testGetNthNumberWithFour() { assertThat(getNthNumber(4), is(valueOf(4))); }
@Test public void testGetNthNumberWithFive() { assertThat(getNthNumber(5), is(valueOf(5))); }
@Test public void testGetNthNumberWithSix() { assertThat(getNthNumber(6), is(valueOf(6))); }
@Test public void testGetNthNumberWithSeven() { assertThat(getNthNumber(7), is(valueOf(8))); }
@Test public void testGetNthNumberWithEight() { assertThat(getNthNumber(8), is(valueOf(9))); }
@Test public void testGetNthNumberWithNine() { assertThat(getNthNumber(9), is(valueOf(10))); }
@Test public void testGetNthNumberWithTen() { assertThat(getNthNumber(10), is(valueOf(12))); }
@Test public void testGetNthNumberWithEleven() { assertThat(getNthNumber(11), is(valueOf(15))); }
@Test public void testGetNthNumberWithTwelve() { assertThat(getNthNumber(12), is(valueOf(16))); }
@Test public void testGetNthNumberWithThirteen() { assertThat(getNthNumber(13), is(valueOf(18))); }
@Test public void testGetNthNumberWithFourteen() { assertThat(getNthNumber(14), is(valueOf(20))); }
@Test public void testGetNthNumberWithFifteen() { assertThat(getNthNumber(15), is(valueOf(24))); }
|
### Question:
GraphAlgorithms { public static UndirectedGraph getMinimumSpanningTree(UndirectedGraph graph) { if (graph == null) { throw new IllegalArgumentException("Input graph should be not null"); } List<Edge> edges = new ArrayList<>(graph.getEdgeCount()); for (int i = 0; i < graph.getVertexCount(); i++) { Iterator<Edge> edgesIterator = graph.getEdgesForVertex(i); while (edgesIterator.hasNext()) { Edge edge = edgesIterator.next(); if (edge.getHead() < i) { edges.add(edge); } } } Collections.sort(edges, (Edge e1, Edge e2) -> e1.getWeight() > e2.getWeight() ? 1 : e1.getWeight() < e2.getWeight() ? -1 : 0); UnionFind unionFind = new UnionFind(graph.getVertexCount()); UndirectedGraph minimumSpanningTree = new UndirectedGraph(graph.getVertexCount()); for (Edge edge : edges) { if (unionFind.find(edge.getTail()) == unionFind.find(edge.getHead())) { continue; } unionFind.union(edge.getTail(), edge.getHead()); minimumSpanningTree.addEdge(edge); } return minimumSpanningTree; } private GraphAlgorithms(); static ClusteringResult getClusteringComponents(UndirectedGraph graph,
int k); static UndirectedGraph getMinimumSpanningTree(UndirectedGraph graph); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSpanningTreeNullGraph() { getMinimumSpanningTree(null); }
@Test public void testGetMinimumSpanningTree1() { UndirectedGraph graph = new UndirectedGraph(3); graph.addEdge(new Edge(0, 1, 1)); graph.addEdge(new Edge(1, 2, 1)); graph.addEdge(new Edge(2, 0, 1)); UndirectedGraph minimumSpanningTree = GraphAlgorithms.getMinimumSpanningTree(graph); assertEquals(3, minimumSpanningTree.getVertexCount()); assertEquals(2, minimumSpanningTree.getEdgeCount()); double weight = 0; for (int i = 0; i < minimumSpanningTree.getVertexCount(); i++) { Iterator<Edge> edgesIterator = minimumSpanningTree.getEdgesForVertex(i); while (edgesIterator.hasNext()) { Edge edge = edgesIterator.next(); if (edge.getHead() < i) { weight += edge.getWeight(); } } } assertEquals(2, weight, EPSILON); }
@Test public void testGetMinimumSpanningTree2() { UndirectedGraph graph = new UndirectedGraph(3); graph.addEdge(new Edge(0, 1, 1)); graph.addEdge(new Edge(1, 2, 3)); graph.addEdge(new Edge(2, 0, 3)); UndirectedGraph minimumSpanningTree = GraphAlgorithms.getMinimumSpanningTree(graph); assertEquals(3, minimumSpanningTree.getVertexCount()); assertEquals(2, minimumSpanningTree.getEdgeCount()); double weight = 0; for (int i = 0; i < minimumSpanningTree.getVertexCount(); i++) { Iterator<Edge> edgesIterator = minimumSpanningTree.getEdgesForVertex(i); while (edgesIterator.hasNext()) { Edge edge = edgesIterator.next(); if (edge.getHead() < i) { weight += edge.getWeight(); } } } assertEquals(4, weight, EPSILON); }
|
### Question:
SegmentTreeMin { public void addValue(int left, int right, int value) { if (left < 0 || right > size) { throw new IllegalArgumentException( "Input left and round bounds should be between zero and segment tree size"); } if (right <= left) { throw new IllegalArgumentException( "Input right bound should be greater than left bound"); } addValue(left, right, value, 0, 0, size); } SegmentTreeMin(int size); void addValue(int left, int right, int value); long getMinimum(int left, int right); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSegmentTreeMinIncorrectBounds1() { SegmentTreeMin tree = new SegmentTreeMin(100); tree.addValue(-1, 10, 100); }
@Test(expected = IllegalArgumentException.class) public void testSegmentTreeMinIncorrectBounds2() { SegmentTreeMin tree = new SegmentTreeMin(100); tree.addValue(1, 101, 10); }
@Test(expected = IllegalArgumentException.class) public void testSegmentTreeMinIncorrectBounds3() { SegmentTreeMin tree = new SegmentTreeMin(100); tree.addValue(10, 10, 101); }
|
### Question:
SegmentTreeSum { public void addValue(int left, int right, long value) { if (left < 0 || right > size) { throw new IllegalArgumentException( "Input left and round bounds should be between zero and segment tree size"); } if (right <= left) { throw new IllegalArgumentException( "Input right bound should be greater than left bound"); } addValue(left, right, value, 0, 0, size); } SegmentTreeSum(int size); void addValue(int left, int right, long value); long getSum(int left, int right); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testSegmentTreeSumIncorrectBounds1() { SegmentTreeSum tree = new SegmentTreeSum(100); tree.addValue(-1, 10, 100); }
@Test(expected = IllegalArgumentException.class) public void testSegmentTreeSumIncorrectBounds2() { SegmentTreeSum tree = new SegmentTreeSum(100); tree.addValue(1, 101, 10); }
@Test(expected = IllegalArgumentException.class) public void testSegmentTreeSumIncorrectBounds3() { SegmentTreeSum tree = new SegmentTreeSum(100); tree.addValue(10, 10, 101); }
|
### Question:
ThreeArraysInAscendingOrder { public static int getMinimumSum(int[] a, int[] b, int[] c) { if ((a == null) || (a.length == 0)) { throw new IllegalArgumentException("First array is null or empty"); } if ((b == null) || (b.length == 0)) { throw new IllegalArgumentException("Second array is null or empty"); } if ((c == null) || (c.length == 0)) { throw new IllegalArgumentException("Third array is null or empty"); } int sum = Integer.MAX_VALUE; int i = 0; int j = 0; int k = 0; while ((i < a.length) && (j < b.length) && (k < c.length)) { int s = Math.abs(a[i] - b[j]) + Math.abs(b[j] - c[k]) + Math.abs(c[k] - a[i]); if (s < sum) { sum = s; } if ((a[i] <= b[j]) && (a[i] <= c[k])) { i++; } else if ((b[j] <= a[i]) && (b[j] <= c[k])) { j++; } else if ((c[k] <= a[i]) && (c[k] <= b[j])) { k++; } } return sum; } static int getMinimumSum(int[] a, int[] b, int[] c); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSumFirstArrayIsNull() { getMinimumSum(null, new int[] { 1 }, new int[] { 2 }); }
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSumFirstArrayIsEmpty() { getMinimumSum(new int[0], new int[] { 1 }, new int[] { 2 }); }
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSumSecondArrayIsNull() { getMinimumSum(new int[] { 1 }, null, new int[] { 2 }); }
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSumSecondArrayIsEmpty() { getMinimumSum(new int[] { 1 }, new int[0], new int[] { 2 }); }
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSumThirdArrayIsNull() { getMinimumSum(new int[] { 1 }, new int[] { 2 }, null); }
@Test(expected = IllegalArgumentException.class) public void testGetMinimumSumThirdArrayIsEmpty() { getMinimumSum(new int[] { 1 }, new int[] { 2 }, new int[0]); }
@Test public void testGetMinimumSum1() { int[] first = new int[] { 1, 2, 5 }; int[] second = new int[] { 0, 2, 7 }; int[] third = new int[] { 1, 3, 5 }; assertThat(getMinimumSum(first, second, third), is(2)); }
@Test public void testGetMinimumSum2() { int[] first = new int[] { 1, 2, 5 }; int[] second = new int[] { 0, 2, 7 }; int[] third = new int[] { -3, -1, 0 }; assertThat(getMinimumSum(first, second, third), is(2)); }
@Test public void testGetMinimumSum3() { int[] first = new int[] { 1, 2, 5, 6, 7 }; int[] second = new int[] { 0, 2, 7 }; int[] third = new int[] { -3, -1, 7 }; assertThat(getMinimumSum(first, second, third), is(0)); }
@Test public void testGetMinimumSum4() { int[] first = new int[] { 1, 2, 5, 6, 7 }; int[] second = new int[] { 0, 2 }; int[] third = new int[] { -3, -1, 7 }; assertThat(getMinimumSum(first, second, third), is(4)); }
|
### Question:
MovingSpacesToStartOfString { public static void moveSpaces(char[] str) { if (str == null || str.length == 0) { return; } int i = str.length - 1; int j = str.length - 1; while (i >= 0) { if (str[i] == ' ') { i--; continue; } if (i < j) { char t = str[i]; str[i] = str[j]; str[j] = t; } i--; j--; } while (j >= 0) { str[j--] = ' '; } } static void moveSpaces(char[] str); }### Answer:
@Test public void testMoveSpaces() { String original = str == null ? null : new String(str); moveSpaces(str); assertThat("Result for character array of string = " + original + " is not expected", str, is(expected)); }
|
### Question:
LeastDifferenceInArrayWithGivenNumber { public static int getElementWithLeastDifference(int[] sequence, int element) { if (sequence == null || sequence.length == 0) { throw new IllegalArgumentException("Input array is null or empty"); } int left = 0; int right = sequence.length - 1; while (left < right) { int median = left + ((right - left) >> 1); if (sequence[median] < element) { left = median + 1; } else { right = median; } } if (sequence[left] == element) { return element; } else { if (left == 0) { return sequence[0]; } else { if (abs(element - sequence[left]) >= abs(element - sequence[left - 1])) { return sequence[left - 1]; } else { return sequence[left]; } } } } static int getElementWithLeastDifference(int[] sequence, int element); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetElementWithLeastDifferenceNullArray() { getElementWithLeastDifference(null, 1); }
@Test(expected = IllegalArgumentException.class) public void testGetElementWithLeastDifferenceEmptyArray() { getElementWithLeastDifference(new int[0], 1); }
@Test public void testGetElementWithLeastDifference1() { int actual = getElementWithLeastDifference(new int[]{1, 3, 5, 7, 9, 11, 13, 15}, 1); assertThat(actual, is(1)); }
@Test public void testGetElementWithLeastDifference2() { int actual = getElementWithLeastDifference(new int[]{1, 4, 5, 7, 9, 11, 13, 15}, 2); assertThat(actual, is(1)); }
@Test public void testGetElementWithLeastDifference3() { int actual = getElementWithLeastDifference(new int[]{1, 3, 5, 7, 9, 11, 13, 15}, 2); assertThat(actual, is(1)); }
@Test public void testGetElementWithLeastDifference4() { int actual = getElementWithLeastDifference(new int[]{1, 4, 5, 7, 9, 11, 13, 15}, 2); assertThat(actual, is(1)); }
@Test public void testGetElementWithLeastDifference5() { int actual = getElementWithLeastDifference(new int[]{1, 4, 5, 7, 9, 11, 13, 15}, 5); assertThat(actual, is(5)); }
@Test public void testGetElementWithLeastDifference6() { int actual = getElementWithLeastDifference(new int[]{1, 4, 5, 7, 9, 11, 13, 15}, 14); assertThat(actual, is(13)); }
@Test public void testGetElementWithLeastDifference7() { int actual = getElementWithLeastDifference(new int[]{1, 4, 5, 7, 9, 11, 13, 15}, 15); assertThat(actual, is(15)); }
@Test public void testGetElementWithLeastDifference8() { int actual = getElementWithLeastDifference(new int[]{1, 4, 5, 7, 9, 11, 13, 15}, 20); assertThat(actual, is(15)); }
|
### Question:
LeftmostElementOfEachLevelInBinaryTree { public static List<Integer> findLeftmostElements(BinaryTree root) { if (root == null) { throw new IllegalArgumentException("Input tree is null"); } ArrayList<Integer> values = new ArrayList<>(); Queue<Object[]> queue = new LinkedList<>(); queue.add(new Object[]{root, 0}); int level = 0; while (!queue.isEmpty()) { Object[] obj = queue.poll(); BinaryTree currentTree = (BinaryTree) obj[0]; int currentLevel = (Integer) obj[1]; if (level == currentLevel) { values.add(currentTree.data); level++; } if (currentTree.left != null) { queue.add(new Object[]{currentTree.left, currentLevel + 1}); } if (currentTree.right != null) { queue.add(new Object[]{currentTree.right, currentLevel + 1}); } } return values; } static List<Integer> findLeftmostElements(BinaryTree root); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindLeftmostElementsNullTree() { findLeftmostElements(null); }
@Test public void testFindLeftmostElements1() { List<Integer> actual = findLeftmostElements(new BinaryTree(null, null, 10)); List<Integer> expected = Collections.singletonList(10); assertThat(actual, is(expected)); }
@Test public void testFindLeftmostElements2() { BinaryTree level21 = new BinaryTree(null, null, 21); BinaryTree level22 = new BinaryTree(null, null, 22); BinaryTree level23 = new BinaryTree(null, null, 23); BinaryTree level24 = new BinaryTree(null, null, 24); BinaryTree level11 = new BinaryTree(level21, level22, 11); BinaryTree level12 = new BinaryTree(level23, level24, 12); BinaryTree root = new BinaryTree(level11, level12, 1); List<Integer> actual = findLeftmostElements(root); List<Integer> expected = Arrays.asList(1, 11, 21); assertThat(actual, is(expected)); }
@Test public void testFindLeftmostElements3() { BinaryTree level32 = new BinaryTree(null, null, 32); BinaryTree level34 = new BinaryTree(null, null, 34); BinaryTree level21 = new BinaryTree(null, null, 21); BinaryTree level22 = new BinaryTree(level34, null, 22); BinaryTree level23 = new BinaryTree(null, null, 23); BinaryTree level24 = new BinaryTree(level32, null, 24); BinaryTree level11 = new BinaryTree(level21, level22, 11); BinaryTree level12 = new BinaryTree(level23, level24, 12); BinaryTree root = new BinaryTree(level11, level12, 1); List<Integer> actual = findLeftmostElements(root); List<Integer> expected = Arrays.asList(1, 11, 21, 34); assertThat(actual, is(expected)); }
|
### Question:
MajorityVoteAlgorithm { public static int findMajorityElement(int[] sequence) { if (sequence == null || sequence.length == 0) { throw new IllegalArgumentException("Input array is null or empty"); } int cnt = 0; int currentElement = 0; for (int element : sequence) { if (cnt == 0) { currentElement = element; cnt = 1; } else if (element == currentElement) { cnt++; } else { cnt--; } } int occurrence = 0; for (int element : sequence) { if (element == currentElement) { occurrence++; } } if (occurrence << 1 >= sequence.length) { return currentElement; } else { throw new IllegalArgumentException("Input array does not have majority element"); } } static int findMajorityElement(int[] sequence); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testFindMajorityElementNullArray() { findMajorityElement(null); }
@Test(expected = IllegalArgumentException.class) public void testFindMajorityElementEmptyArray() { findMajorityElement(new int[0]); }
@Test(expected = IllegalArgumentException.class) public void testFindMajorityElementNoMajorityElement() { findMajorityElement(new int[]{1, 2, 3, 4, 5, 1, 1, 1, 3}); }
@Test public void testFindMajorityElement1() { assertThat(findMajorityElement(new int[]{10}), is(10)); }
@Test public void testFindMajorityElement2() { assertThat(findMajorityElement(new int[]{9, 10}), is(9)); }
@Test public void testFindMajorityElement3() { assertThat(findMajorityElement(new int[]{9, 10, 10, 11}), is(10)); }
@Test public void testFindMajorityElement4() { assertThat(findMajorityElement(new int[]{1, 2, 1, 4, 1, 1, 2, 1, 3}), is(1)); }
@Test public void testFindMajorityElement5() { assertThat(findMajorityElement(new int[]{5, 5, 2, 3, 4, 5, 6, 5, 7, 5, 5, 5, 3}), is(5)); }
|
### Question:
ConvertNumberToExcelNumber { public static String convert(int n) { if (n <= 0) { throw new IllegalArgumentException("Argument is not positive"); } StringBuilder builder = new StringBuilder(); while (n > 0) { n--; int remainder = n % 26; n /= 26; builder.append((char) (remainder + 65)); } return builder.reverse().toString(); } static String convert(int n); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testConvertNegativeN() { convert(-1); }
@Test(expected = IllegalArgumentException.class) public void testConvertZeroN() { convert(0); }
@Test public void testConvert() { assertThat(convert(1), is("A")); assertThat(convert(26), is("Z")); assertThat(convert(27), is("AA")); assertThat(convert(52), is("AZ")); assertThat(convert(53), is("BA")); assertThat(convert(54), is("BB")); assertThat(convert(676), is("YZ")); assertThat(convert(702), is("ZZ")); assertThat(convert(703), is("AAA")); }
|
### Question:
SumOfTwoSquares { public static int findNumberOfWays(int value) { if (value < 0) { return 0; } if (value <= 1) { return 1; } int left = 0; int right = (int) Math.sqrt(value); int numberOfWays = 0; while (left <= right) { long sum = (left + 0L) * left + (right + 0L) * right; if (sum < value) { left++; } else if (sum > value) { right--; } else { numberOfWays++; left++; right--; } } return numberOfWays; } static int findNumberOfWays(int value); }### Answer:
@Test public void testFindNumberOfWays() { int actual = findNumberOfWays(inputValue); assertThat("Result for value = " + inputValue + " does not match with expected = " + expected, actual, is(expected)); }
|
### Question:
GenerateWhile extends LoopGenerator<E> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GenerateWhile<?>)) { return false; } GenerateWhile<?> other = (GenerateWhile<?>) obj; return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.test.equals(test); } GenerateWhile(Generator<? extends E> wrapped, Predicate<? super E> test); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testEquals() { Generator<Integer> anotherGenerate = new GenerateWhile<Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1, 10)), isLessThanFive); assertEquals(generateWhile, generateWhile); assertEquals(generateWhile, anotherGenerate); assertTrue(!generateWhile.equals((GenerateWhile<Integer>)null)); Generator<Integer> aGenerateWithADifferentPredicate = new GenerateWhile<Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1, 10)), new Predicate<Integer>() { public boolean test(Integer obj) { return obj < FIVE; } }); assertTrue(!generateWhile.equals(aGenerateWithADifferentPredicate)); Generator<Integer> aGenerateWithADifferentWrapped = new GenerateWhile<Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1,11)), isLessThanFive); assertTrue(!generateWhile.equals(aGenerateWithADifferentWrapped)); }
|
### Question:
IteratorToGeneratorAdapter extends LoopGenerator<E> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof IteratorToGeneratorAdapter<?>)) { return false; } IteratorToGeneratorAdapter<?> that = (IteratorToGeneratorAdapter<?>) obj; return this.iter.equals(that.iter); } IteratorToGeneratorAdapter(Iterator<? extends E> iter); void run(Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static IteratorToGeneratorAdapter<E> adapt(Iterator<? extends E> iter); static IteratorToGeneratorAdapter<E> adapt(Iterable<? extends E> iterable); }### Answer:
@Test public void testEquals() { Iterator<String> iter = list.iterator(); Generator<String> gen = new IteratorToGeneratorAdapter<String>(iter); assertObjectsAreEqual(gen,gen); assertObjectsAreEqual(gen,new IteratorToGeneratorAdapter<String>(iter)); }
|
### Question:
LoopGenerator extends BaseGenerator<E> { public void stop() { if (wrappedGenerator != null && wrappedGenerator instanceof LoopGenerator<?>) { ((LoopGenerator<?>) wrappedGenerator).stop(); } stopped = true; } LoopGenerator(); LoopGenerator(Generator<? extends E> generator); void stop(); boolean isStopped(); }### Answer:
@Test public void testStop() { final StringBuilder result = new StringBuilder(); simpleGenerator.run(new Procedure<Integer>() { int i = 0; public void run(Integer obj) { result.append(obj); if (i++ > 1) { simpleGenerator.stop(); } } }); assertEquals("012", result.toString()); }
|
### Question:
GenerateUntil extends LoopGenerator<E> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof GenerateUntil<?>)) { return false; } GenerateUntil<?> other = (GenerateUntil<?>) obj; return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.test.equals(test); } GenerateUntil(Generator<? extends E> wrapped, Predicate<? super E> test); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testEquals() { Generator<Integer> anotherGenerate = new GenerateUntil<Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1, 10)), isMoreThanFive); assertEquals(generateUntil, generateUntil); assertEquals(generateUntil, anotherGenerate); assertTrue(!generateUntil.equals((GenerateUntil<Integer>)null)); Generator<Integer> aGenerateWithADifferentPredicate = new GenerateUntil<Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1, 10)), new Predicate<Integer>() { public boolean test(Integer obj) { return obj > FIVE; } }); assertTrue(!generateUntil.equals(aGenerateWithADifferentPredicate)); Generator<Integer> aGenerateWithADifferentWrapped = new GenerateUntil<Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1,2)), isMoreThanFive); assertTrue(!generateUntil.equals(aGenerateWithADifferentWrapped)); }
|
### Question:
GenerateUntil extends LoopGenerator<E> { @Override public int hashCode() { int result = "GenerateUntil".hashCode(); result <<= 2; Generator<?> gen = getWrappedGenerator(); result ^= gen.hashCode(); result <<= 2; result ^= test.hashCode(); return result; } GenerateUntil(Generator<? extends E> wrapped, Predicate<? super E> test); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testHashcode() { assertEquals(generateUntil.hashCode(), generateUntil.hashCode()); assertEquals(generateUntil.hashCode(), new GenerateUntil<Integer>(wrappedGenerator, isMoreThanFive).hashCode()); }
|
### Question:
TransformedGenerator extends LoopGenerator<E> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof TransformedGenerator<?, ?>)) { return false; } TransformedGenerator<?, ?> other = (TransformedGenerator<?, ?>) obj; return other.getWrappedGenerator().equals(getWrappedGenerator()) && other.func == func; } @SuppressWarnings("unchecked") TransformedGenerator(Generator<? extends I> wrapped, Function<? super I, ? extends E> func); @SuppressWarnings("unchecked") void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testEquals() { TransformedGenerator<Integer, Integer> anotherTransformedGenerator = new TransformedGenerator<Integer, Integer>(wrappedGenerator, sumsTwo); assertEquals(sumsTwoGenerator, sumsTwoGenerator); assertEquals(sumsTwoGenerator, anotherTransformedGenerator); assertTrue(!sumsTwoGenerator.equals((TransformedGenerator<Integer, Integer>)null)); TransformedGenerator<Integer, Integer> aGenerateWithADifferentFunction = new TransformedGenerator<Integer, Integer>(wrappedGenerator, new Function<Integer, Integer>() { public Integer evaluate( Integer obj ) { return obj; } }); assertTrue( !sumsTwoGenerator.equals(aGenerateWithADifferentFunction)); TransformedGenerator<Integer, Integer> aTransformedGeneratorWithADifferentWrapped = new TransformedGenerator<Integer, Integer>( IteratorToGeneratorAdapter.adapt(new IntegerRange(1,2)), sumsTwo); assertTrue(!sumsTwoGenerator.equals(aTransformedGeneratorWithADifferentWrapped)); }
|
### Question:
TransformedGenerator extends LoopGenerator<E> { @Override public int hashCode() { int result = "TransformedGenerator".hashCode(); result <<= 2; Generator<?> gen = getWrappedGenerator(); result ^= gen.hashCode(); result <<= 2; result ^= func.hashCode(); return result; } @SuppressWarnings("unchecked") TransformedGenerator(Generator<? extends I> wrapped, Function<? super I, ? extends E> func); @SuppressWarnings("unchecked") void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testHashcode() { assertEquals(sumsTwoGenerator.hashCode(), sumsTwoGenerator.hashCode()); assertEquals(sumsTwoGenerator.hashCode(), new TransformedGenerator<Integer, Integer>(wrappedGenerator, sumsTwo).hashCode()); }
|
### Question:
TransformedGenerator extends LoopGenerator<E> { @SuppressWarnings("unchecked") public void run(final Procedure<? super E> proc) { ((Generator<? extends I>) getWrappedGenerator()).run(new Procedure<I>() { public void run(I obj) { proc.run(func.evaluate(obj)); } }); } @SuppressWarnings("unchecked") TransformedGenerator(Generator<? extends I> wrapped, Function<? super I, ? extends E> func); @SuppressWarnings("unchecked") void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testGenerate() { final List<Integer> doubledValues = new ArrayList<Integer>(); sumsTwoGenerator.run(new Procedure<Integer>() { public void run( Integer obj ) { doubledValues.add(obj); } }); final List<Integer> expected = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10 , 11); assertEquals(9, doubledValues.size()); assertEquals(expected, doubledValues); }
|
### Question:
BaseGenerator implements Generator<E> { public final <T> T to(Function<Generator<? extends E>, ? extends T> transformer) { return transformer.evaluate(this); } BaseGenerator(); final T to(Function<Generator<? extends E>, ? extends T> transformer); final C to(C collection); final Collection<E> toCollection(); }### Answer:
@Test public void testTo() { Collection<Integer> col = simpleGenerator.to(CollectionTransformer.<Integer> toCollection()); assertEquals("[0, 1, 2, 3, 4]", col.toString()); Collection<Integer> fillThis = new LinkedList<Integer>(); col = simpleGenerator.to(new CollectionTransformer<Integer, Collection<Integer>>(fillThis)); assertSame(fillThis, col); assertEquals("[0, 1, 2, 3, 4]", col.toString()); col = (Collection<Integer>) simpleGenerator.toCollection(); assertEquals("[0, 1, 2, 3, 4]", col.toString()); assertEquals("[0, 1, 2, 3, 4]", col.toString()); fillThis = new LinkedList<Integer>(); col = (Collection<Integer>) simpleGenerator.to(fillThis); assertSame(fillThis, col); assertEquals("[0, 1, 2, 3, 4]", col.toString()); }
|
### Question:
EachElement { public static <E> Generator<E> from(Iterable<? extends E> iterable) { return iterable == null ? null : EachElement.from(iterable.iterator()); } private EachElement(); static Generator<E> from(Iterable<? extends E> iterable); @SuppressWarnings("unchecked") static Generator<Map.Entry<K, V>> from(Map<? extends K, ? extends V> map); static Generator<E> from(E... array); static Generator<E> from(Iterator<? extends E> iter); }### Answer:
@Test public void testFromNull() { assertNull(EachElement.from((Collection<?>) null)); assertNull(EachElement.from((Map<?, ?>) null)); assertNull(EachElement.from((Iterator<?>) null)); assertNull(EachElement.from((Object[]) null)); }
@Test public void testWithList() { Collection<?> col = EachElement.from(list).toCollection(); assertEquals("[0, 1, 2, 3, 4]", col.toString()); }
@Test @SuppressWarnings("unchecked") public void testWithMap() { List<?> col = (List<?>) EachElement.from(map).toCollection(); int i = 0; for (;i<col.size();i++) { Map.Entry<String, String> entry = (Map.Entry<String, String>) col.get(i); if (entry.getKey().equals("1")) { assertEquals("1-1", entry.getValue()); } else if (entry.getKey().equals("2")) { assertEquals("2-1", entry.getValue()); } else if (entry.getKey().equals("3")) { assertEquals("3-1", entry.getValue()); } else if (entry.getKey().equals("4")) { assertEquals("4-1", entry.getValue()); } else if (entry.getKey().equals("5")) { assertEquals("5-1", entry.getValue()); } } assertEquals(5, i); }
@Test public void testWithArray() { Collection<?> col = EachElement.from(array).toCollection(); assertEquals("[1, 2, 3, 4, 5]", col.toString()); }
@Test public void testWithStop() { assertEquals("[0, 1, 2]", new UntilGenerate<Integer>(new Offset(3), EachElement.from(list)).toCollection().toString()); assertEquals("[0, 1, 2, 3]", new GenerateUntil<Integer>(EachElement.from(list), new Offset(3)).toCollection().toString()); assertEquals("[0, 1, 2]", new WhileGenerate<Integer>(new Limit(3), EachElement.from(list)).toCollection().toString()); assertEquals("[0, 1, 2, 3]", new GenerateWhile<Integer>(EachElement.from(list), new Limit(3)).toCollection().toString()); }
@Test public void testWithIterator() { Collection<?> col = EachElement.from(list.iterator()).toCollection(); assertEquals("[0, 1, 2, 3, 4]", col.toString()); }
|
### Question:
Offset implements NullaryPredicate, Predicate<Object>,
BinaryPredicate<Object, Object> { public boolean test() { if (state.get() < min) { state.incrementAndGet(); return false; } return true; } Offset(int count); boolean test(); boolean test(Object obj); boolean test(Object a, Object b); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testZero() throws Exception { NullaryPredicate p = new Offset(0); assertTrue( p.test()); assertTrue( p.test()); assertTrue( p.test()); }
@Test public void testTestNullary() throws Exception { NullaryPredicate p = new Offset(3); assertTrue(!p.test()); assertTrue(!p.test()); assertTrue(!p.test()); assertTrue(p.test()); }
@Test public void testTestUnary() throws Exception { Predicate<Object> p = new Offset(3); assertTrue(!p.test(null)); assertTrue(!p.test(null)); assertTrue(!p.test(null)); assertTrue(p.test(null)); }
@Test public void testTestBinary() throws Exception { BinaryPredicate<Object, Object> p = new Offset(3); assertTrue(!p.test(null,null)); assertTrue(!p.test(null,null)); assertTrue(!p.test(null,null)); assertTrue(p.test(null,null)); }
|
### Question:
GenerateWhile extends LoopGenerator<E> { @Override public int hashCode() { int result = "GenerateWhile".hashCode(); result <<= 2; Generator<?> gen = getWrappedGenerator(); result ^= gen.hashCode(); result <<= 2; result ^= test.hashCode(); return result; } GenerateWhile(Generator<? extends E> wrapped, Predicate<? super E> test); void run(final Procedure<? super E> proc); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testHashcode() { assertEquals(generateWhile.hashCode(), generateWhile.hashCode()); assertEquals(generateWhile.hashCode(), new GenerateWhile<Integer>(wrappedGenerator, isLessThanFive).hashCode()); }
|
### Question:
Offset implements NullaryPredicate, Predicate<Object>,
BinaryPredicate<Object, Object> { @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Offset)) { return false; } Offset other = (Offset) obj; return other.min == min; } Offset(int count); boolean test(); boolean test(Object obj); boolean test(Object a, Object b); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { Offset offset = new Offset(1); assertObjectsAreEqual(new Offset(1), offset); assertObjectsAreNotEqual(new Offset(2), offset); assertTrue(!offset.equals(null)); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.