method2testcases
stringlengths
118
6.63k
### Question: GeneralUtilities extends SpagoBIUtilities { public static Map<String, ParamDefaultValue> getParamsDefaultValuesUseAlsoDB(IDataSet dataSet) { Map<String, ParamDefaultValue> res = DataSetUtilities.getParamsDefaultValues(dataSet); if (res != null) { return res; } logger.warn("No params default values found on dataSet. I try from db."); try { String label = dataSet.getLabel(); if (label == null) { logger.warn("Label not found -> no default values from database"); return null; } IDataSetDAO dsDAO = DAOFactory.getDataSetDAO(); IDataSet ds = dsDAO.loadDataSetByLabel(label); if (ds == null) { logger.warn("Dataset not found -> no default values from database"); return null; } res = DataSetUtilities.getParamsDefaultValues(ds); } catch (Exception e) { logger.warn("Default parameters values can't be retrieved from dataSet db.", e); } return res; } static String replaceInternationalizedMessages(String message); static String trim(String s); static void subsituteBIObjectParametersLovProfileAttributes(BIObject obj, SessionContainer session); static IEngUserProfile createNewUserProfile(String userId); static String getSpagoBIProfileBaseUrl(String userId); static boolean isSSOEnabled(); static String getSpagoAdapterHttpUrl(); static Locale getStartingDefaultLocale(); static Locale getDefaultLocale(); static List<Locale> getSupportedLocales(); static String getCountry(String language); static JSONArray getSupportedLocalesAsJSONArray(); static Locale getCurrentLocale(RequestContainer requestContainer); static String getLocaleDateFormat(SessionContainer permSess); static String getLocaleDateFormat(Locale locale); static String getLocaleDateFormatForExtJs(SessionContainer permSess); static String getServerDateFormat(); static String getServerTimeStampFormat(); static String getServerDateFormatExtJs(); static String getServerTimestampFormatExtJs(); static char getDecimalSeparator(Locale locale); static char getGroupingSeparator(Locale locale); static int getTemplateMaxSize(); static int getDataSetFileMaxSize(); static int getGisLayerFileMaxSize(); static String getSessionExpiredURL(); static String getUrl(String baseUrl, Map mapPars); static Map getParametersFromURL(String urlString); static int getDatasetMaxResults(); static File getPreviewFilesStorageDirectoryPath(); static Map<String, ParamDefaultValue> getParamsDefaultValuesUseAlsoDB(IDataSet dataSet); static String getSpagoBIConfigurationProperty(String propertyName); static String getExternalEngineUrl(Engine eng); static String getServiceHostUrl(); static final int MAX_DEFAULT_FILE_5M_SIZE; static final int MAX_DEFAULT_FILE_10M_SIZE; }### Answer: @Test public void testGetParamsDefaultValuesEmptyNoDSLabel() { IDataSet dummy = new MockDataSet(); Map<String, ?> dvs = GeneralUtilities.getParamsDefaultValuesUseAlsoDB(dummy); Assert.assertNull(dvs); } @Test public void testGetParamsDefaultValuesParamsStringNoDSLabel() { IDataSet dummy = new MockDataSet(); dummy.setParameters(DataSetParametersListTest.XML); Map<String, ?> dvs = GeneralUtilities.getParamsDefaultValuesUseAlsoDB(dummy); Assert.assertEquals(2, dvs.size()); Assert.assertEquals(DataSetParametersListTest.FIRST_DEFAULT_VALUE, dvs.get(DataSetParametersListTest.FIRST_PARAM)); Assert.assertEquals(DataSetParametersListTest.SECOND_DEFAULT_VALUE, dvs.get(DataSetParametersListTest.SECOND_PARAM)); } @Test public void testGetParamsDefaultValuesWithDSLabelFromDB() { IDataSet dummy = new MockDataSet(); dummy.setLabel(DataSetUtilitiesTest.DATA_SET_QUERY_TEST); Map<String, ParamDefaultValue> dvs = GeneralUtilities.getParamsDefaultValuesUseAlsoDB(dummy); DataSetUtilitiesTest.checkQueryDataSetDefaultValues(dvs); } @Test public void testGetParamsDefaultValuesEmptyDSAndNoDB() { IDataSet dummy = new MockDataSet(); dummy.setLabel("doesntExist18"); Map<String, ?> dvs = GeneralUtilities.getParamsDefaultValuesUseAlsoDB(dummy); Assert.assertNull(dvs); }
### Question: DataSetParametersList { public static DataSetParametersList fromXML(String dataDefinition) throws SourceBeanException { return new DataSetParametersList(dataDefinition); } DataSetParametersList(); DataSetParametersList(String dataDefinition); void loadFromXML(String dataDefinition); String toXML(); String getDataSetResult(IEngUserProfile profile); List getProfileAttributeNames(); boolean requireProfileAttributes(); void add(String name, String type); void add(String name, String type, String defaultValue); void remove(String name, String type); static DataSetParametersList fromXML(String dataDefinition); List getItems(); void setPars(List items); static final String DEFAULT_VALUE_XML; }### Answer: @Test public void testFromXML() throws SourceBeanException { DataSetParametersList fromXML = DataSetParametersList.fromXML(XML); checkParams(fromXML); }
### Question: StringUtilities { public static String[] getSubstringsBetween(String values, String delimiter) { try { ArrayList<String> arrayList = new ArrayList<>(); int start = values.indexOf(delimiter); int delimiterLength = delimiter.length(); while (start > -1) { int end = values.indexOf(delimiter, start + delimiterLength); arrayList.add(values.substring(start + delimiterLength, end)); start = values.indexOf(delimiter, end + delimiterLength); } return arrayList.toArray(new String[0]); } catch (IndexOutOfBoundsException e) { throw new SpagoBIRuntimeException("Unable to tokenize string [" + values + "] with delimiter [" + delimiter + "]", e); } } static String substituteProfileAttributesInString(String str, IEngUserProfile profile); static String substituteParametersInString(String str, Map parameters); static String substituteProfileAttributesInString(String str, IEngUserProfile profile, int profileAttributeStartIndex); static String left(String str, int index); static String substituteParametersInString(String statement, Map parameters, int parametersStartIndex); static String[] findAttributeValues(String attributeValue); static String quote(String s); static String substituteParametersInString(String statement, Map valuesMap, Map parType, boolean surroundWithQuotes); static boolean isNull(String str); static boolean isEmpty(String str); static boolean isNotEmpty(String str); static boolean containsOnlySpaces(String str); static Date stringToDate(String strDate, String format); static String substituteDatasetParametersInString(String statement, Map valuesMap, Map parType, boolean surroundWithQuotes); static String convertStreamToString(InputStream is); static String[] convertCollectionInArray(Collection coll); static Collection convertArrayInCollection(String[] array); static String getRandomString(int len); static String fromStringToHTML(String s); static String sha256(String s); static String readStream(InputStream inputStream); static String getMultiValue(String value, String type); static String getSingleValue(String value, String type); static String findLongest(String... text); static String[] getSubstringsBetween(String values, String delimiter); static String[] splitBetween(String values, String prefix, String delimiter, String suffix); static String replaceSpecials(String replacement); static final String START_PARAMETER; static final String START_USER_PROFILE_ATTRIBUTE; static final String DEFAULT_CHARSET; }### Answer: @Test public void getSubstringsBetweenTest() { String delimiter = "'"; String values = "('1')"; String[] result = StringUtilities.getSubstringsBetween(values, delimiter); assertEquals(1, result.length); assertEquals("1", result[0]); values = "('2')"; result = StringUtilities.getSubstringsBetween(values, delimiter); assertEquals(1, result.length); assertEquals("2", result[0]); values = "('Drink')"; result = StringUtilities.getSubstringsBetween(values, delimiter); assertEquals(1, result.length); assertEquals("Drink", result[0]); values = "('Drink','Food')"; result = StringUtilities.getSubstringsBetween(values, delimiter); assertEquals(2, result.length); assertEquals("Drink", result[0]); assertEquals("Food", result[1]); values = "('D'rink','Fo'od')"; result = StringUtilities.getSubstringsBetween(values, delimiter); assertEquals(3, result.length); assertEquals("D", result[0]); assertEquals(",", result[1]); assertEquals("od", result[2]); } @Test(expected = SpagoBIRuntimeException.class) public void getSubstringsBetweenExceptionTest() { String delimiter = "'"; String values = "('D'rink')"; String[] result = StringUtilities.getSubstringsBetween(values, delimiter); }
### Question: StringUtilities { public static String[] splitBetween(String values, String prefix, String delimiter, String suffix) { int prefixIndex = values.indexOf(prefix); int suffixIndex = values.lastIndexOf(suffix); if (prefixIndex > -1 && suffixIndex > -1) { int prefixLength = prefix.length(); String[] returnedValues = values.substring(prefixIndex + prefixLength, suffixIndex).split("\\Q" + delimiter + "\\E"); Character ch1 = values.charAt(values.lastIndexOf(suffix) - 1); Character ch2 = values.charAt(values.lastIndexOf(suffix)); if (ch1.equals(ch2)) { String[] returnedValuesEmpty = new String[returnedValues.length + 1]; for (int i = 0; i < returnedValues.length; i++) { returnedValuesEmpty[i] = returnedValues[i]; } returnedValuesEmpty[returnedValues.length] = StringUtils.EMPTY; return returnedValuesEmpty; } return returnedValues; } else { throw new SpagoBIRuntimeException("Unable to tokenize string [" + values + "] with delimiters [" + prefix + "," + delimiter + "," + suffix + "]"); } } static String substituteProfileAttributesInString(String str, IEngUserProfile profile); static String substituteParametersInString(String str, Map parameters); static String substituteProfileAttributesInString(String str, IEngUserProfile profile, int profileAttributeStartIndex); static String left(String str, int index); static String substituteParametersInString(String statement, Map parameters, int parametersStartIndex); static String[] findAttributeValues(String attributeValue); static String quote(String s); static String substituteParametersInString(String statement, Map valuesMap, Map parType, boolean surroundWithQuotes); static boolean isNull(String str); static boolean isEmpty(String str); static boolean isNotEmpty(String str); static boolean containsOnlySpaces(String str); static Date stringToDate(String strDate, String format); static String substituteDatasetParametersInString(String statement, Map valuesMap, Map parType, boolean surroundWithQuotes); static String convertStreamToString(InputStream is); static String[] convertCollectionInArray(Collection coll); static Collection convertArrayInCollection(String[] array); static String getRandomString(int len); static String fromStringToHTML(String s); static String sha256(String s); static String readStream(InputStream inputStream); static String getMultiValue(String value, String type); static String getSingleValue(String value, String type); static String findLongest(String... text); static String[] getSubstringsBetween(String values, String delimiter); static String[] splitBetween(String values, String prefix, String delimiter, String suffix); static String replaceSpecials(String replacement); static final String START_PARAMETER; static final String START_USER_PROFILE_ATTRIBUTE; static final String DEFAULT_CHARSET; }### Answer: @Test public void splitBetweenTest() { String prefix = "'"; String delimiter = "','"; String suffix = "'"; String values = "('D'rink','Fo'od')"; String[] result = StringUtilities.splitBetween(values, prefix, delimiter, suffix); assertEquals(2, result.length); assertEquals("D'rink", result[0]); assertEquals("Fo'od", result[1]); prefix = "**"; delimiter = "++++"; suffix = "###"; values = "(**D'rink++++Fo'od###)"; result = StringUtilities.splitBetween(values, prefix, delimiter, suffix); assertEquals(2, result.length); assertEquals("D'rink", result[0]); assertEquals("Fo'od", result[1]); } @Test(expected = SpagoBIRuntimeException.class) public void splitBetweenExceptionTest() { String prefix = "**"; String delimiter = "','"; String suffix = "'"; String values = "('D'rink','Fo'od')"; String[] result = StringUtilities.splitBetween(values, prefix, delimiter, suffix); }
### Question: ParametersDecoder { public boolean isMultiValues(String value) { return value.trim().matches(multiValueRegex); } ParametersDecoder(); ParametersDecoder(String openBlockMarker, String closeBlockMarker); String getCloseBlockMarker(); void setCloseBlockMarker(String closeBlockMarker); String getOpenBlockMarker(); void setOpenBlockMarker(String openBlockMarker); boolean isMultiValues(String value); String decodeParameter(Object paramaterValue); List decode(String value); List getOriginalValues(String value); static HashMap getDecodedRequestParameters(HttpServletRequest servletRequest); static HashMap getDecodedRequestParameters(IContainer requestContainer); static void main(String[] args); static final String DEFAULT_OPEN_BLOCK_MARKER; static final String DEFAULT_CLOSE_BLOCK_MARKER; }### Answer: @Test public void testIsMultiValue() { ParametersDecoder decoder = new ParametersDecoder(); String value = "{;{American;Colony;Ebony;Johnson;Urban}STRING}"; boolean isMultiValue = decoder.isMultiValues(value); assertTrue(isMultiValue); String json = "{name: {a : 4, b : 4}}"; isMultiValue = decoder.isMultiValues(json); assertTrue(!isMultiValue); }
### Question: SimpleRestClient { protected Response executeGetService(Map<String, Object> parameters, String serviceUrl, String userId) throws Exception { return executeService(parameters, serviceUrl, userId, RequestTypeEnum.GET, null, null); } SimpleRestClient(String hmacKey); SimpleRestClient(); boolean isAddServerUrl(); void setAddServerUrl(boolean addServerUrl); }### Answer: @Test public void testExecuteGetService() throws Exception { SimpleRestClient client = getSimpleRestClient(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); Response resp = client.executeGetService(parameters, "http: Assert.assertEquals(200, resp.getStatus()); Assert.assertTrue(DummyServlet.arrived); } @Test public void testExecuteGetServiceFail() throws Exception { SimpleRestClient client = getSimpleRestClientFail(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); boolean done = false; try { client.executeGetService(parameters, "http: } catch (Exception e) { done = true; } Assert.assertTrue(done); Assert.assertFalse(DummyServlet.arrived); }
### Question: SimpleRestClient { protected Response executePostService(Map<String, Object> parameters, String serviceUrl, String userId, String mediaType, Object data) throws Exception { return executeService(parameters, serviceUrl, userId, RequestTypeEnum.POST, mediaType, data); } SimpleRestClient(String hmacKey); SimpleRestClient(); boolean isAddServerUrl(); void setAddServerUrl(boolean addServerUrl); }### Answer: @Test public void testExecutePostService() throws Exception { SimpleRestClient client = getSimpleRestClient(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); Response resp = client.executePostService(parameters, "http: Assert.assertEquals(200, resp.getStatus()); Assert.assertTrue(DummyServlet.arrived); } @Test public void testExecutePostServiceFail() throws Exception { SimpleRestClient client = getSimpleRestClientFail(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("a", "b"); parameters.put("c", "d"); boolean done = false; try { client.executePostService(parameters, "http: } catch (Exception e) { done = true; } Assert.assertTrue(done); Assert.assertFalse(DummyServlet.arrived); }
### Question: HMACFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { throw new IllegalArgumentException("request not instance of HttpServletRequest"); } HttpServletRequest req = (HttpServletRequest) request; checkHMAC(req, tokenValidator, key); chain.doFilter(req, response); } @Override void destroy(); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig filterConfig); static final String DEFAULT_ENCODING; static final String KEY_CONFIG_NAME; final static long MAX_TIME_DELTA_DEFAULT_MS; }### Answer: @Test public void testDoFilter() throws IOException, NoSuchAlgorithmException, HMACSecurityException { Map<String, String> headers = new HashMap<String, String>(); String token = "" + System.currentTimeMillis(); headers.put(HMACUtils.HMAC_TOKEN_HEADER, token); headers.put(HMACUtils.HMAC_SIGNATURE_HEADER, getSignature("/hmac", "a=b", "", token)); RestUtilities.makeRequest(HttpMethod.Get, "http: Assert.assertTrue(DummyServlet.arrived); DummyServlet.arrived = false; headers.put(HMACUtils.HMAC_TOKEN_HEADER, token); headers.put(HMACUtils.HMAC_SIGNATURE_HEADER, getSignature("/hmac", "", body, token)); RestUtilities.makeRequest(HttpMethod.Post, "http: Assert.assertTrue(DummyServlet.arrived); DummyServlet.arrived = false; headers.put(HMACUtils.HMAC_TOKEN_HEADER, token); headers.put(RestUtilities.CONTENT_TYPE, "application/x-www-form-urlencoded"); headers.put(HMACUtils.HMAC_SIGNATURE_HEADER, getSignature("/hmac", "g=h&y=i", body, token)); RestUtilities.makeRequest(HttpMethod.Post, "http: Assert.assertTrue(DummyServlet.arrived); DummyServlet.arrived = false; headers.put(HMACUtils.HMAC_SIGNATURE_HEADER, "i0pe5"); RestUtilities.makeRequest(HttpMethod.Post, "http: Assert.assertFalse(DummyServlet.arrived); headers.put(HMACUtils.HMAC_TOKEN_HEADER, token); headers.put(RestUtilities.CONTENT_TYPE, "application/x-www-form-urlencoded"); headers.put(HMACUtils.HMAC_SIGNATURE_HEADER, getSignature("/hmac", "g=h&y=i", body, token)); RestUtilities.makeRequest(HttpMethod.Put, "http: Assert.assertTrue(DummyServlet.arrived); }
### Question: RealtimeEvaluationStrategy extends CachedEvaluationStrategy { @Override protected DatasetEvaluationStrategyType getEvaluationStrategy() { return DatasetEvaluationStrategyType.REALTIME; } RealtimeEvaluationStrategy(UserProfile userProfile, IDataSet dataSet, ICache cache); }### Answer: @Test public void shouldReturnRealtimeStrategyType() { RealtimeEvaluationStrategy strategy = (RealtimeEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.REALTIME, new MockDataSet(), new UserProfile()); assertThat(strategy.getEvaluationStrategy(), is(DatasetEvaluationStrategyType.REALTIME)); }
### Question: PersistedEvaluationStrategy extends AbstractJdbcEvaluationStrategy { @Override protected String getTableName() { return dataSet.getPersistTableName(); } PersistedEvaluationStrategy(IDataSet dataSet); }### Answer: @Test public void shouldUsePersistedTableName() { final String TABLE_NAME = "PersistedTable"; MockDataSet dataSet = new MockDataSet(); dataSet.setPersistTableName(TABLE_NAME); PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, dataSet, new UserProfile()); Assert.assertThat(strategy.getTableName(), is(TABLE_NAME)); }
### Question: PersistedEvaluationStrategy extends AbstractJdbcEvaluationStrategy { @Override protected IDataSource getDataSource() { return dataSet.getDataSourceForWriting(); } PersistedEvaluationStrategy(IDataSet dataSet); }### Answer: @Test public void shouldUseDatasourceForWriting() { final String DATASOURCE_LABEL = "DatasourceForWriting"; MockDataSet dataSet = new MockDataSet(); IDataSource dataSource = DataSourceFactory.getDataSource(); dataSource.setLabel(DATASOURCE_LABEL); dataSet.setDataSourceForWriting(dataSource); PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, dataSet, new UserProfile()); Assert.assertThat(strategy.getDataSource().getLabel(), is(DATASOURCE_LABEL)); }
### Question: PersistedEvaluationStrategy extends AbstractJdbcEvaluationStrategy { @Override protected Date getDate() { Date toReturn = null; Trigger trigger = loadTrigger(); Date previousFireTime = null; if (trigger != null) { previousFireTime = trigger.getPreviousFireTime(); } if (previousFireTime != null) { toReturn = previousFireTime; } else { toReturn = dataSet.getDateIn(); } return toReturn; } PersistedEvaluationStrategy(IDataSet dataSet); }### Answer: @Test public void shouldUsePreviousFireTimeToSetDataStoreDate() { final Date now = new Date(); new MockUp<PersistedEvaluationStrategy>() { @Mock private Trigger loadTrigger() { Trigger trigger = new Trigger(); trigger.setPreviousFireTime(now); return trigger; } }; PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, new MockDataSet(), new UserProfile()); Assert.assertThat(strategy.getDate(), is(now)); } @Test public void shouldUseDatasetDateInToSetDataStoreDate() { final Date now = new Date(); new MockUp<PersistedEvaluationStrategy>() { @Mock private Trigger loadTrigger() { return new Trigger(); } }; MockDataSet dataSet = new MockDataSet(); dataSet.setDateIn(now); PersistedEvaluationStrategy strategy = (PersistedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.PERSISTED, dataSet, new UserProfile()); Assert.assertThat(strategy.getDate(), is(now)); }
### Question: CachedEvaluationStrategy extends AbstractEvaluationStrategy { protected DatasetEvaluationStrategyType getEvaluationStrategy() { return DatasetEvaluationStrategyType.CACHED; } CachedEvaluationStrategy(UserProfile userProfile, IDataSet dataSet, ICache cache); }### Answer: @Test public void shouldReturnCachedStrategyType() { CachedEvaluationStrategy strategy = (CachedEvaluationStrategy) DatasetEvaluationStrategyFactory.get(DatasetEvaluationStrategyType.CACHED, new MockDataSet(), new UserProfile()); assertThat(strategy.getEvaluationStrategy(), is(DatasetEvaluationStrategyType.CACHED)); }
### Question: ManageDatasets extends AbstractSpagoBIAction { static String getSingleValue(String value, String type) { String toReturn = ""; value = value.trim(); if (type.equalsIgnoreCase(DataSetUtilities.STRING_TYPE)) { if (!(value.startsWith("'") && value.endsWith("'"))) { toReturn = "'" + value + "'"; } else { toReturn = value; } } else if (type.equalsIgnoreCase(DataSetUtilities.NUMBER_TYPE)) { if (value.startsWith("'") && value.endsWith("'") && value.length() >= 2) { toReturn = value.substring(1, value.length() - 1); } else { toReturn = value; } if (toReturn == null || toReturn.length() == 0) { toReturn = ""; } } else if (type.equalsIgnoreCase(DataSetUtilities.GENERIC_TYPE)) { toReturn = value; } else if (type.equalsIgnoreCase(DataSetUtilities.RAW_TYPE)) { if (value.startsWith("'") && value.endsWith("'") && value.length() >= 2) { toReturn = value.substring(1, value.length() - 1); } else { toReturn = value; } } return toReturn; } @Override void doService(); void insertPersistenceAndScheduling(IDataSet ds, HashMap<String, String> logParam); void modifyPersistenceAndScheduling(IDataSet ds, HashMap<String, String> logParam); void deletePersistenceAndScheduling(IDataSet ds, HashMap<String, String> logParam); List getCategories(); void deleteDatasetFile(IDataSet dataset); JSONArray serializeJSONArrayParsList(String parsList); IMetaData getDatasetTestMetadata(IDataSet dataSet, HashMap parametersFilled, IEngUserProfile profile, String metadata); JSONObject getDatasetTestResultList(IDataSet dataSet, HashMap<String, String> parametersFilled, IEngUserProfile profile); JSONObject getJSONDatasetResult(Integer dsId, IEngUserProfile profile); IEngUserProfile getProfile(); void setProfile(IEngUserProfile profile); static final String DEFAULT_VALUE_PARAM; static Logger logger; static Logger auditlogger; static final String JOB_GROUP; static final String TRIGGER_GROUP; static final String TRIGGER_NAME_PREFIX; static final String PUBLIC; }### Answer: @Test public void testGetSingleValue() { String[] types = new String[] { DataSetUtilities.GENERIC_TYPE, DataSetUtilities.NUMBER_TYPE, DataSetUtilities.RAW_TYPE, DataSetUtilities.STRING_TYPE }; String[] values = new String[] { "", "'", "''", "0", "'0", "0'", "'0'", "17", "abc", "'qcd'", "'qcd", "qcd'" }; Map<String, Map<String, String>> resByValueByType = new HashMap<String, Map<String, String>>(); for (String type : types) { if (!resByValueByType.containsKey(type)) { resByValueByType.put(type, new HashMap<String, String>()); } for (String value : values) { String res; try { res = ManageDatasets.getSingleValue(value, type); } catch (Exception e) { res = "exception"; } resByValueByType.get(type).put(value, res); System.out.println(String.format("%s - %s : %s", type, value, res)); } } }
### Question: LabeledEdge extends DefaultEdge { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LabeledEdge other = (LabeledEdge) obj; if (label == null) { if (other.label != null) return false; } else if (!label.equals(other.label)) return false; if (source == null && other.source != null) return false; if (target == null && other.target != null) return false; return (source.equals(other.source) && target.equals(other.target)) || (source.equals(other.target) && target.equals(other.source)); } LabeledEdge(V source, V target, String label); @Override V getSource(); @Override V getTarget(); String getLabel(); boolean isParametric(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testEquals() { assertEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("x", "y", "label")); assertEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("y", "x", "label")); assertNotEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("z", "y", "label")); assertNotEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("x", "z", "label")); assertNotEquals(new LabeledEdge<String>("x", "y", "label"), new LabeledEdge<String>("x", "z", "tag")); }
### Question: EdgeGroup { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof EdgeGroup)) return false; EdgeGroup other = (EdgeGroup) obj; if (orderedEdgeNames == null) { if (other.orderedEdgeNames != null) return false; } else if (!orderedEdgeNames.equals(other.orderedEdgeNames)) return false; if (edgeNames == null) { if (other.edgeNames != null) return false; } else if (!edgeNames.equals(other.edgeNames)) return false; return true; } EdgeGroup(Set<LabeledEdge<String>> edges); Set<String> getEdgeNames(); String getOrderedEdgeNames(); Set<Tuple> getValues(); void addValues(Set<Tuple> values); void addValue(Tuple value); boolean isResolved(); void resolve(); void unresolve(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testEquals() { assertEquals(eg1, eg1); assertEquals(eg1, eg2); assertNotEquals(eg1, eg3); }
### Question: EdgeGroup { public String getOrderedEdgeNames() { return orderedEdgeNames; } EdgeGroup(Set<LabeledEdge<String>> edges); Set<String> getEdgeNames(); String getOrderedEdgeNames(); Set<Tuple> getValues(); void addValues(Set<Tuple> values); void addValue(Tuple value); boolean isResolved(); void resolve(); void unresolve(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer: @Test public void testGetColumnNames() { assertEquals(eg1.getOrderedEdgeNames(), eg1.getOrderedEdgeNames()); assertEquals(eg1.getOrderedEdgeNames(), eg4.getOrderedEdgeNames()); }
### Question: PersistedHDFSManager implements IPersistedManager { public Object persistDataStore(IDataStore dataStore, String fileName, String folderName) { FSDataOutputStream fsOS = openHdfsFile(fileName, folderName); IMetaData mt = dataStore.getMetaData(); int nFields = mt.getFieldCount(); try { logger.debug("Starting writing the DataSet metadata"); for (int f = 0; f < nFields; f++) { String sep = f == (nFields - 1) ? "\n" : ","; fsOS.writeChars("\"" + mt.getFieldName(f) + "\"" + sep); } logger.debug("End metadata writing. Starting writing the data"); long nRecords = dataStore.getRecordsCount(); for (int i = 0; i < nRecords; i++) { IRecord record = dataStore.getRecordAt(i); for (int f = 0; f < nFields; f++) { String sep = f == (nFields - 1) ? "\n" : ","; IField field = record.getFieldAt(f); Class clz = mt.getFieldType(f); Object value = field.getValue(); appendObjectWithCast(fsOS, value, clz); fsOS.writeChars(sep); } } logger.debug("End data writing. Closing file.."); fsOS.close(); } catch (IOException e) { logger.error("Impossible to write on hdfs, error during writing "); throw new SpagoBIRuntimeException("Impossible to write on hdfs, error during writing " + e); } return fsOS; } PersistedHDFSManager(); PersistedHDFSManager(Hdfs hdfs); PersistedHDFSManager(IEngUserProfile profile); PersistedHDFSManager(String label, String description); PersistedHDFSManager(IEngUserProfile profile, String label, String description); @Override void persistDataSet(IDataSet dataSet); void persistDataSet(IDataSet dataSet, String fileName); Object persistDataStore(IDataStore dataStore, String fileName, String folderName); FSDataOutputStream openHdfsFile(String fileName, String folderName); String getFilePathFromHdfsResourcePath(String fileName); Hdfs getHdfs(); void setHdfs(Hdfs hdfs); IEngUserProfile getProfile(); void setProfile(IEngUserProfile profile); }### Answer: @Test public void testPersistDataStore() { IDataStore dataStore = Mockito.mock(IDataStore.class); IMetaData metaData = Mockito.mock(IMetaData.class); IRecord record = Mockito.mock(IRecord.class); IField fieldInt = Mockito.mock(IField.class); IField fieldStr = Mockito.mock(IField.class); Mockito.when(dataStore.getMetaData()).thenReturn(metaData); Mockito.when(dataStore.getRecordAt(Mockito.anyInt())).thenReturn(record); Mockito.when(dataStore.getRecordsCount()).thenReturn(10L); Mockito.when(metaData.getFieldCount()).thenReturn(2); Mockito.when(metaData.getFieldName(1)).thenReturn("column_Int"); Mockito.when(metaData.getFieldName(2)).thenReturn("column_Str"); Mockito.when(metaData.getFieldType(1)).thenReturn(Integer.class); Mockito.when(metaData.getFieldType(2)).thenReturn(String.class); Mockito.when(record.getFieldAt(1)).thenReturn(fieldInt); Mockito.when(record.getFieldAt(2)).thenReturn(fieldStr); Mockito.when(fieldInt.getValue()).thenReturn(new Integer(1)); Mockito.when(fieldStr.getValue()).thenReturn(new String("test")); FSDataOutputStream fsOS = (FSDataOutputStream) hdfsManager.persistDataStore(dataStore, "test_table", "signature_xyz"); assertNotNull(fsOS); assertEquals(fsOS.size(), 232); }
### Question: DataSetUtilities { public static Map<String, ParamDefaultValue> getParamsDefaultValuesUseAlsoService(IDataSet dataSet, String user, HttpSession session) { Helper.checkNotNull(dataSet, "dataSet"); Helper.checkNotNull(session, "session"); Helper.checkNotNullNotTrimNotEmpty(user, "user"); Map<String, ParamDefaultValue> res = getParamsDefaultValues(dataSet); if (res != null) { return res; } logger.warn("No params default values found on dataSet. I try from service."); try { String label = dataSet.getLabel(); if (label == null) { logger.warn("Label not found -> no default values from service"); return null; } DataSetServiceProxy proxy = new DataSetServiceProxy(user, session); IDataSet ds = proxy.getDataSetByLabel(label); if (ds == null) { logger.warn("Dataset not found -> no default values from service"); return null; } res = getParamsDefaultValues(ds); } catch (Exception e) { logger.warn("Default parameters values can't be retrieved from dataSet service.", e); } return res; } static boolean isExecutableByUser(IDataSet dataset, IEngUserProfile profile); static boolean isExecutableByUser(String ownerDataSet, IEngUserProfile profile); static boolean isAdministrator(IEngUserProfile profile); @SuppressWarnings("unchecked") static Map<String, ParamDefaultValue> getParamsDefaultValues(IDataSet dataSet); static Map<String, ParamDefaultValue> getParamsDefaultValuesUseAlsoService(IDataSet dataSet, String user, HttpSession session); @SuppressWarnings({ "rawtypes", "unchecked" }) static void fillDefaultValues(IDataSet dataSet, Map parameters); static boolean isDisableDefaultParams(); static void setDisableDefaultParams(boolean disableDefaultParams); static Map<String, String> getParametersMap(String parameters); static JSONObject parametersJSONArray2JSONObject(IDataSet dataSet, JSONArray parameters); static Map<String, String> getParametersMap(JSONObject jsonParameters); static Map<String, Object> getDriversMap(JSONObject driversJson); static Object getValue(String value, Class type); static IFieldMetaData getFieldMetaData(IDataSet dataSet, String columnName); static String getColumnNameWithoutQbePrefix(String columnName); static final String STRING_TYPE; static final String NUMBER_TYPE; static final String RAW_TYPE; static final String GENERIC_TYPE; }### Answer: @Ignore @Test public void testGetParamsDefaultValuesUseAlsoService() throws Exception { UtilitiesForTest.setUpTestJNDI(); EnginConf.setTestconfigInputstream(new FileInputStream("resources-test/engine-config.xml")); UtilitiesForTest.writeSessionOfWebApp(); HttpSession session = UtilitiesForTest.getSession(); MockDataSet dataSet = new MockDataSet(); dataSet.setLabel(DATA_SET_QUERY_TEST); Map<String, ParamDefaultValue> values = DataSetUtilities.getParamsDefaultValuesUseAlsoService(dataSet, ADMIN_USER, session); checkQueryDataSetDefaultValues(values); }
### Question: DataSetUtilities { @SuppressWarnings("unchecked") public static Map<String, ParamDefaultValue> getParamsDefaultValues(IDataSet dataSet) { Helper.checkNotNull(dataSet, "dataSet"); try { String params = dataSet.getParameters(); if (params == null || params.isEmpty()) { return null; } Map<String, ParamDefaultValue> res = new HashMap<String, ParamDefaultValue>(); DataSetParametersList dspl = DataSetParametersList.fromXML(params); for (DataSetParameterItem item : (List<DataSetParameterItem>) dspl.getItems()) { String defaultValue = item.getDefaultValue(); if (defaultValue == null || defaultValue.isEmpty()) { continue; } String name = item.getName(); String type = item.getType(); res.put(name, new ParamDefaultValue(name, type, defaultValue)); } return res; } catch (Exception e) { logger.warn( "Default parameters values can't be retrieved from dataSet. I try from dataSet persistence. Empty defaults values map will be returned.", e); } return null; } static boolean isExecutableByUser(IDataSet dataset, IEngUserProfile profile); static boolean isExecutableByUser(String ownerDataSet, IEngUserProfile profile); static boolean isAdministrator(IEngUserProfile profile); @SuppressWarnings("unchecked") static Map<String, ParamDefaultValue> getParamsDefaultValues(IDataSet dataSet); static Map<String, ParamDefaultValue> getParamsDefaultValuesUseAlsoService(IDataSet dataSet, String user, HttpSession session); @SuppressWarnings({ "rawtypes", "unchecked" }) static void fillDefaultValues(IDataSet dataSet, Map parameters); static boolean isDisableDefaultParams(); static void setDisableDefaultParams(boolean disableDefaultParams); static Map<String, String> getParametersMap(String parameters); static JSONObject parametersJSONArray2JSONObject(IDataSet dataSet, JSONArray parameters); static Map<String, String> getParametersMap(JSONObject jsonParameters); static Map<String, Object> getDriversMap(JSONObject driversJson); static Object getValue(String value, Class type); static IFieldMetaData getFieldMetaData(IDataSet dataSet, String columnName); static String getColumnNameWithoutQbePrefix(String columnName); static final String STRING_TYPE; static final String NUMBER_TYPE; static final String RAW_TYPE; static final String GENERIC_TYPE; }### Answer: @Test public void testGetParamsDefaultValues() { IDataSet dataSet = new MockDataSet(); dataSet.setParameters(DataSetParametersListTest.XML); Map<String, ParamDefaultValue> pdvs = DataSetUtilities.getParamsDefaultValues(dataSet); checkParams(pdvs); }
### Question: DataSetParametersList { public void loadFromXML(String dataDefinition) throws SourceBeanException { logger.debug("IN"); dataDefinition.trim(); InputSource stream = new InputSource(new StringReader(dataDefinition)); SourceBean source = SourceBean.fromXMLStream(stream); if (!source.getName().equals("PARAMETERSLIST")) { SourceBean wrapper = new SourceBean("PARAMETERSLIST"); wrapper.setAttribute(source); source = wrapper; } List listRows = source.getAttributeAsList("ROWS.ROW"); Iterator iterRows = listRows.iterator(); ArrayList parsList = new ArrayList(); while (iterRows.hasNext()) { DataSetParameterItem par = new DataSetParameterItem(); SourceBean element = (SourceBean) iterRows.next(); String name = (String) element.getAttribute("NAME"); par.setName(name); String type = (String) element.getAttribute("TYPE"); par.setType(type); String defaultValue = (String) element.getAttribute(DEFAULT_VALUE_XML); par.setDefaultValue(defaultValue); parsList.add(par); } setPars(parsList); logger.debug("OUT"); } DataSetParametersList(); DataSetParametersList(String dataDefinition); void loadFromXML(String dataDefinition); String toXML(); String getDataSetResult(IEngUserProfile profile); List getProfileAttributeNames(); boolean requireProfileAttributes(); void add(String name, String type); void add(String name, String type, String defaultValue); void remove(String name, String type); static DataSetParametersList fromXML(String dataDefinition); List getItems(); void setPars(List items); static final String DEFAULT_VALUE_XML; }### Answer: @Test public void testLoadFromXML() throws SourceBeanException { DataSetParametersList dspl = new DataSetParametersList(); dspl.loadFromXML(XML); checkParams(dspl); }
### Question: DataSetParametersList { public String toXML() { logger.debug("IN"); String lovXML = ""; lovXML += "<PARAMETERSLIST>"; lovXML += "<ROWS>"; DataSetParameterItem lov = null; Iterator iter = items.iterator(); while (iter.hasNext()) { lov = (DataSetParameterItem) iter.next(); String name = lov.getName(); String type = lov.getType(); String defaultValue = lov.getDefaultValue(); lovXML += "<ROW" + " NAME=\"" + name + "\"" + " TYPE=\"" + type + "\" " + DEFAULT_VALUE_XML + "=\"" + defaultValue + "\" />"; } lovXML += "</ROWS></PARAMETERSLIST>"; logger.debug("OUT"); return lovXML; } DataSetParametersList(); DataSetParametersList(String dataDefinition); void loadFromXML(String dataDefinition); String toXML(); String getDataSetResult(IEngUserProfile profile); List getProfileAttributeNames(); boolean requireProfileAttributes(); void add(String name, String type); void add(String name, String type, String defaultValue); void remove(String name, String type); static DataSetParametersList fromXML(String dataDefinition); List getItems(); void setPars(List items); static final String DEFAULT_VALUE_XML; }### Answer: @Test public void testToXML() { DataSetParametersList dspl = new DataSetParametersList(); dspl.add(FIRST_PARAM, "string"); dspl.add(SECOND_PARAM, "number"); String xml = dspl.toXML(); assertEquals( "<PARAMETERSLIST><ROWS><ROW NAME=\"firstParam\" TYPE=\"string\" DEFAULT_VALUE=\"\" /><ROW NAME=\"secondParam\" TYPE=\"number\" DEFAULT_VALUE=\"\" /></ROWS></PARAMETERSLIST>" + "", xml); dspl = new DataSetParametersList(); dspl.add(FIRST_PARAM, "string", FIRST_DEFAULT_VALUE); dspl.add(SECOND_PARAM, "number", SECOND_DEFAULT_VALUE); xml = dspl.toXML(); assertEquals( "<PARAMETERSLIST><ROWS><ROW NAME=\"firstParam\" TYPE=\"string\" DEFAULT_VALUE=\"kik\" /><ROW NAME=\"secondParam\" TYPE=\"number\" DEFAULT_VALUE=\"2\" /></ROWS></PARAMETERSLIST>" + "", xml); }
### Question: ExceptionUtilities { public static String getStackTraceAsString( Exception aException ){ String vStackTrace = "\t" + aException.toString() + "\n"; for( StackTraceElement vElement : aException.getStackTrace() ){ vStackTrace += "\t\t" + vElement.toString() + "\n"; } return vStackTrace; } static String getStackTraceAsString( Exception aException ); }### Answer: @Test public void testGetStackTraceAsString() { Exception mockException = mock(Exception.class); when(mockException.toString()).thenReturn("Mocked Exception"); when(mockException.getStackTrace()).thenReturn(new StackTraceElement[]{ new StackTraceElement("String","toString()","testfile",123), new StackTraceElement("Testclass","testMethod()","testfile2",42) }); String expectedResult = "\tMocked Exception\n" + "\t\tString.toString()(testfile:123)\n" + "\t\tTestclass.testMethod()(testfile2:42)\n"; assertThat(ExceptionUtilities.getStackTraceAsString(mockException)).isEqualTo(expectedResult); }
### Question: ToServerManagement extends Thread { public static ToServerManagement getInstance() { if( ToServerManagement.sINSTANCE == null){ ToServerManagement.sINSTANCE = new ToServerManagement(); } return ToServerManagement.sINSTANCE; } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer: @Test public void testGetInstance() { ToServerManagement vSaveToCompare = ToServerManagement.getInstance(); assertThat(vSaveToCompare).isInstanceOf(ToServerManagement.class); assertThat(vSaveToCompare).isEqualTo(ToServerManagement.getInstance()); }
### Question: ToServerManagement extends Thread { public void stopManagement(){ synchronized (this) { mManageMessagesToServer = false; } if( isAlive()){ resumeManagement(); while(isAlive()){ try { Thread.sleep( 10 ); } catch ( Exception vException ) { Core.getLogger().error( "Error stopping ToServerManagement.", vException ); } } Core.getLogger().info( "ToServerManagement stopped." ); } } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer: @Test public void testStopManagementWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); mSUT.stopManagement(); assertThat(mSUT.isAlive()).isFalse(); verify(mLoggerMock, never()).info("ToServerManagement stopped."); }
### Question: ToServerManagement extends Thread { public boolean isSendingMessages(){ return isAlive() && (System.currentTimeMillis() - mLastSendMessage.get() ) < 100; } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer: @Test public void testIsSendingMessagesWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); assertThat(mSUT.isSendingMessages()).isFalse(); }
### Question: Movement implements Action { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Movement other = (Movement) obj; if (mLeftWheelVelocity != other.mLeftWheelVelocity) return false; if (mRightWheelVelocity != other.mRightWheelVelocity) return false; return true; } Movement( int aRightWheelVelocity, int aLeftWheelVelocity ); int getmRightWheelVelocity(); int getmLeftWheelVelocity(); @Override String getXMLString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Movement NO_MOVEMENT; }### Answer: @Test public void testEqualsWithDifferentRightWheelVelocity() { Movement movement1 = new Movement(51,50); Movement movement2 = new Movement(49,50); assertThat(movement1.equals(movement2)).isEqualTo(false); } @Test public void testEqualsWithSameValues() { Movement movement1 = new Movement(50,50); Movement movement2 = new Movement(50,50); assertThat(movement1.equals(movement2)).isEqualTo(true); } @Test public void testEqualsWithSameObject() { Movement movement = new Movement(51,50); assertThat(movement.equals(movement)).isEqualTo(true); } @Test public void testEqualsWithObjectIsNull() { Movement movement = new Movement(51,50); assertThat(movement.equals(null)).isEqualTo(false); } @Test public void testEqualsWithDifferentClass() { Movement movement = new Movement(51,50); assertThat(movement.equals(new Integer(12))).isEqualTo(false); } @Test public void testEqualsWithDifferentLeftWheelVelocity() { Movement movement1 = new Movement(51,50); Movement movement2 = new Movement(51,49); assertThat(movement1.equals(movement2)).isEqualTo(false); }
### Question: RawWorldData implements WorldData { public void setBallPosition(BallPosition ballPos){ mBallPosition = ballPos != null ? ballPos : new BallPosition(); } static RawWorldData createRawWorldDataFromXML( String aXMLData ); @XmlTransient double getPlayTime(); @XmlTransient PlayMode getPlayMode(); @XmlTransient Score getScore(); @XmlTransient int getAgentId(); @XmlTransient String getAgentNickname(); @XmlTransient Boolean getAgentStatus(); @XmlTransient int getMaxNumberOfAgents(); @XmlTransient BallPosition getBallPosition(); @XmlTransient List<FellowPlayer> getListOfTeamMates(); @XmlTransient List<FellowPlayer> getListOfOpponents(); @XmlTransient ReferencePoint getCenterLineBottom(); @XmlTransient ReferencePoint getYellowFieldCornerBottom(); @XmlTransient ReferencePoint getYellowPenaltyAreaFrontBottom(); @XmlTransient ReferencePoint getYellowGoalCornerBottom(); @XmlTransient ReferencePoint getYellowGoalAreaFrontBottom(); @XmlTransient ReferencePoint getBlueFieldCornerBottom(); @XmlTransient ReferencePoint getBluePenaltyAreaFrontBottom(); @XmlTransient ReferencePoint getBlueGoalCornerBottom(); @XmlTransient ReferencePoint getBlueGoalAreaFrontBottom(); @XmlTransient ReferencePoint getFieldCenter(); @XmlTransient ReferencePoint getCenterLineTop(); @XmlTransient ReferencePoint getYellowFieldCornerTop(); @XmlTransient ReferencePoint getYellowPenaltyAreaFrontTop(); @XmlTransient ReferencePoint getYellowGoalCornerTop(); @XmlTransient ReferencePoint getYellowGoalAreaFrontTop(); @XmlTransient ReferencePoint getBlueFieldCornerTop(); @XmlTransient ReferencePoint getBluePenaltyAreaFrontTop(); @XmlTransient ReferencePoint getBlueGoalCornerTop(); @XmlTransient ReferencePoint getBlueGoalAreaFrontTop(); @XmlTransient void setOpponentPlayer(FellowPlayer player); @XmlTransient void setFellowPlayer(FellowPlayer player); void setBallPosition(BallPosition ballPos); @XmlTransient List<ReferencePoint> getReferencePoints(); ReferencePoint getReferencePoint( ReferencePointName aName ); String toXMLString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void setBallPositionTest() { BallPosition bp = new BallPosition(30, 40, true); rawWorldDataSpy.setBallPosition(bp); assert(rawWorldDataSpy.getBallPosition().equals(bp)); }
### Question: RawWorldData implements WorldData { @XmlTransient public List<ReferencePoint> getReferencePoints() { return mReferencePoints; } static RawWorldData createRawWorldDataFromXML( String aXMLData ); @XmlTransient double getPlayTime(); @XmlTransient PlayMode getPlayMode(); @XmlTransient Score getScore(); @XmlTransient int getAgentId(); @XmlTransient String getAgentNickname(); @XmlTransient Boolean getAgentStatus(); @XmlTransient int getMaxNumberOfAgents(); @XmlTransient BallPosition getBallPosition(); @XmlTransient List<FellowPlayer> getListOfTeamMates(); @XmlTransient List<FellowPlayer> getListOfOpponents(); @XmlTransient ReferencePoint getCenterLineBottom(); @XmlTransient ReferencePoint getYellowFieldCornerBottom(); @XmlTransient ReferencePoint getYellowPenaltyAreaFrontBottom(); @XmlTransient ReferencePoint getYellowGoalCornerBottom(); @XmlTransient ReferencePoint getYellowGoalAreaFrontBottom(); @XmlTransient ReferencePoint getBlueFieldCornerBottom(); @XmlTransient ReferencePoint getBluePenaltyAreaFrontBottom(); @XmlTransient ReferencePoint getBlueGoalCornerBottom(); @XmlTransient ReferencePoint getBlueGoalAreaFrontBottom(); @XmlTransient ReferencePoint getFieldCenter(); @XmlTransient ReferencePoint getCenterLineTop(); @XmlTransient ReferencePoint getYellowFieldCornerTop(); @XmlTransient ReferencePoint getYellowPenaltyAreaFrontTop(); @XmlTransient ReferencePoint getYellowGoalCornerTop(); @XmlTransient ReferencePoint getYellowGoalAreaFrontTop(); @XmlTransient ReferencePoint getBlueFieldCornerTop(); @XmlTransient ReferencePoint getBluePenaltyAreaFrontTop(); @XmlTransient ReferencePoint getBlueGoalCornerTop(); @XmlTransient ReferencePoint getBlueGoalAreaFrontTop(); @XmlTransient void setOpponentPlayer(FellowPlayer player); @XmlTransient void setFellowPlayer(FellowPlayer player); void setBallPosition(BallPosition ballPos); @XmlTransient List<ReferencePoint> getReferencePoints(); ReferencePoint getReferencePoint( ReferencePointName aName ); String toXMLString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void getReferencePointsTest() { List<ReferencePoint> refPoints = rawWorldData.getReferencePoints(); assert(refPoints==null); }
### Question: RawWorldData implements WorldData { public ReferencePoint getReferencePoint( ReferencePointName aName ) { if( mReferencePoints.get( aName.getPosition() ).getPointName() == aName ){ return mReferencePoints.get( aName.getPosition() ); } for( ReferencePoint vPoint : mReferencePoints ){ if( vPoint.getPointName() == aName ){ return vPoint; } } return null; } static RawWorldData createRawWorldDataFromXML( String aXMLData ); @XmlTransient double getPlayTime(); @XmlTransient PlayMode getPlayMode(); @XmlTransient Score getScore(); @XmlTransient int getAgentId(); @XmlTransient String getAgentNickname(); @XmlTransient Boolean getAgentStatus(); @XmlTransient int getMaxNumberOfAgents(); @XmlTransient BallPosition getBallPosition(); @XmlTransient List<FellowPlayer> getListOfTeamMates(); @XmlTransient List<FellowPlayer> getListOfOpponents(); @XmlTransient ReferencePoint getCenterLineBottom(); @XmlTransient ReferencePoint getYellowFieldCornerBottom(); @XmlTransient ReferencePoint getYellowPenaltyAreaFrontBottom(); @XmlTransient ReferencePoint getYellowGoalCornerBottom(); @XmlTransient ReferencePoint getYellowGoalAreaFrontBottom(); @XmlTransient ReferencePoint getBlueFieldCornerBottom(); @XmlTransient ReferencePoint getBluePenaltyAreaFrontBottom(); @XmlTransient ReferencePoint getBlueGoalCornerBottom(); @XmlTransient ReferencePoint getBlueGoalAreaFrontBottom(); @XmlTransient ReferencePoint getFieldCenter(); @XmlTransient ReferencePoint getCenterLineTop(); @XmlTransient ReferencePoint getYellowFieldCornerTop(); @XmlTransient ReferencePoint getYellowPenaltyAreaFrontTop(); @XmlTransient ReferencePoint getYellowGoalCornerTop(); @XmlTransient ReferencePoint getYellowGoalAreaFrontTop(); @XmlTransient ReferencePoint getBlueFieldCornerTop(); @XmlTransient ReferencePoint getBluePenaltyAreaFrontTop(); @XmlTransient ReferencePoint getBlueGoalCornerTop(); @XmlTransient ReferencePoint getBlueGoalAreaFrontTop(); @XmlTransient void setOpponentPlayer(FellowPlayer player); @XmlTransient void setFellowPlayer(FellowPlayer player); void setBallPosition(BallPosition ballPos); @XmlTransient List<ReferencePoint> getReferencePoints(); ReferencePoint getReferencePoint( ReferencePointName aName ); String toXMLString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void getReferencePointTestNA() { ReferencePoint mockedBottomCenter = mock(ReferencePoint.class); rawWorldData.mReferencePoints = new ArrayList<>(); rawWorldData.mReferencePoints.add(0, new ReferencePoint()); rawWorldData.mReferencePoints.add(0, new ReferencePoint()); when(mockedBottomCenter.getPointName()).thenReturn((ReferencePointName.CenterLineBottom)); ReferencePoint noRefPoint = rawWorldData.getReferencePoint(ReferencePointName.CenterLineBottom); assertThat(noRefPoint).isNull(); }
### Question: BotInformation implements Serializable { public synchronized String toString() { String vBotInformationString = "Bot " + getBotname() + "(" + getRcId() + "/" + getVtId() + ")\n"; vBotInformationString += "with Address: " + getBotIP().toString() + " Port: " + getBotPort(); vBotInformationString += getReconnect()?" (Reconnected)":"" + "\n"; vBotInformationString += "on Team " + getTeamname() + "(" + getTeam().toString() + ")" + " Port: " + getServerPort() + "\n"; vBotInformationString += "on Server: " + getServerIP().toString() + "\n"; vBotInformationString += "with Values:\n"; for ( GamevalueNames aGamevalueName : GamevalueNames.values() ) { vBotInformationString += aGamevalueName.toString() + " = " + aGamevalueName.getValue() + "\n"; } vBotInformationString += "The AI " + getAIClassname() + " starts from " + getAIArchive() + " with parameters: \n"; vBotInformationString += getAIArgs() + "\n"; vBotInformationString += getBotMemory()!=null?getBotMemory().toString() + "\n":""; return vBotInformationString; } BotInformation(); static synchronized Logger getLogger(); synchronized String getBotname(); synchronized int getRcId(); synchronized int getVtId(); synchronized InetAddress getBotIP(); synchronized int getBotPort(); synchronized InetAddress getServerIP(); synchronized int getServerPort(); synchronized Teams getTeam(); synchronized String getTeamname(); synchronized float getGamevalue( GamevalueNames aGamevalueName ); synchronized boolean getReconnect(); synchronized String getAIArgs(); synchronized void setAIArgs( String aAiArgs ); synchronized String getAIArchive(); synchronized void setAIArchive( String aAIArchive ); synchronized String getAIClassname(); synchronized Object getBotMemory(); synchronized void setBotMemory( Object aBotMemory ); synchronized void setAIClassname( String aAIClassname ); synchronized void setReconnect( boolean aReconnect); synchronized void setGamevalue( GamevalueNames aGamevalueName, float aGamevalue ); synchronized void setTeamname( String aTeamname ); synchronized void setTeam( Teams aTeam ); synchronized void setServerPort( int aServerPort ); synchronized void setServerIP( InetAddress aServerIP ); synchronized void setBotPort( int aBotPort ); synchronized void setBotIP( InetAddress aBotIP ); synchronized void setVtId( int aVtId ); synchronized void setRcId( int aRcId ); synchronized void setBotname( String aBotname ); synchronized String toString(); }### Answer: @Test public void testGetAllGamevalueNamesAsAString() { String gvString = new String(); for ( BotInformation.GamevalueNames vGamevalueName : BotInformation.GamevalueNames.values() ) { gvString += vGamevalueName.toString() + " "; } assertThat(BotInformation.GamevalueNames.getAllGamevalueNamesAsAString()).isEqualTo(gvString); } @Test public void testGetGamevalueNamesAsStringArray() { int i = 0; String[] gvStrings= new String[BotInformation.GamevalueNames.values().length]; for ( BotInformation.GamevalueNames vGamevalueName : BotInformation.GamevalueNames.values() ) { gvStrings[i] = vGamevalueName.toString(); i++; } assertThat(BotInformation.GamevalueNames.getGamevalueNamesAsStringArray()).isEqualTo(gvStrings); }
### Question: FellowPlayer extends ReferencePoint { @Override void setPointName( ReferencePointName aPointName ) { super.setPointName( ReferencePointName.Player ); mId = IDCOUNTER++; } FellowPlayer(); FellowPlayer(int aId, String aNickname, Boolean aStatus, double aDistanceToPlayer, double aAngleToPlayer, double aOrientation); @XmlElement(name="id") int getId(); @XmlTransient String getNickname(); @XmlTransient Boolean getStatus(); @XmlTransient double getDistanceToPlayer(); @XmlTransient double getAngleToPlayer(); @XmlTransient double getOrientation(); @Override String toString(); @Override boolean equals(Object obj); }### Answer: @Test public void setPointNameText() { FellowPlayer fellowPlayer = new FellowPlayer(); int IDCountBefore = FellowPlayer.IDCOUNTER ; fellowPlayer.setPointName(ReferencePointName.Ball); int IDCountAfter = FellowPlayer.IDCOUNTER; assert(IDCountBefore+1==IDCountAfter); }
### Question: ReferencePoint { public void setXOfPoint( double aXValue ) { mX = aXValue; set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetXOfPoint() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.setXOfPoint(10); assertThat(referencePoint.getXOfPoint()).isCloseTo(10, Percentage.withPercentage(1)); }
### Question: ReferencePoint { public void setYOfPoint( double aYValue ) { mY = aYValue; set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testSetYOfPoint() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.setYOfPoint(10); assertThat(referencePoint.getYOfPoint()).isCloseTo(10, Percentage.withPercentage(1)); }
### Question: ReferencePoint { public ReferencePoint copy () { return new ReferencePoint( this ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testCopy() { ReferencePoint referencePoint = new ReferencePoint(10,15,false); ReferencePoint copyOfReferencePoint = referencePoint.copy(); assertThat(copyOfReferencePoint).isNotNull(); assertThat(copyOfReferencePoint).isInstanceOf(ReferencePoint.class); assertThat(copyOfReferencePoint.getXOfPoint()).isCloseTo(10, Percentage.withPercentage(1)); assertThat(copyOfReferencePoint.getYOfPoint()).isCloseTo(15, Percentage.withPercentage(1)); }
### Question: ReferencePoint { public ReferencePoint set ( ReferencePoint aReferencePoint ) { mDistanceToPoint = aReferencePoint.getDistanceToPoint(); mAngleToPoint = aReferencePoint.getAngleToPoint(); mX = aReferencePoint.getXOfPoint(); mY = aReferencePoint.getYOfPoint(); mPointName = ReferencePointName.NoFixedName; return this; } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test(expected = IllegalArgumentException.class) public void testSetWithPolarcoordinatesWithNegativeDistance() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.set(-5,25,true); } @Test(expected = IllegalArgumentException.class) public void testSetWithPolarcoordinatesWithToSmallAngle() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.set(13,-190,true); } @Test(expected = IllegalArgumentException.class) public void testSetWithPolarcoordinatesWithToBigAngle() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.set(13,190,true); }
### Question: ReferencePoint { public ReferencePoint add( ReferencePoint aReferencePoint ) { mX += aReferencePoint.mX; mY += aReferencePoint.mY; return set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testAdd() { ReferencePoint referencePoint = new ReferencePoint(50,20,false); ReferencePoint plusReferencePoint = new ReferencePoint(10,10, false); referencePoint.add(plusReferencePoint); assertThat(referencePoint.getXOfPoint()).isCloseTo(60,Percentage.withPercentage(1)); assertThat(referencePoint.getYOfPoint()).isCloseTo(30, Percentage.withPercentage(1)); }
### Question: ReferencePoint { public ReferencePoint multiply( double scalar ) { mX *= scalar; mY *= scalar; return set( mX, mY, false ); } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testMultiply() { ReferencePoint referencePoint = new ReferencePoint(50,20, false); referencePoint.multiply(2.0); assertThat(referencePoint.getXOfPoint()).isCloseTo(100, Percentage.withPercentage(1)); assertThat(referencePoint.getYOfPoint()).isCloseTo(40,Percentage.withPercentage(1)); }
### Question: Kick implements Action { @Override public String getXMLString() { return "<command> <kick> <angle>" + mAngle + "</angle> <force>" + mForce + "</force> </kick> </command>"; } Kick( double aAngle, float aForce); @Override String getXMLString(); double getAngle(); float getForce(); }### Answer: @Test public void getXMLString() throws Exception { Kick kick = new Kick(90.1, (float) 21.0); assertThat(kick.getXMLString()).isEqualTo("<command> <kick> <angle>90.1</angle> <force>21.0</force> </kick> </command>"); }
### Question: ReferencePoint { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ReferencePoint other = (ReferencePoint) obj; if (Double.doubleToLongBits(mAngleToPoint) != Double.doubleToLongBits(other.mAngleToPoint)) return false; if (Double.doubleToLongBits(mDistanceToPoint) != Double.doubleToLongBits(other.mDistanceToPoint)) return false; if (mPointName != other.mPointName) return false; if (Double.doubleToLongBits(mX) != Double.doubleToLongBits(other.mX)) return false; if (Double.doubleToLongBits(mY) != Double.doubleToLongBits(other.mY)) return false; return true; } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testEqualsSameObject() { ReferencePoint referencePoint = new ReferencePoint(); Boolean result = referencePoint.equals(referencePoint); assertThat(result).isEqualTo(true); } @Test public void testEqualsObjectIsNull() { ReferencePoint referencePoint = new ReferencePoint(); Boolean result = referencePoint.equals(null); assertThat(result).isEqualTo(false); } @Test public void testEqualsObjectIsOtherClass() { ReferencePoint referencePoint = new ReferencePoint(); Boolean result = referencePoint.equals(new Double(1.2)); assertThat(result).isEqualTo(false); }
### Question: Movement implements Action { @Override public String getXMLString() { return "<command> <wheel_velocities> <right>" + mRightWheelVelocity + "</right> <left>" + mLeftWheelVelocity + "</left> </wheel_velocities> </command>"; } Movement( int aRightWheelVelocity, int aLeftWheelVelocity ); int getmRightWheelVelocity(); int getmLeftWheelVelocity(); @Override String getXMLString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Movement NO_MOVEMENT; }### Answer: @Test public void testGetXMLString() { Movement movement = new Movement(51,50); assertThat(movement.getXMLString()).isEqualTo("<command> <wheel_velocities> <right>51</right> <left>50</left> </wheel_velocities> </command>"); }
### Question: ReferencePoint { @Override public String toString() { return "ReferencePoint [mPointName=" + mPointName + ", mDistanceToPoint=" + mDistanceToPoint + ", mAngleToPoint=" + mAngleToPoint + ", mX=" + mX + ", mY=" + mY + "]"; } ReferencePoint( ); @Deprecated ReferencePoint( double aDistanceToPoint, double aAngleToPoint ); ReferencePoint( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint( ReferencePoint aReferencePoint ); @XmlElement(name="id") ReferencePointName getPointName(); @XmlElement(name="dist") double getDistanceToPoint(); void setDistanceToPoint( double aDistance ); @XmlElement(name="angle") double getAngleToPoint(); void setAngleToPoint( double aAngle ); @XmlElement(name="xvalue") double getXOfPoint(); void setXOfPoint( double aXValue ); @XmlElement(name="yvalue") double getYOfPoint(); void setYOfPoint( double aYValue ); ReferencePoint copy(); ReferencePoint set( ReferencePoint aReferencePoint ); ReferencePoint set( double aFirstValue, double aSecondValue, boolean aPolarcoordinates ); ReferencePoint sub( double aScalar ); ReferencePoint sub( ReferencePoint aReferencePoint ); ReferencePoint add( ReferencePoint aReferencePoint ); ReferencePoint multiply( double scalar ); boolean epsilonEquals( ReferencePoint aReferencePoint, double aEpsilon ); boolean epsilonEquals( double aX, double aY, double aEpsilon ); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void testToString() { ReferencePoint referencePoint = new ReferencePoint(); referencePoint.setPointName(ReferencePointName.NoFixedName); double distance = 1.41421356; double angle = 45.0; referencePoint.setDistanceToPoint(distance); referencePoint.setAngleToPoint(angle); double x = referencePoint.getDistanceToPoint() * Math.cos(Math.toRadians(referencePoint.getAngleToPoint())); double y = referencePoint.getDistanceToPoint() * Math.sin(Math.toRadians(referencePoint.getAngleToPoint())); String result = referencePoint.toString(); assertThat(result).isEqualTo((String) "ReferencePoint [mPointName=" + ReferencePointName.NoFixedName + ", mDistanceToPoint=" + distance + ", mAngleToPoint=" + angle + ", mX=" + x + ", mY=" + y + "]" ); }
### Question: ObjectFactory { public RawWorldData createRawWorldData() { return new RawWorldData(); } RawWorldData createRawWorldData(); }### Answer: @Test public void testCreateRawWorldData() { ObjectFactory objectFactory = new ObjectFactory(); assertThat(objectFactory.createRawWorldData()).isInstanceOf(RawWorldData.class); }
### Question: InitialConnectionData implements Action { public InitialConnectionData( BotInformation aBot ){ mConnection.type = "Client"; mConnection.protocol_version = 1.0; mConnection.nickname = aBot.getBotname(); mConnection.rc_id = aBot.getRcId(); mConnection.vt_id = aBot.getVtId(); } InitialConnectionData( BotInformation aBot ); @Override String getXMLString(); }### Answer: @Test public void testInitialConnectionData() { fail("Not yet implemented"); }
### Question: InitialConnectionData implements Action { @Override public String getXMLString() { StringWriter vXMLDataStream = new StringWriter(); JAXB.marshal( mConnection, vXMLDataStream ); String vXMLDataString = vXMLDataStream.toString(); vXMLDataString = vXMLDataString.substring( vXMLDataString.indexOf('>') + 2 ); return vXMLDataString; } InitialConnectionData( BotInformation aBot ); @Override String getXMLString(); }### Answer: @Test public void testGetXMLString() { InitialConnectionData initialConnectionData = new InitialConnectionData(botInformationMock); fail("Not yet implemented"); }
### Question: NetworkCommunication { public void sendDatagramm( String aData ) throws IOException { mDataPaket.setData( aData.getBytes() ); mToServerSocket.send( mDataPaket ); } NetworkCommunication( InetAddress aServerAddress, int aServerPort ); NetworkCommunication( InetAddress aServerAddress, int aServerPort, int aClientPort); void sendDatagramm( String aData ); String getDatagramm( int aWaitTime ); void closeConnection(); boolean isConnected(); DatagramPacket getDataPaket(); DatagramSocket getToServerSocket(); void setToServerSocket(DatagramSocket mToServerSocket); void setDataPaket(DatagramPacket mDataPaket); String toString(); }### Answer: @Test public void testSendDatagramm() { }
### Question: CommandLineOptions { static boolean parseCommandLineArguments( String[] aArguments ) { Core.getLogger().trace( "Parsing commandline." ); CommandLineOptions commandLineOptions = new CommandLineOptions(); try { CommandLine commandLine = new CommandLine(commandLineOptions) .registerConverter(BotInformation.Teams.class, new TeamConverter()); commandLine.parse(aArguments); if (!commandLineOptions.reconnect && commandLineOptions.botPort != -1) throw new CommandLine.MissingParameterException(commandLine, "Wenn der Botport gesetzt wurde, muss auch reconnect gesetzt werden!"); commandLineOptions.parseAndShowHelp(); commandLineOptions.setOptions(); return commandLineOptions.remoteStart; } catch (CommandLine.ParameterException e) { Core.getLogger().error(e); CommandLine.usage(commandLineOptions, System.out, CommandLine.Help.Ansi.AUTO); System.exit( 0 ); } catch (UnknownHostException e) { Core.getLogger().error(e); } Core.getInstance().close(); return false; } }### Answer: @Test public void testParseCommandLineArgumentsWithNoExceptionsWithRemoteStart() { String[] args = {"-bn","3","-tn","Northern Stars","-t","blau","-ids","13","-s","localhost:3310","-aiarc","../mrbotkiexample/bin/exampleai/brain","-aicl","exampleai.brain.Striker","-aiarg","0","-rs"}; boolean result = CommandLineOptions.parseCommandLineArguments(args); assertThat(result).isTrue(); } @Test public void testParseCommandLineArgumentsWithNoExceptionsWithoutRemoteStart() { String[] args = {"-bn","3","-tn","Northern Stars","-t","blau","-ids","13","-s","localhost:3310","-aiarc","../mrbotkiexample/bin/exampleai/brain","-aicl","exampleai.brain.Striker","-aiarg","0"}; boolean result = CommandLineOptions.parseCommandLineArguments(args); assertThat(result).isFalse(); } @Test public void testParseCommandLineArgumentsWithNoExceptionsWithMissingArgument() { String[] args = {"-bn","3","-tn","Northern Stars","-t","blau","-ids","13","-s","localhost:3310","-aiarc","../mrbotkiexample/bin/exampleai/brain","-aicl","exampleai.brain.Striker","-aiarg","0"}; boolean result = CommandLineOptions.parseCommandLineArguments(args); assertThat(result).isFalse(); }
### Question: Movement implements Action { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mLeftWheelVelocity; result = prime * result + mRightWheelVelocity; return result; } Movement( int aRightWheelVelocity, int aLeftWheelVelocity ); int getmRightWheelVelocity(); int getmLeftWheelVelocity(); @Override String getXMLString(); @Override int hashCode(); @Override boolean equals(Object obj); static final Movement NO_MOVEMENT; }### Answer: @Test public void testHashCode() { Movement movement = new Movement(51,50); assertThat(movement.hashCode()).isEqualTo(2562); }
### Question: CommandLineOptions { private void setOptions() throws UnknownHostException { BotInformation botInformation = Core.getInstance().getBotinformation(); botInformation.setAIClassname(this.aiClassname); botInformation.setAIArchive(this.aiArchive); botInformation.setAIArgs(Arrays.toString(this.aiArguments)); botInformation.setTeamname(this.teamName); botInformation.setTeam(this.team); botInformation.setBotPort(this.botPort); botInformation.setServerIP(InetAddress.getByName(this.serverPortAndAddress[0])); botInformation.setServerPort(Integer.parseInt(this.serverPortAndAddress[1])); if(this.rcAndVtIdOption.length <= 1) { botInformation.setRcId(rcAndVtIdOption[0]); botInformation.setVtId(rcAndVtIdOption[0]); } else { botInformation.setRcId(rcAndVtIdOption[0]); botInformation.setVtId(rcAndVtIdOption[1]); } botInformation.setBotname(botname); } }### Answer: @Test public void testSetOptions() { String[] args = {"-bn","3","-tn","Northern Stars","-t","blau","-ids","13","-s","localhost:3310","-aiarc","../mrbotkiexample/bin/exampleai/brain","-aicl","exampleai.brain.Striker","-aiarg","0"}; CommandLineOptions.parseCommandLineArguments(args); BotInformation botInformation = Core.getInstance().getBotinformation(); assertThat(botInformation.getAIArchive()).isEqualTo("../mrbotkiexample/bin/exampleai/brain"); assertThat(botInformation.getAIArgs()).isEqualTo("[0]"); assertThat(botInformation.getAIClassname()).isEqualTo("exampleai.brain.Striker"); try { assertThat(botInformation.getServerIP()).isEqualTo(InetAddress.getByName("localhost")); } catch (UnknownHostException e) { e.printStackTrace(); } assertThat(botInformation.getServerPort()).isEqualTo(3310); assertThat(botInformation.getRcId()).isEqualTo(13); assertThat(botInformation.getTeam()).isEqualTo(BotInformation.Teams.Blue); assertThat(botInformation.getTeamname()).isEqualTo("Northern Stars"); assertThat(botInformation.getBotname()).isEqualTo("3"); }
### Question: TeamConverter implements CommandLine.ITypeConverter<BotInformation.Teams> { @Override public BotInformation.Teams convert(String value) throws Exception { if (value == "gelb" || value == "yellow" || value == "g" || value == "y") return Yellow; else if (value == "blau" || value == "blue" || value == "b") return Blue; else return NotSpecified; } @Override BotInformation.Teams convert(String value); }### Answer: @Test public void testConvertWithValueIsGelb() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("gelb"); assertThat(result).isEqualTo(BotInformation.Teams.Yellow); } @Test public void testConvertWithValueIsYellow() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("yellow"); assertThat(result).isEqualTo(BotInformation.Teams.Yellow); } @Test public void testConvertWithValueIsG() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("g"); assertThat(result).isEqualTo(BotInformation.Teams.Yellow); } @Test public void testConvertWithValueIsY() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("y"); assertThat(result).isEqualTo(BotInformation.Teams.Yellow); } @Test public void testConvertWithValueIsBlau() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("blau"); assertThat(result).isEqualTo(BotInformation.Teams.Blue); } @Test public void testConvertWithValueIsBlue() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("blue"); assertThat(result).isEqualTo(BotInformation.Teams.Blue); } @Test public void testConvertWithValueIsB() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("b"); assertThat(result).isEqualTo(BotInformation.Teams.Blue); } @Test public void testConvertWithValueIsSomething() throws Exception { TeamConverter teamConverter = new TeamConverter(); BotInformation.Teams result = teamConverter.convert("something"); assertThat(result).isEqualTo(BotInformation.Teams.NotSpecified); }
### Question: Main { public static void main( String[] aCommandline ) { System.setProperty("Bot", ManagementFactory.getRuntimeMXBean().getName() + "" ); Core.getLogger().info("Starting Bot(" + ManagementFactory.getRuntimeMXBean().getName() + ")" ); StringBuilder vParameters = new StringBuilder(); for ( String vParameter: aCommandline) { vParameters.append(vParameter).append(" "); } Core.getLogger().info("Parameters: " + vParameters.toString()); try { Core.getInstance().startBot( aCommandline ); } catch ( Exception e ) { Core.getLogger().fatal( "Fatal error! Bot terminates. ", e ); } } static void main( String[] aCommandline ); }### Answer: @Test public void mainWithEmptyCommandline() { String[] vEmptyCommandline = new String[0]; doNothing().when(mCoreMock).startBot(vEmptyCommandline); Main.main(vEmptyCommandline); assertThat(System.getProperty("Bot")).isEqualToIgnoringCase(ManagementFactory.getRuntimeMXBean().getName()); verify(mLoggerMock).info("Starting Bot(" + ManagementFactory.getRuntimeMXBean().getName() + ")" ); verify(mLoggerMock).info("Parameters: "); verify(mCoreMock).startBot(vEmptyCommandline); } @Test public void mainWithACommandline() { String[] vCommandline = new String[5]; vCommandline[0] = "Hello,"; vCommandline[1] = "this"; vCommandline[2] = "is"; vCommandline[3] = "a"; vCommandline[4] = "test."; doNothing().when(mCoreMock).startBot(vCommandline); Main.main(vCommandline); assertThat(System.getProperty("Bot")).isEqualToIgnoringCase(ManagementFactory.getRuntimeMXBean().getName()); verify(mLoggerMock).info("Starting Bot(" + ManagementFactory.getRuntimeMXBean().getName() + ")" ); verify(mLoggerMock).info("Parameters: Hello, this is a test. "); verify(mCoreMock).startBot(vCommandline); } @Test public void mainWithFatalError() { String[] vEmptyCommandline = new String[0]; RuntimeException vTestException = new RuntimeException(); doThrow(vTestException).when(mCoreMock).startBot(vEmptyCommandline); Main.main(vEmptyCommandline); verify(mCoreMock).startBot(vEmptyCommandline); verify(mLoggerMock).fatal( "Fatal error! Bot terminates. ", vTestException ); }
### Question: Core { synchronized public BotInformation getBotinformation() { Core.getLogger().debug( "Retriving Botinformation: \n" + mBotinformation.toString() ); return mBotinformation; } Core(); Core( BotInformation aBotInformation ); static Core getInstance(); static synchronized Logger getLogger(); void close(); void startBot( String[] aCommandline ); @SuppressWarnings("resource") boolean initializeAI(); void disposeAI(); synchronized boolean resumeAI(); synchronized void suspendAI(); boolean startServerConnection( int aNumberOfTries ); void stopServerConnection(); void startServermanagements(); void stopServermanagements(); void resumeServermanagements(); void suspendServermanagements(); synchronized BotInformation getBotinformation(); synchronized void setBotinformation( BotInformation aBotinformation ); synchronized NetworkCommunication getServerConnection(); synchronized ArtificialIntelligence getAI(); }### Answer: @Test public void testConstructorWithBotInformation() { mSUT = new Core(mBotInformationMock); assertThat(mSUT.getBotinformation()).isEqualTo(mBotInformationMock); }
### Question: Core { public static Core getInstance() { if( Core.sINSTANCE == null){ Core.getLogger().trace( "Creating Core-instance." ); Core.sINSTANCE = new Core(); } Core.getLogger().trace( "Retrieving Core-instance." ); return Core.sINSTANCE; } Core(); Core( BotInformation aBotInformation ); static Core getInstance(); static synchronized Logger getLogger(); void close(); void startBot( String[] aCommandline ); @SuppressWarnings("resource") boolean initializeAI(); void disposeAI(); synchronized boolean resumeAI(); synchronized void suspendAI(); boolean startServerConnection( int aNumberOfTries ); void stopServerConnection(); void startServermanagements(); void stopServermanagements(); void resumeServermanagements(); void suspendServermanagements(); synchronized BotInformation getBotinformation(); synchronized void setBotinformation( BotInformation aBotinformation ); synchronized NetworkCommunication getServerConnection(); synchronized ArtificialIntelligence getAI(); }### Answer: @Test public void testGetInstance() { mSUT = Core.getInstance(); assertThat(mSUT).isInstanceOf(Core.class); assertThat(mSUT).isEqualTo(Core.getInstance()); assertThat(mSUT.getBotinformation()).isEqualTo(Core.getInstance().getBotinformation()); }
### Question: Core { public static synchronized Logger getLogger(){ return sBOTCORELOGGER; } Core(); Core( BotInformation aBotInformation ); static Core getInstance(); static synchronized Logger getLogger(); void close(); void startBot( String[] aCommandline ); @SuppressWarnings("resource") boolean initializeAI(); void disposeAI(); synchronized boolean resumeAI(); synchronized void suspendAI(); boolean startServerConnection( int aNumberOfTries ); void stopServerConnection(); void startServermanagements(); void stopServermanagements(); void resumeServermanagements(); void suspendServermanagements(); synchronized BotInformation getBotinformation(); synchronized void setBotinformation( BotInformation aBotinformation ); synchronized NetworkCommunication getServerConnection(); synchronized ArtificialIntelligence getAI(); }### Answer: @Test public void testGetLogger() { Logger vLoggerToTest = Core.getLogger(); assertThat(vLoggerToTest).isInstanceOf(Logger.class); assertThat(vLoggerToTest).isEqualTo(Core.getLogger()); }
### Question: FromServerManagement extends Thread { public void startManagement(){ if( Core.getInstance().getServerConnection() == null ) { throw new NullPointerException( "NetworkCommunication cannot be NULL when starting FromServerManagement." ) ; } else if ( isAlive() ){ throw new IllegalThreadStateException( "FromServerManagement can not be started again." ); } else { synchronized (this) { mManageMessagesFromServer = true; } super.start(); Core.getLogger().info( "FromServerManagement started." ); } } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer: @Test public void testStartManagementWithoutNetworkConnection() { when(mCoreMock.getServerConnection()).thenReturn( null ); try{ mSUT.startManagement(); fail("Expected Nullpointerexception"); } catch( Exception vExpectedException ) { assertThat(vExpectedException).isInstanceOf(NullPointerException.class); assertThat(vExpectedException.getMessage()).isEqualToIgnoringCase( "NetworkCommunication cannot be NULL when starting FromServerManagement." ); } } @Test public void testStartManagementWithNetworkConnectionAndNotAlive() { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( null ); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("FromServerManagement started."); } @Test public void testStartManagementWithNetworkConnectionAndAlive() { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( null ); mSUT.startManagement(); try{ mSUT.startManagement(); fail("Expected IllegalThreadStateException"); } catch( Exception vExpectedException ) { assertThat(vExpectedException).isInstanceOf(IllegalThreadStateException.class); assertThat(vExpectedException.getMessage()).isEqualToIgnoringCase( "FromServerManagement can not be started again." ); } } @Test public void testRecieveMessagesWithAI() throws Exception { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( mArtificialIntelligenceMock ); WorldData vTestData = RawWorldData.createRawWorldDataFromXML("<rawWorldData><time>0</time><agent_id>20</agent_id><nickname>TestBot</nickname><status>found</status></rawWorldData>"); doReturn(((RawWorldData)vTestData).toXMLString()).when(mNetworkCommunicationMock).getDatagramm(1000); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); await().atMost(2, SECONDS).untilAsserted(()->verify(mArtificialIntelligenceMock, atLeast(1)).putWorldState(vTestData)); } @Test public void testLoseServerConnectionWhileRecievingMessages() throws Exception { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( mArtificialIntelligenceMock ); doReturn(new RawWorldData().toXMLString()).when(mNetworkCommunicationMock).getDatagramm(1000); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); when(mCoreMock.getServerConnection()).thenReturn( null ); assertThat(mSUT.isAlive()).isTrue(); await().atMost(2, SECONDS).untilAsserted(()->verify(mLoggerMock, atLeast(1)).debug( "NetworkCommunication cannot be NULL when running FromServerManagement." )); }
### Question: FromServerManagement extends Thread { @Override public void start(){ startManagement(); } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer: @Test public void testStartWithoutNetworkConnection() { when(mCoreMock.getServerConnection()).thenReturn( null ); try{ mSUT.start(); fail("Expected Nullpointerexception"); } catch( Exception vExpectedException ) { assertThat(vExpectedException).isInstanceOf(NullPointerException.class); assertThat(vExpectedException.getMessage()).isEqualToIgnoringCase( "NetworkCommunication cannot be NULL when starting FromServerManagement." ); } } @Test public void testStartWithNetworkConnectionAndNotAlive() { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( null ); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("FromServerManagement started."); }
### Question: FromServerManagement extends Thread { public static FromServerManagement getInstance() { if( FromServerManagement.sINSTANCE == null){ FromServerManagement.sINSTANCE = new FromServerManagement(); } return FromServerManagement.sINSTANCE; } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer: @Test public void testGetInstance() { FromServerManagement vSaveToCompare = FromServerManagement.getInstance(); assertThat(vSaveToCompare).isInstanceOf(FromServerManagement.class); assertThat(vSaveToCompare).isEqualTo(FromServerManagement.getInstance()); }
### Question: FromServerManagement extends Thread { public void stopManagement(){ synchronized (this) { mManageMessagesFromServer = false; } if( isAlive()){ mSuspended = false; while(isAlive()){ try { Thread.sleep( 10 ); } catch ( Exception vException ) { Core.getLogger().error( "Error stopping FromServerManagement.", vException ); } } Core.getLogger().info( "FromServerManagement stopped." ); } } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer: @Test public void testStopManagementWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); mSUT.stopManagement(); assertThat(mSUT.isAlive()).isFalse(); verify(mLoggerMock, never()).info("FromServerManagement stopped."); }
### Question: FromServerManagement extends Thread { public boolean isReceivingMessages(){ return isAlive() && (System.currentTimeMillis() - mLastReceivedMessage.get()) < 100; } FromServerManagement(); static FromServerManagement getInstance(); void close(); void resumeManagement(); void suspendManagement(); boolean isSuspended(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isReceivingMessages(); }### Answer: @Test public void testIsReceivingMessagesWhenNotAlive() { assertThat(mSUT.isAlive()).isFalse(); assertThat(mSUT.isReceivingMessages()).isFalse(); }
### Question: ReloadAiManagement extends Thread { public void startManagement(){ if( !isAlive() ){ mAiActive = true; super.start(); Core.getLogger().info( "RestartAiServerManagement started." ); } } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer: @Test public void testStartManagementWhileNotAlive() { when(mCoreMock.getAI()).thenReturn( null ); assertThat(mSUT.isAlive()).isFalse(); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("RestartAiServerManagement started."); } @Test public void testStartManagementWhileAlive() { when(mCoreMock.getAI()).thenReturn( null ); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock, times(1)).info("RestartAiServerManagement started."); } @Test public void testRunWithoutAI() throws Exception { when(mCoreMock.getAI()).thenReturn( null ); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); } @Test public void testRunWithAIAndNoNeedToRestart() throws Exception { when(mCoreMock.getAI()).thenReturn( mArtificialIntelligenceMock ); when(mArtificialIntelligenceMock.wantRestart()).thenReturn(false); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); await().atMost(2, SECONDS).untilAsserted(()->verify(mArtificialIntelligenceMock, atLeast(2)).wantRestart()); verify(mCoreMock, never()).initializeAI(); verify(mCoreMock, never()).resumeAI(); } @Test public void testRunWithAIAndNeedToRestart() throws Exception { when(mCoreMock.getAI()).thenReturn( mArtificialIntelligenceMock ); when(mArtificialIntelligenceMock.wantRestart()).thenReturn(true).thenReturn(false); mSUT.startManagement(); assertThat(mSUT.isAlive()).isTrue(); await().atMost(2, SECONDS).untilAsserted(()->verify(mArtificialIntelligenceMock, atLeast(2)).wantRestart()); InOrder inOrder = inOrder(mCoreMock); inOrder.verify(mCoreMock).initializeAI(); inOrder.verify(mCoreMock).resumeAI(); }
### Question: ReloadAiManagement extends Thread { @Override public void start(){ startManagement(); } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer: @Test public void testStartWhileNotAlive() { when(mCoreMock.getAI()).thenReturn( null ); assertThat(mSUT.isAlive()).isFalse(); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("RestartAiServerManagement started."); } @Test public void testStartWhileAlive() { when(mCoreMock.getAI()).thenReturn( null ); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock, times(1)).info("RestartAiServerManagement started."); }
### Question: ReloadAiManagement extends Thread { public static ReloadAiManagement getInstance() { if( ReloadAiManagement.sINSTANCE == null){ ReloadAiManagement.sINSTANCE = new ReloadAiManagement(); } return ReloadAiManagement.sINSTANCE; } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer: @Test public void testGetInstance() { ReloadAiManagement vSaveToCompare = ReloadAiManagement.getInstance(); assertThat(vSaveToCompare).isInstanceOf(ReloadAiManagement.class); assertThat(vSaveToCompare).isEqualTo(ReloadAiManagement.getInstance()); }
### Question: ReloadAiManagement extends Thread { public void stopManagement(){ mAiActive = false; if( isAlive()){ Core.getLogger().info( "RestartAiServerManagement stopping." ); while(isAlive()){ try { Thread.sleep( 10 ); } catch ( Exception vException ) { Core.getLogger().error( "Error stopping RestartAiServerManagement.", vException ); } } Core.getLogger().info( "RestartAiServerManagement stopped." ); } } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer: @Test public void testStopManagementWhenNotAlive() { when(mCoreMock.getAI()).thenReturn( null ); assertThat(mSUT.isAlive()).isFalse(); mSUT.stopManagement(); assertThat(mSUT.isAlive()).isFalse(); verify(mLoggerMock, never()).info("RestartAiServerManagement stopped."); }
### Question: ReloadAiManagement extends Thread { @Override public void run(){ while( mAiActive ){ try { if(Core.getInstance().getAI() != null && Core.getInstance().getAI().wantRestart()){ Core.getInstance().initializeAI(); Core.getInstance().resumeAI(); Thread.sleep( 500 ); } Thread.sleep( 50 ); } catch ( Exception vException ) { Core.getLogger().error( "Error while waiting in RestartAiServerManagement.", vException ); } } } ReloadAiManagement(); static ReloadAiManagement getInstance(); void close(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); }### Answer: @Test public void testRunWithoutStart() throws Exception { when(mCoreMock.getAI()).thenReturn( mArtificialIntelligenceMock ); assertThat(mSUT.isAlive()).isFalse(); mSUT.run(); assertThat(mSUT.isAlive()).isFalse(); verifyZeroInteractions(mArtificialIntelligenceMock); }
### Question: ToServerManagement extends Thread { @Override public void start(){ this.startManagement(); } ToServerManagement(); static ToServerManagement getInstance(); void close(); void resumeManagement(); boolean isSuspended(); void suspendManagement(); @Override void start(); void startManagement(); void stopManagement(); @Override void run(); boolean isSendingMessages(); }### Answer: @Test public void testStartWithoutNetworkConnection() { when(mCoreMock.getServerConnection()).thenReturn( null ); try{ mSUT.start(); fail("Expected Nullpointerexception"); } catch( Exception vExpectedException ) { assertThat(vExpectedException).isInstanceOf(NullPointerException.class); assertThat(vExpectedException.getMessage()).isEqualToIgnoringCase( "NetworkCommunication cannot be NULL when starting ToServerManagement." ); } } @Test public void testStartWithNetworkConnectionAndNotAlive() { when(mCoreMock.getServerConnection()).thenReturn( mNetworkCommunicationMock ); when(mCoreMock.getAI()).thenReturn( null ); mSUT.start(); assertThat(mSUT.isAlive()).isTrue(); verify(mLoggerMock).info("ToServerManagement started."); }
### Question: WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); mappings.add("html", "text/html;charset=utf-8"); mappings.add("json", "text/html;charset=utf-8"); container.setMimeMappings(mappings); setLocationForStaticAssets(container); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && container instanceof UndertowEmbeddedServletContainerFactory) { ((UndertowEmbeddedServletContainerFactory) container) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties, HazelcastInstance hazelcastInstance); @Override void onStartup(ServletContext servletContext); @Override void customize(ConfigurableEmbeddedServletContainer container); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer: @Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); } @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www")); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); if (container.getDocumentRoot() != null) { assertThat(container.getDocumentRoot().getPath()).isEqualTo("target/www"); } Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); }
### Question: ProfileInfoResource { @GetMapping("/profile-info") public ProfileInfoVM getActiveProfiles() { String[] activeProfiles = DefaultProfileUtil.getActiveProfiles(env); return new ProfileInfoVM(activeProfiles, getRibbonEnv(activeProfiles)); } ProfileInfoResource(Environment env, JHipsterProperties jHipsterProperties); @GetMapping("/profile-info") ProfileInfoVM getActiveProfiles(); }### Answer: @Test public void getActiveProfilesTest() throws Exception { MvcResult res = mock.perform(get("/api/profile-info") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andReturn(); assertTrue(res.getResponse().getContentAsString().contains("\"activeProfiles\":[\""+profiles[0]+"\"]")); }
### Question: TokenProvider { public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature."); log.trace("Invalid JWT signature trace: {}", e); } catch (MalformedJwtException e) { log.info("Invalid JWT token."); log.trace("Invalid JWT token trace: {}", e); } catch (ExpiredJwtException e) { log.info("Expired JWT token."); log.trace("Expired JWT token trace: {}", e); } catch (UnsupportedJwtException e) { log.info("Unsupported JWT token."); log.trace("Unsupported JWT token trace: {}", e); } catch (IllegalArgumentException e) { log.info("JWT token compact of handler are invalid."); log.trace("JWT token compact of handler are invalid trace: {}", e); } return false; } TokenProvider(JHipsterProperties jHipsterProperties); @PostConstruct void init(); String createToken(Authentication authentication, Boolean rememberMe); Authentication getAuthentication(String token); boolean validateToken(String authToken); }### Answer: @Test public void testReturnFalseWhenJWTisUnsupported() { String unsupportedToken = createUnsupportedToken(); boolean isTokenValid = tokenProvider.validateToken(unsupportedToken); assertThat(isTokenValid).isEqualTo(false); }
### Question: LogsResource { @GetMapping("/logs") @Timed public List<LoggerVM> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerVM::new) .collect(Collectors.toList()); } @GetMapping("/logs") @Timed List<LoggerVM> getList(); @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed void changeLevel(@RequestBody LoggerVM jsonLogger); }### Answer: @Test public void getListTest() throws Exception { mock.perform(get("/management/logs") .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); }
### Question: LogsResource { @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerVM jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } @GetMapping("/logs") @Timed List<LoggerVM> getList(); @PutMapping("/logs") @ResponseStatus(HttpStatus.NO_CONTENT) @Timed void changeLevel(@RequestBody LoggerVM jsonLogger); }### Answer: @Test public void changeLevelTest() throws Exception { LoggerVM logger = new LoggerVM(); logger.setLevel("ERROR"); logger.setName("ROOT"); mock.perform(put("/management/logs") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(new ObjectMapper().writeValueAsString(logger))) .andExpect(status().isNoContent()); MvcResult res = mock.perform(get("/management/logs") .accept(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andReturn(); assertTrue(res.getResponse().getContentAsString().contains("\"name\":\""+logger.getName() +"\",\"level\":\""+logger.getLevel()+"\"")); }
### Question: SshResource { @GetMapping(value = "/ssh/public_key", produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity<String> eureka() { try { String publicKey = getPublicKey(); if(publicKey != null) return new ResponseEntity<>(publicKey, HttpStatus.OK); } catch (IOException e) { log.warn("SSH public key could not be loaded: {}", e.getMessage()); } return new ResponseEntity<>(HttpStatus.NOT_FOUND); } @GetMapping(value = "/ssh/public_key", produces = MediaType.TEXT_PLAIN_VALUE) @Timed ResponseEntity<String> eureka(); }### Answer: @Test public void eurekaTest() throws Exception { Mockito.doReturn(null).when(ssh).getPublicKey(); mock.perform(get("/api/ssh/public_key")) .andExpect(status().isNotFound()); Mockito.doReturn("key").when(ssh).getPublicKey(); mock.perform(get("/api/ssh/public_key")) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)) .andExpect(content().string("key")) .andExpect(status().isOk()); }
### Question: UserJWTController { @PostMapping("/authenticate") @Timed public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); try { Authentication authentication = this.authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe(); String jwt = tokenProvider.createToken(authentication, rememberMe); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); return ResponseEntity.ok(new JWTToken(jwt)); } catch (AuthenticationException ae) { log.trace("Authentication exception trace: {}", ae); return new ResponseEntity<>(Collections.singletonMap("AuthenticationException", ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED); } } UserJWTController(TokenProvider tokenProvider, AuthenticationManager authenticationManager); @PostMapping("/authenticate") @Timed ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response); }### Answer: @Test public void authorizeTest() throws Exception { LoginVM vm = new LoginVM(); vm.setUsername("admin"); vm.setPassword("admin"); vm.setRememberMe(true); Mockito.doReturn("fakeToken").when(tokenProvider) .createToken(Mockito.any(Authentication.class), Mockito.anyBoolean()); mock.perform(post("/api/authenticate") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL) .content(new ObjectMapper().writeValueAsString(vm))) .andExpect(content().string("{\"id_token\":\"fakeToken\"}")) .andExpect(status().isOk()); Mockito.doThrow(new AuthenticationException(null){}).when(tokenProvider) .createToken(Mockito.any(Authentication.class), Mockito.anyBoolean()); MvcResult res = mock.perform(post("/api/authenticate") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL) .content("{\"username\":\"fakeUsername\",\"password\":\"fakePassword\",\"rememberMe\":false}")) .andExpect(status().isUnauthorized()) .andReturn(); assertTrue(res.getResponse().getContentAsString().startsWith("{\"AuthenticationException\"")); vm.setUsername("badcred"); vm.setPassword("badcred"); Mockito.doThrow(new BadCredentialsException("Bad credentials")).when(authenticationManager) .authenticate(new UsernamePasswordAuthenticationToken(vm.getUsername(), vm.getPassword())); mock.perform(post("/api/authenticate") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL) .content(new ObjectMapper().writeValueAsString(vm))) .andExpect(status().isUnauthorized()) .andExpect(content().string("{\"AuthenticationException\":\"Bad credentials\"}")); }
### Question: ExceptionTranslator { @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer: @Test public void processValidationErrorTest() throws Exception { UserJWTController control = new UserJWTController(null, null); MockMvc jwtMock = MockMvcBuilders.standaloneSetup(control) .setControllerAdvice(new ExceptionTranslator()) .build(); MvcResult res = jwtMock.perform(post("/api/authenticate") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL) .content("{\"username\":\"fakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLong" + "\",\"password\":\"fakePassword\",\"rememberMe\":false}")) .andExpect(status().isBadRequest()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(MethodArgumentNotValidException.class)); }
### Question: ExceptionTranslator { @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex) { return ex.getErrorVM(); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer: @Test public void processParameterizedValidationErrorTest() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new CustomParameterizedException(null)); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isBadRequest()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(CustomParameterizedException.class)); }
### Question: ExceptionTranslator { @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public ErrorVM processAccessDeniedException(AccessDeniedException e) { return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer: @Test public void processAccessDeniedExceptionTest() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new AccessDeniedException(null)); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isForbidden()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(AccessDeniedException.class)); }
### Question: ExceptionTranslator { @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { return new ErrorVM(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer: @Test public void processMethodNotSupportedExceptionTest() throws Exception { MvcResult res = mock.perform(post("/api/account") .content("{\"testFakeParam\"}")) .andExpect(status().isMethodNotAllowed()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(HttpRequestMethodNotSupportedException.class)); }
### Question: ExceptionTranslator { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) { BodyBuilder builder; ErrorVM errorVM; ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class); if (responseStatus != null) { builder = ResponseEntity.status(responseStatus.value()); errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason()); } else { builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error"); } return builder.body(errorVM); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ErrorVM processValidationError(MethodArgumentNotValidException ex); @ExceptionHandler(CustomParameterizedException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ParameterizedErrorVM processParameterizedValidationError(CustomParameterizedException ex); @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody ErrorVM processAccessDeniedException(AccessDeniedException e); @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception); @ExceptionHandler(Exception.class) ResponseEntity<ErrorVM> processRuntimeException(Exception ex); }### Answer: @Test public void processRuntimeExceptionTest() throws Exception { SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenThrow(new RuntimeException()); SecurityContextHolder.setContext(securityContext); MvcResult res = mock.perform(get("/api/account")) .andExpect(status().isInternalServerError()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(RuntimeException.class)); }
### Question: CustomParameterizedException extends RuntimeException { public ParameterizedErrorVM getErrorVM() { return new ParameterizedErrorVM(message, paramMap); } CustomParameterizedException(String message, String... params); CustomParameterizedException(String message, Map<String, String> paramMap); ParameterizedErrorVM getErrorVM(); }### Answer: @Test public void getErrorVMTest() throws Exception { CustomParameterizedException exc = new CustomParameterizedException("Test"); try { throw exc; } catch ( Exception exception ) { assertTrue(exception instanceof CustomParameterizedException); CustomParameterizedException exceptionCast = (CustomParameterizedException) exception; assertNotNull(exceptionCast.getErrorVM()); assertNotNull(exceptionCast.getErrorVM().getMessage()); assertEquals("Test", exceptionCast.getErrorVM().getMessage()); } exc = new CustomParameterizedException(null); try { throw exc; } catch ( Exception exception ) { assertTrue(exception instanceof CustomParameterizedException); CustomParameterizedException exceptionCast = (CustomParameterizedException) exception; assertNotNull(exceptionCast.getErrorVM()); assertNull(exceptionCast.getErrorVM().getMessage()); } }
### Question: FieldErrorVM implements Serializable { public String getObjectName() { return objectName; } FieldErrorVM(String dto, String field, String message); String getObjectName(); String getField(); String getMessage(); }### Answer: @Test public void getObjectNameTest() throws Exception { FieldErrorVM vm = new FieldErrorVM(null, null, null); assertNull(vm.getObjectName()); vm = new FieldErrorVM("dto", "field", "message"); assertEquals("dto", vm.getObjectName()); }
### Question: FieldErrorVM implements Serializable { public String getField() { return field; } FieldErrorVM(String dto, String field, String message); String getObjectName(); String getField(); String getMessage(); }### Answer: @Test public void getFieldTest() throws Exception { FieldErrorVM vm = new FieldErrorVM(null, null, null); assertNull(vm.getField()); vm = new FieldErrorVM("dto", "field", "message"); assertEquals("field", vm.getField()); }
### Question: FieldErrorVM implements Serializable { public String getMessage() { return message; } FieldErrorVM(String dto, String field, String message); String getObjectName(); String getField(); String getMessage(); }### Answer: @Test public void getMessageTest() throws Exception { FieldErrorVM vm = new FieldErrorVM(null, null, null); assertNull(vm.getMessage()); vm = new FieldErrorVM("dto", "field", "message"); assertEquals("message", vm.getMessage()); }
### Question: ErrorVM implements Serializable { public void add(String objectName, String field, String message) { if (fieldErrors == null) { fieldErrors = new ArrayList<>(); } fieldErrors.add(new FieldErrorVM(objectName, field, message)); } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer: @Test public void addTest() throws Exception { assertNull(vm1.getFieldErrors()); assertNull(vm2.getFieldErrors()); assertNotNull(vm3.getFieldErrors()); assertNull(vm1null.getFieldErrors()); assertNull(vm2null.getFieldErrors()); assertNull(vm3null.getFieldErrors()); vm1.add("testObjectName", "testField", "testMsg"); vm2.add("testObjectName", "testField", "testMsg"); vm3.add("testObjectName", "testField", "testMsg"); vm1null.add("testObjectName", "testField", "testMsg"); vm2null.add("testObjectName", "testField", "testMsg"); vm3null.add("testObjectName", "testField", "testMsg"); assertNotNull(vm1.getFieldErrors()); assertFalse(vm1.getFieldErrors().isEmpty()); assertNotNull(vm2.getFieldErrors()); assertFalse(vm2.getFieldErrors().isEmpty()); assertNotNull(vm3.getFieldErrors()); assertFalse(vm3.getFieldErrors().isEmpty()); assertNotNull(vm1null.getFieldErrors()); assertFalse(vm1null.getFieldErrors().isEmpty()); assertNotNull(vm2null.getFieldErrors()); assertFalse(vm2null.getFieldErrors().isEmpty()); assertNotNull(vm3null.getFieldErrors()); assertFalse(vm3null.getFieldErrors().isEmpty()); }
### Question: ErrorVM implements Serializable { public String getMessage() { return message; } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer: @Test public void getMessageTest() throws Exception { assertEquals(message, vm1.getMessage()); assertEquals(message, vm2.getMessage()); assertEquals(message, vm3.getMessage()); assertNull(vm1null.getMessage()); assertNull(vm2null.getMessage()); assertNull(vm3null.getMessage()); }
### Question: ErrorVM implements Serializable { public String getDescription() { return description; } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer: @Test public void getDescriptionTest() throws Exception { assertNull(vm1.getDescription()); assertEquals(description, vm2.getDescription()); assertEquals(description, vm3.getDescription()); assertNull(vm1null.getDescription()); assertNull(vm2null.getDescription()); assertNull(vm3null.getDescription()); }
### Question: ErrorVM implements Serializable { public List<FieldErrorVM> getFieldErrors() { return fieldErrors; } ErrorVM(String message); ErrorVM(String message, String description); ErrorVM(String message, String description, List<FieldErrorVM> fieldErrors); void add(String objectName, String field, String message); String getMessage(); String getDescription(); List<FieldErrorVM> getFieldErrors(); }### Answer: @Test public void getFieldErrorsTest() throws Exception { assertNull(vm1.getFieldErrors()); assertNull(vm2.getFieldErrors()); assertNotNull(vm3.getFieldErrors()); assertNull(vm1null.getFieldErrors()); assertNull(vm2null.getFieldErrors()); assertNull(vm3null.getFieldErrors()); vm1.add(null, null, null); vm2.add(null, null, null); vm3.add(null, null, null); vm1null.add(null, null, null); vm2null.add(null, null, null); vm3null.add(null, null, null); assertNull(message, vm1.getFieldErrors().get(0).getMessage()); assertNull(message, vm2.getFieldErrors().get(0).getMessage()); assertNull(message, vm3.getFieldErrors().get(0).getMessage()); assertNull(message, vm1null.getFieldErrors().get(0).getMessage()); assertNull(message, vm2null.getFieldErrors().get(0).getMessage()); assertNull(message, vm3null.getFieldErrors().get(0).getMessage()); vm1.add("testObjectName", "testField", "testMsg"); vm2.add("testObjectName", "testField", "testMsg"); vm3.add("testObjectName", "testField", "testMsg"); vm1null.add("testObjectName", "testField", "testMsg"); vm2null.add("testObjectName", "testField", "testMsg"); vm3null.add("testObjectName", "testField", "testMsg"); assertEquals("testMsg", vm1.getFieldErrors().get(1).getMessage()); assertEquals("testMsg", vm2.getFieldErrors().get(1).getMessage()); assertEquals("testMsg", vm3.getFieldErrors().get(1).getMessage()); assertEquals("testMsg", vm1null.getFieldErrors().get(1).getMessage()); assertEquals("testMsg", vm2null.getFieldErrors().get(1).getMessage()); assertEquals("testMsg", vm3null.getFieldErrors().get(1).getMessage()); }
### Question: ParameterizedErrorVM implements Serializable { public String getMessage() { return message; } ParameterizedErrorVM(String message, Map<String, String> paramMap); String getMessage(); Map<String, String> getParams(); }### Answer: @Test public void getMessageTest() { ParameterizedErrorVM vm = new ParameterizedErrorVM(null, null); assertNull(vm.getMessage()); Map<String, String> paramMap = new HashMap<>(); paramMap.put("param1", "param1"); paramMap.put("param2", "param2"); vm = new ParameterizedErrorVM("message", paramMap); assertEquals("message", vm.getMessage()); }
### Question: ParameterizedErrorVM implements Serializable { public Map<String, String> getParams() { return paramMap; } ParameterizedErrorVM(String message, Map<String, String> paramMap); String getMessage(); Map<String, String> getParams(); }### Answer: @Test public void getParamsTest() { ParameterizedErrorVM vm = new ParameterizedErrorVM(null, null); assertNull(vm.getMessage()); Map<String, String> paramMap = new HashMap<>(); paramMap.put("param1", "param1"); paramMap.put("param2", "param2"); vm = new ParameterizedErrorVM("message", paramMap); assertTrue(vm.getParams().size() == 2); }
### Question: EurekaVM { public List<Map<String, Object>> getApplications() { return applications; } List<Map<String, Object>> getApplications(); void setApplications(List<Map<String, Object>> applications); Map<String, Object> getStatus(); void setStatus(Map<String, Object> status); }### Answer: @Test public void getApplicationsTest() throws Exception { List<Map<String, Object>> list = eureka.getApplications(); assertNull(list); eureka.setApplications(initFakeApplicationsList()); list = eureka.getApplications(); assertNotNull(list); assertTrue(list.size()==2); }
### Question: EurekaVM { public void setApplications(List<Map<String, Object>> applications) { this.applications = applications; } List<Map<String, Object>> getApplications(); void setApplications(List<Map<String, Object>> applications); Map<String, Object> getStatus(); void setStatus(Map<String, Object> status); }### Answer: @Test public void setApplicationsTest() throws Exception { assertNull(eureka.getApplications()); eureka.setApplications(initFakeApplicationsList()); assertNotNull(eureka.getApplications()); List<Map<String, Object>> newList = new ArrayList<>(); eureka.setApplications(newList); assertEquals(newList, eureka.getApplications()); }
### Question: EurekaVM { public Map<String, Object> getStatus() { return status; } List<Map<String, Object>> getApplications(); void setApplications(List<Map<String, Object>> applications); Map<String, Object> getStatus(); void setStatus(Map<String, Object> status); }### Answer: @Test public void getStatusTest() throws Exception { Map<String, Object> status = eureka.getStatus(); assertNull(status); eureka.setStatus(initFakeStatus()); status = eureka.getStatus(); assertNotNull(status); assertTrue(status.size()==3); }
### Question: EurekaVM { public void setStatus(Map<String, Object> status) { this.status = status; } List<Map<String, Object>> getApplications(); void setApplications(List<Map<String, Object>> applications); Map<String, Object> getStatus(); void setStatus(Map<String, Object> status); }### Answer: @Test public void setStatusTest() throws Exception { assertNull(eureka.getStatus()); eureka.setStatus(initFakeStatus()); assertNotNull(eureka.getStatus()); Map<String, Object> newStatus = new HashMap<>(); eureka.setStatus(newStatus); assertEquals(newStatus, eureka.getStatus()); }
### Question: LoggerVM { public String getName() { return name; } LoggerVM(Logger logger); @JsonCreator LoggerVM(); String getName(); void setName(String name); String getLevel(); void setLevel(String level); @Override String toString(); }### Answer: @Test public void getNameTest() throws Exception { LoggerVM vm = new LoggerVM(); assertNull(vm.getName()); Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); vm = new LoggerVM(logger); assertEquals(Logger.ROOT_LOGGER_NAME, vm.getName()); }
### Question: LoggerVM { public void setName(String name) { this.name = name; } LoggerVM(Logger logger); @JsonCreator LoggerVM(); String getName(); void setName(String name); String getLevel(); void setLevel(String level); @Override String toString(); }### Answer: @Test public void setNameTest() throws Exception { LoggerVM vm = new LoggerVM(); vm.setName(null); assertNull(vm.getName()); vm = new LoggerVM(); vm.setName("fakeName"); assertEquals("fakeName", vm.getName()); Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); vm = new LoggerVM(logger); vm.setName("fakeRootName"); assertEquals("fakeRootName", vm.getName()); }
### Question: LoggerVM { public String getLevel() { return level; } LoggerVM(Logger logger); @JsonCreator LoggerVM(); String getName(); void setName(String name); String getLevel(); void setLevel(String level); @Override String toString(); }### Answer: @Test public void getLevelTest() throws Exception { LoggerVM vm = new LoggerVM(); assertNull(vm.getLevel()); Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); vm = new LoggerVM(logger); assertEquals(Level.ERROR.toString(), vm.getLevel()); }
### Question: LoggerVM { public void setLevel(String level) { this.level = level; } LoggerVM(Logger logger); @JsonCreator LoggerVM(); String getName(); void setName(String name); String getLevel(); void setLevel(String level); @Override String toString(); }### Answer: @Test public void setLevelTest() throws Exception { LoggerVM vm = new LoggerVM(); vm.setLevel(null); assertNull(vm.getLevel()); vm = new LoggerVM(); vm.setLevel("fakeLevel"); assertEquals("fakeLevel", vm.getLevel()); Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); vm = new LoggerVM(logger); vm.setLevel(Level.OFF.toString()); assertEquals(Level.OFF.toString(), vm.getLevel()); }
### Question: LoggerVM { @Override public String toString() { return "LoggerVM{" + "name='" + name + '\'' + ", level='" + level + '\'' + '}'; } LoggerVM(Logger logger); @JsonCreator LoggerVM(); String getName(); void setName(String name); String getLevel(); void setLevel(String level); @Override String toString(); }### Answer: @Test public void toStringTestTest() throws Exception { Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); LoggerVM vm = new LoggerVM(logger); assertTrue(vm.toString().startsWith(LoggerVM.class.getSimpleName())); String json = vm.toString().replace(LoggerVM.class.getSimpleName(), ""); assertTrue(TestUtils.isValid(json)); }
### Question: LoginVM { public String getUsername() { return username; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer: @Test public void getUsernameTest(){ LoginVM vm = new LoginVM(); assertNull(vm.getUsername()); vm.setUsername("fakeUsername"); assertEquals("fakeUsername", vm.getUsername()); }
### Question: LoginVM { public void setUsername(String username) { this.username = username; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer: @Test public void setUsernameTest(){ LoginVM vm = new LoginVM(); assertNull(vm.getUsername()); vm.setUsername(null); assertNull(vm.getUsername()); vm.setUsername("fakeUsername"); assertEquals("fakeUsername", vm.getUsername()); vm = new LoginVM(); vm.setPassword("goodPassword"); assertFalse(validator.validate(vm).isEmpty()); vm.setUsername(""); assertFalse(validator.validate(vm).isEmpty()); vm.setUsername("badUsernameTooLongbadUsernameTooLongbadUsernameTooLongbadUsernameTooLongbadUsernameTooLong"); assertFalse(validator.validate(vm).isEmpty()); vm.setUsername("goodUsername"); assertTrue(validator.validate(vm).isEmpty()); }
### Question: LoginVM { public String getPassword() { return password; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer: @Test public void getPasswordTest(){ LoginVM vm = new LoginVM(); assertNull(vm.getPassword()); vm.setPassword("fakePassword"); assertEquals("fakePassword", vm.getPassword()); }
### Question: LoginVM { public void setPassword(String password) { this.password = password; } String getUsername(); void setUsername(String username); String getPassword(); void setPassword(String password); Boolean isRememberMe(); void setRememberMe(Boolean rememberMe); @Override String toString(); }### Answer: @Test public void setPasswordTest(){ LoginVM vm = new LoginVM(); assertNull(vm.getPassword()); vm.setPassword(null); assertNull(vm.getPassword()); vm.setPassword("fakePassword"); assertEquals("fakePassword", vm.getPassword()); vm = new LoginVM(); vm.setUsername("goodUsername"); vm.setPassword("goodPassword"); assertTrue(validator.validate(vm).isEmpty()); }