src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ExpectedRankRegression extends AObjectRankingWithBaseLearner<ExpectedRankRegressionConfiguration> { @Override public ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset) throws TrainModelsFailedException { return (ExpectedRankRegressionLearningModel) super.train(dataset); } ExpectedRankRegression(); @Override ExpectedRankRegressionLearningModel train(IDataset<?, ?, ?> dataset); }
@Test public void expectedRankRegressionTestCorrectInput() throws ParsingFailedException, TrainModelsFailedException, PredictionFailedException, LossException { File file = new File(getTestRessourcePathFor(OBJECT_RANKING_DATASET_B)); ExpectedRankRegression expectedRankRegressionAlgorithm = new ExpectedRankRegression(); DatasetFile datasetFile = new DatasetFile(file); ObjectRankingDatasetParser expectedRankRegressionDatasetParser = (ObjectRankingDatasetParser) expectedRankRegressionAlgorithm .getDatasetParser(); IDataset<?, ?, ?> expectedRankRegressionDataset = expectedRankRegressionDatasetParser.parse(datasetFile); IInstance<?, ?, ?> instance = expectedRankRegressionDataset.getInstance(505); IDataset<?, ?, ?> testSet = expectedRankRegressionDataset.getPartOfDataset(500, expectedRankRegressionDataset.getNumberOfInstances()); expectedRankRegressionDataset = expectedRankRegressionDataset.getPartOfDataset(0, 500); ILearningModel<?> train = expectedRankRegressionAlgorithm.train(expectedRankRegressionDataset); ExpectedRankRegressionLearningModel expectedRankRegressionLearningModel = (ExpectedRankRegressionLearningModel) train; Ranking predict = null; List<Ranking> predictedRankingsOnTestSet = new ArrayList<>(); if (expectedRankRegressionLearningModel != null) { predict = expectedRankRegressionLearningModel.predict(instance); predictedRankingsOnTestSet = expectedRankRegressionLearningModel.predict(testSet); } int[] objectList = new int[] { 8, 0, 21, 12, 7, 14, 16, 24, 30, 59 }; Ranking expectedResult = new Ranking(objectList, Ranking.createCompareOperatorArrayForLabels(objectList)); assertNotNull(predict); assertTrue(expectedResult.getObjectList().length == predict.getObjectList().length); assertTrue(expectedResult.getCompareOperators().length == predict.getCompareOperators().length); assertTrue(expectedResult.equals(predict)); List<Ranking> expected = ((ObjectRankingDataset) testSet).getRankings(); SpearmansCorrelation correlation = new SpearmansCorrelation(); double rho = correlation.getAggregatedLossForRatings(expected, predictedRankingsOnTestSet); Assert.assertEquals(0.17740336700336695, rho, 0.0001); }
AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfiguration(); @Override @SuppressWarnings("unchecked") void setAlgorithmConfiguration(AAlgorithmConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getAlgorithmConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override boolean equals(Object secondObject); @Override int hashCode(); @Override String toString(); }
@Test @Override public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> listOfJsonObjects = getCorrectParameters(); for (int i = 0; i < listOfJsonObjects.size(); i++) { IAlgorithm algorithm = getAlgorithm(); try { algorithm.setParameters(listOfJsonObjects.get(i)); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, listOfJsonObjects.get(i))); } } } @Test @Override public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> listOfPairsOfStringAndJsonObjects = getWrongParameters(); for (int i = 0; i < listOfPairsOfStringAndJsonObjects.size(); i++) { IAlgorithm algorithm = getAlgorithm(); try { algorithm.setParameters(listOfPairsOfStringAndJsonObjects.get(i).getSecond()); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, listOfPairsOfStringAndJsonObjects.get(i).getSecond())); } catch (ParameterValidationFailedException e) { Assert.assertEquals(ERROR_WRONG_OUTPUT, e.getMessage(), listOfPairsOfStringAndJsonObjects.get(i).getFirst()); } } }
PlackettLuceModelFittingAlgorithm extends ARankingDistributionFittingAlgorithm<PlackettLuceModelFittingAlgorithmConfiguration> { @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((PlackettLuceModelSampleSet) sampleSet); while (!shouldStop()) { updateParameters(); normalizeParameters(); updateDifferenceBetweenOldAndNewParameters(); updateNumberOfIterations(); oldParameters = Arrays.copyOf(parameters, parameters.length); } try { return new PlackettLuceModel(parameters, plackettLuceSampleSet.getValidItems()); } catch (ParameterValidationFailedException e) { throw new FittingDistributionFailedException(e); } } PlackettLuceModelFittingAlgorithm(); PlackettLuceModelFittingAlgorithm(double minimumRequiredChangeOnUpdate, int iterationsSampleSetMultiplier); @Override PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void testFitting() throws ParameterValidationFailedException, DistributionException, FittingDistributionFailedException { double[] expectedParameters = new double[] { 0.2, 0.1, 0.1, 0.1, 0.25, 0.25 }; int[] validItems = new int[] { 1, 2, 3, 4, 5, 6 }; PlackettLuceModel model = new PlackettLuceModel(expectedParameters, validItems); long startingTimeSampling = System.currentTimeMillis(); PlackettLuceModelSampleSet sampleSet = new PlackettLuceModelSampleSet(validItems); for (int i = 0; i < 2000; i++) { sampleSet.addSample(model.generateSample()); } long stoppingTimeSampling = System.currentTimeMillis(); logger.debug( "Stopped sampling at " + stoppingTimeSampling + " and took " + (stoppingTimeSampling - startingTimeSampling) / 1000.0 + " s."); PlackettLuceModelFittingAlgorithm fittingAlgorithm = new PlackettLuceModelFittingAlgorithm(); long startingTime = System.currentTimeMillis(); logger.debug("Started at " + startingTime); PlackettLuceModel fittedModel = fittingAlgorithm.fit(sampleSet); long stoppingTime = System.currentTimeMillis(); logger.debug("Stopped at " + stoppingTime + " and took " + (stoppingTime - startingTime) / 1000.0 + " s."); assertEquals(expectedParameters[0], fittedModel.getDistributionConfiguration().getParameterValueOfItem(1), GREATER_DOUBLE_DELTA); assertEquals(expectedParameters[1], fittedModel.getDistributionConfiguration().getParameterValueOfItem(2), GREATER_DOUBLE_DELTA); assertEquals(expectedParameters[2], fittedModel.getDistributionConfiguration().getParameterValueOfItem(3), GREATER_DOUBLE_DELTA); }
Snippet { @GetMapping(path = "/{id}") public SnippetEntity getSnippet(@PathVariable("id") String id) { return snippetService.getSnippet(id); } @GetMapping() Page<SnippetEntity> getSnippets(@RequestParam(value = "from", defaultValue = "0") final int from, @RequestParam(value = "size", defaultValue = "10") final int size, @RequestParam(value = "query", required = false) final String query); @GetMapping(path = "/search", consumes = MediaType.APPLICATION_JSON) Page<SnippetEntity> search(@RequestParam(value = "from", defaultValue = "0") final int from, @RequestParam(value = "size", defaultValue = "10") final int size, @RequestBody SearchBody searchBody); @PostMapping() SnippetEntity create(@RequestBody SnippetEntity snippet); @GetMapping(path = "/{id}") SnippetEntity getSnippet(@PathVariable("id") String id); @PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON) @PreAuthorize("hasRole('" + Permission.ADMIN + "') or (hasRole('" + Permission.USER + "') and @snippetSecurityService.ownsSnippet(#id))") SnippetEntity updateSnippet(@PathVariable("id") String id, @RequestBody SnippetEntity snippet); @DeleteMapping(path = "/{id}") @PreAuthorize("hasRole('" + Permission.ADMIN + "') or (hasRole('" + Permission.USER + "') and @snippetSecurityService.ownsSnippet(#id))") @ResponseStatus(value = HttpStatus.NO_CONTENT) void delete(@PathVariable("id") String id); }
@Test public void testGetSnippet() throws IOException { ResponseEntity<String> response = restTemplate.getForEntity(SNIPPET_ENDPOINT, String.class); Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); Page<SnippetEntity> page = TestUtils.getObjectFromString(response.getBody(), new TypeReference<Page<SnippetEntity>>() { }); List<SnippetEntity> snippetsExpected = Arrays.asList(TestUtils.getObjectFromJson("snippet/content.json", SnippetEntity[].class)); Assert.assertEquals(2, page.getTotalElement()); Assert.assertEquals(1, page.getTotalPage()); }
CategoryTreeNavigator { public void selectCategory(long selectedCategoryId) { Map<Long, Category> map = categories.asMap(); Category selectedCategory = map.get(selectedCategoryId); if (selectedCategory != null) { Stack<Long> path = new Stack<>(); Category parent = selectedCategory.parent; while (parent != null) { path.push(parent.id); parent = parent.parent; } while (!path.isEmpty()) { navigateTo(path.pop()); } this.selectedCategoryId = selectedCategoryId; } } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); static final long INCOME_CATEGORY_ID; static final long EXPENSE_CATEGORY_ID; public CategoryTree<Category> categories; public long selectedCategoryId; }
@Test public void should_select_startup_category() { long selectedCategoryId = categories.get("AA1").id; navigator.selectCategory(selectedCategoryId); assertEquals(selectedCategoryId, navigator.selectedCategoryId); assertSelected(selectedCategoryId, "A1", "AA1"); }
TransactionsTotalCalculator { public Total getAccountBalance(Currency toCurrency, long accountId) { WhereFilter filter = selectedAccountOnly(this.filter, accountId); return getBalanceInHomeCurrency(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, toCurrency, filter); } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; }
@Test public void should_return_error_if_exchange_rate_not_available() { TransactionBuilder.withDb(db).account(a1).dateTime(DateTime.date(2012, 1, 10)).amount(1).create(); assertFalse(c.getAccountBalance(c1, a1.id).isError()); assertFalse(c.getAccountBalance(c3, a1.id).isError()); Total total = c.getAccountBalance(c2, a1.id); assertTrue(total.isError()); total = c.getAccountBalance(c4, a1.id); assertTrue(total.isError()); } @Test public void should_calculate_account_total_in_home_currency() { assertEquals(a1t1_09th.fromAmount + a1t2_17th.fromAmount + a1t3_20th.fromAmount + a1t4_22nd.fromAmount + a1t5_23rd.fromAmount, c.getAccountBalance(c1, a1.id).balance); assertEquals((long) (a1t1_09th.originalFromAmount + r_c1c2_17th * a1t2_17th.fromAmount - a1t3_20th.toAmount + r_c1c2_18th * a1t4_22nd.fromAmount + r_c1c2_18th * a1t5_23rd.fromAmount), c.getAccountBalance(c2, a1.id).balance); assertEquals(a2t1_17th.fromAmount + a2t2_18th.fromAmount + a1t3_20th.toAmount + a1t5_23rd_s2.toAmount, c.getAccountBalance(c2, a2.id).balance); assertEquals((long) (r_c2c1_17th * a2t1_17th.fromAmount + r_c2c1_18th * a2t2_18th.fromAmount - a1t3_20th.fromAmount - a1t5_23rd_s2.fromAmount), c.getAccountBalance(c1, a2.id).balance); assertEquals((long) (r_c1c3_5th * (a1t1_09th.fromAmount + a1t2_17th.fromAmount + a1t3_20th.fromAmount + a1t4_22nd.fromAmount + a1t5_23rd.fromAmount)), c.getAccountBalance(c3, a1.id).balance); assertEquals((long) (r_c2c3_5th * (a2t1_17th.fromAmount + a2t2_18th.fromAmount + a1t3_20th.toAmount + a1t5_23rd_s2.toAmount)), c.getAccountBalance(c3, a2.id).balance); } @Test public void should_calculate_account_total_in_home_currency_with_big_amounts() { TransactionBuilder.withDb(db).account(a1).dateTime(DateTime.date(2012, 1, 10)).amount(45000000000L).create(); assertEquals(45000000000L + (long) (-100f + 100f - 50f - 450f - 50f - 150f), c.getAccountBalance(c1, a1.id).balance); }
TransactionsTotalCalculator { public Total[] getTransactionsBalance() { WhereFilter filter = this.filter; if (filter.getAccountId() == -1) { filter = excludeAccountsNotIncludedInTotalsAndSplits(filter); } try (Cursor c = db.db().query(V_BLOTTER_FOR_ACCOUNT_WITH_SPLITS, BALANCE_PROJECTION, filter.getSelection(), filter.getSelectionArgs(), BALANCE_GROUPBY, null, null)) { int count = c.getCount(); List<Total> totals = new ArrayList<Total>(count); while (c.moveToNext()) { long currencyId = c.getLong(0); long balance = c.getLong(1); Currency currency = CurrencyCache.getCurrency(db, currencyId); Total total = new Total(currency); total.balance = balance; totals.add(total); } return totals.toArray(new Total[totals.size()]); } } TransactionsTotalCalculator(DatabaseAdapter db, WhereFilter filter); Total[] getTransactionsBalance(); Total getAccountTotal(); Total getBlotterBalanceInHomeCurrency(); Total getBlotterBalance(Currency toCurrency); Total getAccountBalance(Currency toCurrency, long accountId); static Total calculateTotalFromListInHomeCurrency(DatabaseAdapter db, List<TransactionInfo> list); static long[] calculateTotalFromList(DatabaseAdapter db, List<TransactionInfo> list, Currency toCurrency); static BigDecimal getAmountFromCursor(MyEntityManager em, Cursor c, Currency toCurrency, ExchangeRateProvider rates, int index); static BigDecimal getAmountFromTransaction(MyEntityManager em, TransactionInfo ti, Currency toCurrency, ExchangeRateProvider rates); static final String[] BALANCE_PROJECTION; static final String BALANCE_GROUPBY; static final String[] HOME_CURRENCY_PROJECTION; }
@Test public void should_calculate_blotter_total_in_multiple_currencies() { Total[] totals = c.getTransactionsBalance(); assertEquals(2, totals.length); assertEquals(-700, totals[0].balance); assertEquals(-230, totals[1].balance); }
SmsTransactionProcessor { public Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote) { List<SmsTemplate> addrTemplates = db.getSmsTemplatesByNumber(addr); for (final SmsTemplate t : addrTemplates) { String[] match = findTemplateMatches(t.template, fullSmsBody); if (match != null) { Log.d(TAG, format("Found template`%s` with matches `%s`", t, Arrays.toString(match))); String account = match[ACCOUNT.ordinal()]; String parsedPrice = match[PRICE.ordinal()]; try { BigDecimal price = toBigDecimal(parsedPrice); return createNewTransaction(price, account, t, updateNote ? fullSmsBody : "", status); } catch (Exception e) { Log.e(TAG, format("Failed to parse price value: `%s`", parsedPrice), e); } } } return null; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); }
@Test public void TemplatesWithDifferentLength() { String template1 = "*{{a}}. Summa {{p}} RUB. {{*}}, MOSCOW. {{d}}. Dostupno {{b}}"; String template2 = "*{{a}}. Summa {{p}} RUB. NOVYY PROEKT, MOSCOW. {{d}}. Dostupno {{b}}"; String template3 = "*{{a}}. Summa {{p}} RUB. NOVYY PROEKT, MOSCOW. {{d}}. Dostupno {{b}}"; String sms = "Pokupka. Karta *5631. Summa 250.77 RUB. NOVYY PROEKT, MOSCOW. 02.10.2017 14:19. Dostupno 34202.82 RUB. Tinkoff.ru"; SmsTemplateBuilder.withDb(db).title("Tinkoff").accountId(7).categoryId(8).template(template1).sortOrder(2).create(); SmsTemplateBuilder.withDb(db).title("Tinkoff").accountId(7).categoryId(88).template(template2).sortOrder(1).create(); SmsTemplateBuilder.withDb(db).title("Tinkoff").accountId(7).categoryId(89).template(template3).create(); Transaction transaction = smsProcessor.createTransactionBySms("Tinkoff", sms, status, true); assertEquals(7, transaction.fromAccountId); assertEquals(88, transaction.categoryId); assertEquals(-25077, transaction.fromAmount); assertEquals(sms, transaction.note); assertEquals(TransactionStatus.PN, transaction.status); }
SmsTransactionProcessor { public static String[] findTemplateMatches(String template, final String sms) { String[] results = null; template = preprocessPatterns(template); final int[] phIndexes = findPlaceholderIndexes(template); if (phIndexes != null) { template = template.replaceAll("([.\\[\\]{}()*+\\-?^$|])", "\\\\$1"); for (int i = 0; i < phIndexes.length; i++) { if (phIndexes[i] != -1) { Placeholder placeholder = Placeholder.values()[i]; template = template.replace(placeholder.code, placeholder.regexp); } } template = ANY.regexp + template.replace(ANY.code, ANY.regexp) + ANY.regexp; Matcher matcher = Pattern.compile(template, DOTALL).matcher(sms); if (matcher.matches()) { results = new String[Placeholder.values().length]; for (int i = 0; i < phIndexes.length; i++) { final int groupNum = phIndexes[i] + 1; if (groupNum > 0) { results[i] = matcher.group(groupNum); } } } } return results; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); }
@Test public void MultilineSms() { String template = "*{{a}}. Summa {{p}} RUB. NOVYY PROEKT, MOSCOW. {{d}}. Dostupno {{b}}{{*}}"; String sms = "Pokupka. Karta *5631. Summa 1250,77 RUB. NOVYY PROEKT, MOSCOW. 02.10.2017 14:19. Dostupno 34 202.82 RUB.\nTinkoff\n.ru"; String[] matches = SmsTransactionProcessor.findTemplateMatches(template, sms); Assert.assertArrayEquals(new String[]{null, "5631", "34 202.82 ", "02.10.2017 14:19", "1250,77", null}, matches); } @Test public void TemplateWithWrongSpaces() { String smsTpl = "ECMC{{a}}<:D:>покупка{{P}}р TEREMOK METROPOLIS Баланс:{{b}}р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches); } @Test public void TemplateWithAnyMatch() { String smsTpl = "ECMC{{A}}{{d}}покупка<:P:>р TEREMOK <::>Баланс:<:B:>р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches); } @Test public void TemplateWithMultipleAnyMatch() { String smsTpl = "ECMC<:A:> <:D:> {{*}} <:P:>р TEREMOK<::><:B:>р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, "5431", "49820.45", "01.10.17 19:50", "550", null}, matches); } @Test public void TemplateWithMultipleAnyMatchWithoutAccount() { String smsTpl = "<::> <:D:> {{*}} <:P:>р TEREMOK<::><:B:>р"; String sms = "ECMC5431 01.10.17 19:50 покупка 550р TEREMOK METROPOLIS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, null, "49820.45", "01.10.17 19:50", "550", null}, matches); } @Test public void TemplateWithSpecialChars() { String smsTpl = "{{*}} {{d}} {{*}} {{p}}р TE{{R}}E{{MOK ME}TROP<:P:OL?$()[]/\\.*IS{{*}}{{b}}р"; String sms = "ECMC5431 01.10.17 19:50 покупка 555р TE{{R}}E{{MOK ME}TROP<:P:OL?$()[]/\\.*IS Баланс: 49820.45р"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, null, "49820.45", "01.10.17 19:50", "555", null}, matches); } @Test public void MultipleAnyMatchWithoutAccountAndDate() { String smsTpl = "Pokupka{{*}}Summa {{p}} RUB. NOVYY PROEKT, MOSCOW{{*}}Dostupno {{b}} RUB.{{*}}"; String sms = "Pokupka. Karta *5631. Summa 250.00 RUB. NOVYY PROEKT, MOSCOW. 02.10.2017 14:19. Dostupno 34202.82 RUB. Tinkoff.ru"; String[] matches = SmsTransactionProcessor.findTemplateMatches(smsTpl, sms); Assert.assertArrayEquals(new String[]{null, null, "34202.82", null, "250.00", null}, matches); }
CategoryTreeNavigator { public boolean navigateTo(long categoryId) { Category selectedCategory = findCategory(categoryId); if (selectedCategory != null) { selectedCategoryId = selectedCategory.id; if (selectedCategory.hasChildren()) { categoriesStack.push(categories); categories = selectedCategory.children; tagCategories(selectedCategory); return true; } } return false; } CategoryTreeNavigator(DatabaseAdapter db); CategoryTreeNavigator(DatabaseAdapter db, long excludedTreeId); void selectCategory(long selectedCategoryId); void tagCategories(Category parent); boolean goBack(); boolean canGoBack(); boolean navigateTo(long categoryId); boolean isSelected(long categoryId); List<Category> getSelectedRoots(); void addSplitCategoryToTheTop(); void separateIncomeAndExpense(); long getExcludedTreeId(); static final long INCOME_CATEGORY_ID; static final long EXPENSE_CATEGORY_ID; public CategoryTree<Category> categories; public long selectedCategoryId; }
@Test public void should_navigate_to_category() { long categoryId = categories.get("A").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A", "A1", "A2"); categoryId = categories.get("A1").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A1", "AA1"); categoryId = categories.get("AA1").id; navigator.navigateTo(categoryId); assertSelected(categoryId, "A1", "AA1"); }
SmsTransactionProcessor { static int[] findPlaceholderIndexes(String template) { Map<Integer, Placeholder> sorted = new TreeMap<>(); boolean foundPrice = false; for (Placeholder p : Placeholder.values()) { int i = template.indexOf(p.code); if (i >= 0) { if (p == PRICE) { foundPrice = true; } if (p != ANY) { sorted.put(i, p); } } } int[] result = null; if (foundPrice) { result = new int[Placeholder.values().length]; Arrays.fill(result, -1); int i = 0; for (Placeholder p : sorted.values()) { result[p.ordinal()] = i++; } } return result; } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); }
@Test public void FindingPlaceholderIndexes() { int[] indexes = SmsTransactionProcessor.findPlaceholderIndexes("Pokupka. Karta *<:A:>. Summa <:P:> RUB. NOVYY PROEKT, MOSCOW. <:D:>. Dostupno <:B:> RUB. Tinkoff.ru"); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.PRICE.ordinal()]); assertEquals(2, indexes[Placeholder.DATE.ordinal()]); assertEquals(3, indexes[Placeholder.BALANCE.ordinal()]); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:> покупка <:P:> TEREMOK METROPOLIS Баланс: <:B:>р"); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.DATE.ordinal()]); assertEquals(2, indexes[Placeholder.PRICE.ordinal()]); assertEquals(3, indexes[Placeholder.BALANCE.ordinal()]); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:> покупка <:P:> TEREMOK METROPOLIS Баланс:"); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.DATE.ordinal()]); assertEquals(2, indexes[Placeholder.PRICE.ordinal()]); assertEquals(indexes[Placeholder.BALANCE.ordinal()], -1); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:><::> <:P:> TEREMOK METROPOLIS Баланс:"); assertEquals(indexes[Placeholder.ANY.ordinal()], -1); assertEquals(0, indexes[Placeholder.ACCOUNT.ordinal()]); assertEquals(1, indexes[Placeholder.DATE.ordinal()]); assertEquals(2, indexes[Placeholder.PRICE.ordinal()]); assertEquals(indexes[Placeholder.BALANCE.ordinal()], -1); indexes = SmsTransactionProcessor.findPlaceholderIndexes("ECMC<:A:> <:D:><::> TEREMOK METROPOLIS Баланс:"); Assert.assertNull(indexes); }
SmsTransactionProcessor { static BigDecimal toBigDecimal(final String value) { if (value != null) { final String EMPTY = ""; final char COMMA = ','; final String POINT_AS_STRING = "."; final char POINT = '.'; final String COMMA_AS_STRING = ","; String trimmed = value.trim(); boolean negativeNumber = ((trimmed.contains("(") && trimmed.contains(")")) || trimmed.endsWith("-") || trimmed.startsWith("-")); String parsedValue = value.replaceAll("[^0-9,.]", EMPTY); if (negativeNumber) parsedValue = "-" + parsedValue; int lastPointPosition = parsedValue.lastIndexOf(POINT); int lastCommaPosition = parsedValue.lastIndexOf(COMMA); if (lastPointPosition == -1 && lastCommaPosition == -1) { return new BigDecimal(parsedValue); } if (lastPointPosition > -1 && lastCommaPosition == -1) { int firstPointPosition = parsedValue.indexOf(POINT); if (firstPointPosition != lastPointPosition) return new BigDecimal(parsedValue.replace(POINT_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue); } if (lastPointPosition == -1 && lastCommaPosition > -1) { int firstCommaPosition = parsedValue.indexOf(COMMA); if (firstCommaPosition != lastCommaPosition) return new BigDecimal(parsedValue.replace(COMMA_AS_STRING, EMPTY)); else return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastPointPosition < lastCommaPosition) { parsedValue = parsedValue.replace(POINT_AS_STRING, EMPTY); return new BigDecimal(parsedValue.replace(COMMA, POINT)); } if (lastCommaPosition < lastPointPosition) { parsedValue = parsedValue.replace(COMMA_AS_STRING, EMPTY); return new BigDecimal(parsedValue); } } throw new NumberFormatException("Unexpected number format. Cannot convert '" + value + "' to BigDecimal."); } SmsTransactionProcessor(DatabaseAdapter db); Transaction createTransactionBySms(String addr, String fullSmsBody, TransactionStatus status, boolean updateNote); static String[] findTemplateMatches(String template, final String sms); }
@Test public void DifferentPrices() { Assert.assertEquals(new BigDecimal(5), toBigDecimal("5")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal(" 5,3 ")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal("5.3")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("5.000,3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("5.000.000,3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("5.000.000")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("5,000.3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("5,000,000.3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("5,000,000")); Assert.assertEquals(new BigDecimal("5"), toBigDecimal("+5")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal("+5,3")); Assert.assertEquals(new BigDecimal("5.3"), toBigDecimal("+5.3")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("+5.000,3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("+5.000.000,3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("+5.000.000")); Assert.assertEquals(new BigDecimal("5000.3"), toBigDecimal("+5,000.3")); Assert.assertEquals(new BigDecimal("5000000.3"), toBigDecimal("+5,000,000.3")); Assert.assertEquals(new BigDecimal("5000000"), toBigDecimal("+5,000,000")); Assert.assertEquals(new BigDecimal("-5"), toBigDecimal(" -5 ")); Assert.assertEquals(new BigDecimal("-5.3"), toBigDecimal("-5,3")); Assert.assertEquals(new BigDecimal("-5.3"), toBigDecimal("-5.3")); Assert.assertEquals(new BigDecimal("-5000.3"), toBigDecimal("-5.000,3")); Assert.assertEquals(new BigDecimal("-5000000.3"), toBigDecimal("-5.000.000,3")); Assert.assertEquals(new BigDecimal("-5000000"), toBigDecimal("-5.000.000")); Assert.assertEquals(new BigDecimal("-5000.3"), toBigDecimal("-5,000.3")); Assert.assertEquals(new BigDecimal("-5000000.3"), toBigDecimal("-5,000,000.3")); Assert.assertEquals(new BigDecimal("-5000000"), toBigDecimal("-5,000,000")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1 234.56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1234.56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1 234,56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1 234,56")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1,234.56")); Assert.assertEquals(new BigDecimal("123456"), toBigDecimal("123456")); Assert.assertEquals(new BigDecimal("1234.5678"), toBigDecimal("1234,5678")); Assert.assertEquals(new BigDecimal("123456789"), toBigDecimal("123456789")); Assert.assertEquals(new BigDecimal("123456789"), toBigDecimal("123 456 789")); Assert.assertEquals(new BigDecimal("1234.56"), toBigDecimal("1'234.56")); }
IntegrityCheckRunningBalance implements IntegrityCheck { @Override public Result check() { if (isRunningBalanceBroken()) { return new Result(Level.ERROR, context.getString(R.string.integrity_error)); } else { return Result.OK; } } IntegrityCheckRunningBalance(Context context, DatabaseAdapter db); @Override Result check(); }
@Test public void should_detect_that_running_balance_is_broken() { TransactionBuilder.withDb(db).account(a1).amount(1000).create(); TransactionBuilder.withDb(db).account(a1).amount(2000).create(); TransactionBuilder.withDb(db).account(a2).amount(-100).create(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); breakRunningBalanceForAccount(a1); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); db.rebuildRunningBalanceForAccount(a1); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); breakRunningBalance(); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); db.rebuildRunningBalances(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); }
IntegrityCheckAutobackup implements IntegrityCheck { @Override public Result check() { if (MyPreferences.isAutoBackupEnabled(context)) { if (MyPreferences.isAutoBackupWarningEnabled(context)) { MyPreferences.AutobackupStatus status = MyPreferences.getAutobackupStatus(context); if (status.notify) { MyPreferences.notifyAutobackupSucceeded(context); return new Result(Level.ERROR, context.getString(R.string.autobackup_failed_message, DateUtils.getTimeFormat(context).format(new Date(status.timestamp)), status.errorMessage)); } } } else { if (MyPreferences.isAutoBackupReminderEnabled(context)) { long lastCheck = MyPreferences.getLastAutobackupCheck(context); if (lastCheck == 0) { MyPreferences.updateLastAutobackupCheck(context); } else { long delta = System.currentTimeMillis() - lastCheck; if (delta > threshold) { MyPreferences.updateLastAutobackupCheck(context); return new Result(Level.INFO, context.getString(R.string.auto_backup_is_not_enabled)); } } } } return Result.OK; } IntegrityCheckAutobackup(Context context, long threshold); @Override Result check(); }
@Test public void should_check_if_autobackup_has_been_disabled() { givenAutobackupReminderEnabledIs(true); givenAutobackupEnabledIs(false); givenFirstRunAfterRelease(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); sleepMillis(50); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); sleepMillis(51); assertEquals(IntegrityCheck.Level.INFO, integrity.check().level); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenAutobackupEnabledIs(true); sleepMillis(101); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenAutobackupReminderEnabledIs(false); givenAutobackupEnabledIs(false); sleepMillis(101); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); } @Test public void should_check_if_the_last_autobackup_has_failed() { givenAutobackupWarningEnabledIs(true); givenAutobackupEnabledIs(true); givenFirstRunAfterRelease(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenTheLastAutobackupHasFailed(); assertEquals(IntegrityCheck.Level.ERROR, integrity.check().level); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenTheLastAutobackupHasFailed(); givenTheLastAutobackupHasSucceeded(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); givenAutobackupWarningEnabledIs(false); givenTheLastAutobackupHasFailed(); assertEquals(IntegrityCheck.Level.OK, integrity.check().level); }
CurrencySelector { public void addSelectedCurrency(int selectedCurrency) { if (selectedCurrency > 0 && selectedCurrency <= currencies.size()) { List<String> c = currencies.get(selectedCurrency-1); addSelectedCurrency(c); } else { listener.onCreated(0); } } CurrencySelector(Context context, MyEntityManager em, OnCurrencyCreatedListener listener); void show(); void addSelectedCurrency(int selectedCurrency); }
@Test public void should_add_selected_currency_as_default_if_it_is_the_very_first_currency_added() { givenNoCurrenciesYetExist(); selector.addSelectedCurrency(1); Currency currency1 = db.load(Currency.class, currencyId); assertTrue(currency1.isDefault); selector.addSelectedCurrency(2); Currency currency2 = db.load(Currency.class, currencyId); assertTrue(currency1.isDefault); assertFalse(currency2.isDefault); }
CategoryCache { public static String extractCategoryName(String name) { int i = name.indexOf('/'); if (i != -1) { name = name.substring(0, i); } return name; } static String extractCategoryName(String name); void loadExistingCategories(DatabaseAdapter db); void insertCategories(DatabaseAdapter dbAdapter, Set<? extends CategoryInfo> categories); Category findCategory(String category); public Map<String, Category> categoryNameToCategory; public CategoryTree<Category> categoryTree; }
@Test public void should_split_category_name() { assertEquals("P1", extractCategoryName("P1")); assertEquals("P1:c1", extractCategoryName("P1:c1")); assertEquals("P1", extractCategoryName("P1/C2")); assertEquals("P1:c1", extractCategoryName("P1:c1/C2")); }
DatabaseAdapter extends MyEntityManager { public boolean singleCurrencyOnly() { long currencyId = getSingleCurrencyId(); return currencyId > 0; } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void should_detect_multiple_account_currencies() { assertTrue(db.singleCurrencyOnly()); AccountBuilder.withDb(db).currency(a1.currency).title("Account2").create(); assertTrue(db.singleCurrencyOnly()); Currency c2 = CurrencyBuilder.withDb(db).name("USD").title("Dollar").symbol("$").create(); AccountBuilder.withDb(db).currency(c2).title("Account3").doNotIncludeIntoTotals().create(); assertTrue(db.singleCurrencyOnly()); AccountBuilder.withDb(db).currency(c2).title("Account4").inactive().create(); assertTrue(db.singleCurrencyOnly()); AccountBuilder.withDb(db).currency(c2).title("Account5").create(); assertFalse(db.singleCurrencyOnly()); }
DatabaseAdapter extends MyEntityManager { public List<Category> getCategoriesWithoutSubtreeAsList(long categoryId) { List<Category> list = new ArrayList<>(); try (Cursor c = getCategoriesWithoutSubtree(categoryId, true)) { while (c.moveToNext()) { Category category = Category.formCursor(c); list.add(category); } return list; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void should_not_return_split_category_as_parent_when_editing_a_category() { List<Category> list = db.getCategoriesWithoutSubtreeAsList(categoriesMap.get("A").id); for (Category category : list) { assertFalse("Should not be split", category.isSplit()); } } @Test public void should_return_only_valid_parent_categories_when_editing_a_category() { List<Category> list = db.getCategoriesWithoutSubtreeAsList(categoriesMap.get("A").id); assertEquals(2, list.size()); assertEquals(Category.NO_CATEGORY_ID, list.get(0).id); assertEquals(categoriesMap.get("B").id, list.get(1).id); }
DatabaseAdapter extends MyEntityManager { public long findNearestOlderTransactionId(Account account, long date) { return DatabaseUtils.rawFetchId(this, "select _id from v_blotter where from_account_id=? and datetime<=? order by datetime desc limit 1", new String[]{String.valueOf(account.id), String.valueOf(DateUtils.atDayEnd(date))}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void should_return_id_of_the_nearest_transaction_which_is_older_than_specified_date() { a2 = AccountBuilder.createDefault(db); Transaction t8 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(17, 30, 45, 0)).account(a2).amount(-234).create(); Transaction t7 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(16, 30, 45, 0)).account(a1).amount(-234).create(); Transaction t6 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 24).at(23, 59, 59, 999)).account(a1).amount(200).create(); Transaction t5 = TransactionBuilder.withDb(db).scheduleOnce(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); Transaction t4 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); Transaction t3 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 0, 12, 345)).account(a1).amount(10).create(); Transaction t2 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 0, 12, 345)).account(a1).amount(10).makeTemplate().create(); Transaction t1 = TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 21).at(0, 0, 0, 0)).account(a1).amount(-20).create(); assertEquals(-1, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 20).asLong())); assertEquals(t1.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 21).at(15, 30, 30, 456).asLong())); assertEquals(t3.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 22).asLong())); assertEquals(t4.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 23).asLong())); assertEquals(t6.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 24).asLong())); assertEquals(t7.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 25).asLong())); assertEquals(t7.id, db.findNearestOlderTransactionId(a1, DateTime.date(2012, 5, 26).asLong())); assertEquals(t8.id, db.findNearestOlderTransactionId(a2, DateTime.date(2012, 5, 26).asLong())); }
DatabaseAdapter extends MyEntityManager { public void deleteOldTransactions(Account account, long date) { SQLiteDatabase db = db(); long dayEnd = DateUtils.atDayEnd(date); db.delete("transactions", "from_account_id=? and datetime<=? and is_template=0", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); db.delete("running_balance", "account_id=? and datetime<=?", new String[]{String.valueOf(account.id), String.valueOf(dayEnd)}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void should_delete_old_transactions() { a2 = AccountBuilder.createDefault(db); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(17, 30, 45, 0)).account(a2).amount(-234).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 24).at(12, 30, 0, 0)).account(a1).amount(-100) .withSplit(categoriesMap.get("A1"), -50) .withTransferSplit(a2, -50, 50) .create(); TransactionBuilder.withDb(db).scheduleOnce(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 23).at(23, 59, 59, 999)).account(a1).amount(10).create(); TransferBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(22, 0, 0, 0)) .fromAccount(a1).fromAmount(10) .toAccount(a2).toAmount(10).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 0, 12, 345)).account(a1).amount(10).makeTemplate().create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 21).at(0, 0, 0, 0)).account(a1).amount(-20).create(); assertTransactionsCount(a1, 8); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 20).asLong()); assertTransactionsCount(a1, 8); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 21).asLong()); assertTransactionsCount(a1, 7); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 22).asLong()); assertTransactionsCount(a1, 6); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 23).asLong()); assertTransactionsCount(a1, 5); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a1, DateTime.date(2012, 5, 25).asLong()); assertTransactionsCount(a1, 2); assertTransactionsCount(a2, 1); db.deleteOldTransactions(a2, DateTime.date(2012, 5, 25).asLong()); assertTransactionsCount(a1, 2); assertTransactionsCount(a2, 0); }
DatabaseAdapter extends MyEntityManager { public long findLatestTransactionDate(long accountId) { return DatabaseUtils.rawFetchLongValue(this, "select datetime from running_balance where account_id=? order by datetime desc limit 1", new String[]{String.valueOf(accountId)}); } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void should_find_latest_transaction_date_for_an_account() { Account a2 = AccountBuilder.createDefault(db); Account a3 = AccountBuilder.createDefault(db); Account a4 = AccountBuilder.createDefault(db); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 25).at(17, 30, 45, 0)).account(a2).amount(-234).create(); TransactionBuilder.withDb(db).scheduleOnce(DateTime.date(2012, 5, 23).at(0, 0, 0, 45)).account(a1).amount(100).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 23).at(23, 59, 59, 999)).account(a1).amount(10).create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 22).at(12, 30, 0, 0)).account(a1).amount(-100) .withSplit(categoriesMap.get("A1"), -50) .withTransferSplit(a3, -50, 50) .create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 21).at(12, 0, 12, 345)).account(a2).amount(10).makeTemplate().create(); TransactionBuilder.withDb(db).dateTime(DateTime.date(2012, 5, 20).at(0, 0, 0, 0)).account(a2).amount(-20).create(); assertEquals(DateTime.date(2012, 5, 23).at(23, 59, 59, 999).asLong(), db.findLatestTransactionDate(a1.id)); assertEquals(DateTime.date(2012, 5, 25).at(17, 30, 45, 0).asLong(), db.findLatestTransactionDate(a2.id)); assertEquals(DateTime.date(2012, 5, 22).at(12, 30, 0, 0).asLong(), db.findLatestTransactionDate(a3.id)); assertEquals(0, db.findLatestTransactionDate(a4.id)); }
DatabaseAdapter extends MyEntityManager { public void restoreSystemEntities() { SQLiteDatabase db = db(); db.beginTransaction(); try { restoreCategories(); restoreAttributes(); restoreProjects(); restoreLocations(); db.setTransactionSuccessful(); } catch (Exception e) { Log.e("Financisto", "Unable to restore system entities", e); } finally { db.endTransaction(); } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void should_restore_system_entities() { givenSystemEntitiesHaveBeenDeleted(); db.restoreSystemEntities(); for (MyEntity e : systemEntities) { MyEntity myEntity = db.get(e.getClass(), e.id); assertNotNull(e.getClass() + ":" + e.getTitle(), myEntity); } Category c = db.get(Category.class, Category.NO_CATEGORY_ID); assertNotNull(c); assertEquals("<NO_CATEGORY>", c.title); }
DatabaseAdapter extends MyEntityManager { public List<Long> findAccountsByNumber(String numberEnding) { try (Cursor c = db().rawQuery( "select " + AccountColumns.ID + " from " + ACCOUNT_TABLE + " where " + AccountColumns.NUMBER + " like ?", new String[]{"%" + numberEnding})) { List<Long> res = new ArrayList<>(c.getCount()); while (c.moveToNext()) { res.add(c.getLong(0)); } return res; } } DatabaseAdapter(Context context); void open(); void close(); int deleteAccount(long id); Transaction getTransaction(long id); Cursor getBlotter(WhereFilter filter); Cursor getBlotterForAccount(WhereFilter filter); static WhereFilter enhanceFilterForAccountBlotter(WhereFilter filter); Cursor getBlotterForAccountWithSplits(WhereFilter filter); Cursor getAllTemplates(WhereFilter filter, String sortBy); Cursor getBlotterWithSplits(String where); long duplicateTransaction(long id); long duplicateTransactionWithMultiplier(long id, int multiplier); long duplicateTransactionAsTemplate(long id); long insertOrUpdate(Transaction transaction); long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes); long insertOrUpdateInTransaction(Transaction transaction, List<TransactionAttribute> attributes); void insertWithoutUpdatingBalance(Transaction transaction); void updateTransactionStatus(long id, TransactionStatus status); void deleteTransaction(long id); void deleteTransactionNoDbTransaction(long id); long insertOrUpdate(Category category, List<Attribute> attributes); Category getCategoryWithParent(long id); List<Long> getCategoryIdsByLeftIds(List<String> leftIds); Category getCategoryByLeft(long left); CategoryTree<Category> getCategoriesTreeWithoutSubTree(long excludingTreeId, boolean includeNoCategory); CategoryTree<Category> getCategoriesTree(boolean includeNoCategory); CategoryTree<Category> getAllCategoriesTree(); Map<Long, Category> getAllCategoriesMap(); List<Category> getCategoriesList(boolean includeNoCategory); Cursor getAllCategories(); List<Category> getAllCategoriesList(); Cursor getCategories(boolean includeNoCategory); Cursor filterCategories(CharSequence titleFilter); Cursor getCategories(boolean includeNoCategory, CharSequence titleFilter); Cursor getCategoriesWithoutSubtree(long id, boolean includeNoCategory); List<Category> getCategoriesWithoutSubtreeAsList(long categoryId); long insertChildCategory(long parentId, Category category); long insertMateCategory(long categoryId, Category category); void deleteCategory(long categoryId); void insertCategoryTreeInTransaction(CategoryTree<Category> tree); void updateCategoryTree(CategoryTree<Category> tree); List<SmsTemplate> getSmsTemplatesForCategory(long categoryId); List<SmsTemplate> getSmsTemplatesByNumber(String smsNumber); Set<String> findAllSmsTemplateNumbers(); Cursor getAllSmsTemplates(); Cursor getSmsTemplatesWithFullInfo(); Cursor getSmsTemplatesWithFullInfo(final String filter); long duplicateSmsTemplateBelowOriginal(long id); ArrayList<Attribute> getAttributesForCategory(long categoryId); ArrayList<Attribute> getAllAttributesForCategory(long categoryId); Attribute getSystemAttribute(SystemAttribute a); Attribute getAttribute(long id); long insertOrUpdate(Attribute attribute); void deleteAttribute(long id); Cursor getAllAttributes(); Map<Long, String> getAllAttributesMap(); Map<Long, String> getAllAttributesForTransaction(long transactionId); EnumMap<SystemAttribute, String> getSystemAttributesForTransaction(long transactionId); void clearSelectedTransactions(long[] ids); void reconcileSelectedTransactions(long[] ids); void deleteSelectedTransactions(long[] ids); long[] storeMissedSchedules(List<RestoredTransaction> restored, long now); int getCustomClosingDay(long accountId, int period); void setCustomClosingDay(long accountId, int period, int closingDay); void deleteCustomClosingDay(long accountId, int period); void updateCustomClosingDay(long accountId, int period, int closingDay); void rebuildRunningBalances(); void rebuildRunningBalanceForAccount(Account account); long fetchBudgetBalance(Map<Long, Category> categories, Map<Long, Project> projects, Budget b); void recalculateAccountsBalances(); void saveRate(ExchangeRate r); void replaceRate(ExchangeRate rate, long originalDate); void saveDownloadedRates(List<ExchangeRate> downloadedRates); ExchangeRate findRate(Currency fromCurrency, Currency toCurrency, long date); List<ExchangeRate> findRates(Currency fromCurrency); List<ExchangeRate> findRates(Currency fromCurrency, Currency toCurrency); ExchangeRateProvider getLatestRates(); ExchangeRateProvider getHistoryRates(); void deleteRate(ExchangeRate rate); void deleteRate(long fromCurrencyId, long toCurrencyId, long date); Total getAccountsTotalInHomeCurrency(); Total[] getAccountsTotal(); Total getAccountsTotal(Currency homeCurrency); List<Long> findAccountsByNumber(String numberEnding); boolean singleCurrencyOnly(); void setDefaultHomeCurrency(); void purgeAccountAtDate(Account account, long date); void deleteOldTransactions(Account account, long date); long getAccountBalanceForTransaction(Account a, Transaction t); long findNearestOlderTransactionId(Account account, long date); long findLatestTransactionDate(long accountId); void updateAccountsLastTransactionDate(); void restoreSystemEntities(); long getLastRunningBalanceForAccount(Account account); }
@Test public void account_number_lookup() { Account account = AccountBuilder.withDb(db) .currency(CurrencyBuilder.createDefault(db)) .title("SB").issuer("Sber").number("1111-2222-3333-5431").create(); final List<Long> res = db.findAccountsByNumber("5431"); assertEquals(1, res.size()); assertEquals((Long) account.id, res.get(0)); }
Beverage { public abstract double cost(); protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); }
@Test public void should_pay_1_when_buy_espresso() { Espresso espresso = new Espresso(false, false); assertTrue(espresso.cost() == 4.0); } @Test public void should_pay_5_when_buy_espresso_with_milk() { Espresso espresso = new Espresso(true, false); assertTrue(espresso.cost() == 5.0); } @Test public void should_pay_7_when_buy_espresso_with_mocha() { Espresso espresso = new Espresso(false, true); assertTrue(espresso.cost() == 7.0); } @Test public void should_pay_8_when_buy_espresso_with_milk_and_mocha() { Espresso espresso = new Espresso(true, true); assertTrue(espresso.cost() == 8.0); }
RemoteControl { public void off(int slot) { if (slot == 1) light.off(); if (slot == 2) ceiling.off(); if (slot == 3) stereo.off(); } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); void on(int slot); void off(int slot); }
@Test public void should_turn_off_stereo_when_press_third_off_button() { Stereo stereo = new Stereo(); RemoteControl remoteControl = new RemoteControl(null, null, stereo); remoteControl.off(3); assertFalse(stereo.getCdStatus()); assertFalse(stereo.getCdStatus()); assertEquals(0, stereo.getVolume()); } @Test public void should_turn_off_light_when_press_first_off_button() { Light light = new Light(); RemoteControl remoteControl = new RemoteControl(light, null, null); remoteControl.off(1); assertFalse(light.status()); } @Test public void should_turn_off_ceiling_when_press_second_off_button() { Ceiling ceiling = new Ceiling(); RemoteControl remoteControl = new RemoteControl(null, ceiling, null); remoteControl.off(2); assertEquals(CeilingSpeed.Off, ceiling.getSpeed()); }
GumballMachine { public MachineStatus getState() { return State; } GumballMachine(int gumballNum, MachineStatus machineStatus); int getGumballNum(); void setGumballNum(int gumballNum); MachineStatus getState(); void setState(MachineStatus state); String insertQuarter(); String turnCrank(); String dispense(); String ejectQuarter(); final String insertedQuarterMessage; }
@Test public void gumball_machine_status_should_be_no_quarter_at_start() { GumballMachine gumballMachine = new GumballMachine(10, MachineStatus.NO_QUARTER); assertEquals(MachineStatus.NO_QUARTER, gumballMachine.getState()); }
WeatherData { public void measurementsChanged(int temp, int humidity, int windPower) { if (temp > 5) { seedingMachine.start(); if (humidity > 65) reapingMachine.start(); } if (temp > 10 && humidity < 55 && windPower < 4) wateringMachine.start(); } WeatherData(SeedingMachine seedingMachine, ReapingMachine reapingMachine, WateringMachine wateringMachine); void measurementsChanged(int temp, int humidity, int windPower); }
@Test public void seeding_machine_should_start_if_temperature_over_5_degree() { weatherData.measurementsChanged(10, 0, 0); assertTrue(seedingMachine.getStatus()); } @Test public void reaping_machine_should_start_if_temperature_over_5_degree_and_humidity_over_65() { weatherData.measurementsChanged(10, 70, 0); assertTrue(reapingMachine.getStatus()); } @Test public void water_machine_should_start_if_temperature_over_10_degree_and_humidity_less_than_55_and_wind_power_less_than_4() { weatherData.measurementsChanged(12, 50, 2); assertTrue(wateringMachine.getStatus()); }
MenuItem { public List<Integer> getHealthRating() { return ingredients.stream() .map(Ingredient::getHealthRating) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); }
@Test public void should_calc_health_rating_Ingredient() { assertEquals(1, flour.getHealthRating()); } @Test public void should_calc_health_rating_for_MenuItem() { assertEquals(2, moonCake.getHealthRating().size()); assertTrue(moonCake.getHealthRating().contains(1)); assertTrue(moonCake.getHealthRating().contains(2)); }
MenuItem { public List<String> getProtein() { return ingredients.stream() .map(Ingredient::getProtein) .collect(Collectors.toList()); } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); }
@Test public void should_calc_protein_for_Ingredient() { assertEquals("100.0 g", flour.getProtein()); } @Test public void should_calc_protein_for_MenuItem() { assertEquals(2, moonCake.getProtein().size()); assertTrue(moonCake.getProtein().contains("100.0 g")); assertTrue(moonCake.getProtein().contains("200.0 g")); }
MenuItem { public List<String> getCalory() { List<String> calories = ingredients.stream() .map(Ingredient::getCalory) .collect(Collectors.toList()); calories.add("Cooking will double calories!!!"); return calories; } MenuItem(List<Ingredient> ingredients); void AddToPot(); void AddWater(); void AddOil(); void Smell(); void Taste(); void Cook(); List<Integer> getHealthRating(); List<String> getProtein(); List<String> getCalory(); }
@Test public void should_calc_calory_for_Ingredient() { assertEquals("10 J", flour.getCalory()); } @Test public void should_calc_calory_for_MenuItem() { assertEquals(3, moonCake.getCalory().size()); assertTrue(moonCake.getCalory().contains("10 J")); assertTrue(moonCake.getCalory().contains("20 J")); assertTrue(moonCake.getCalory().contains("Cooking will double calories!!!")); }
UsingReturn { public String checkSecurity(List<String> people) { String found = ""; for (String name : people) { if (found == "") { if (name.equals("Don")) { sendAlert(); found = "Don"; } if (name.equals("John")) { sendAlert(); found = "John"; } } } return someLaterCode(found); } String checkSecurity(List<String> people); }
@Test public void should_get_alert_message_if_people_names_include_don() { List<String> peopleNames = Arrays.asList("Don", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertDon", alertMessage); } @Test public void should_get_alert_message_if_people_names_include_john() { List<String> peopleNames = Arrays.asList("John", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } @Test public void should_alert_first_matched_people() { List<String> peopleNames = Arrays.asList("John", "Don"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } @Test public void should_not_get_alert_message_if_people_names_does_include_don_and_john() { List<String> peopleNames = Arrays.asList("Martin", "Kent"); UsingReturn usingReturn = new UsingReturn(); String alertMessage = usingReturn.checkSecurity(peopleNames); assertEquals("", alertMessage); }
OrsExample { public double disabilityAmount() { if (seniority < 2) return 0; if (monthsDisabled > 12) return 0; if (isPartTime) return 0; return disabilityAmount; } OrsExample(double seniority, double monthsDisabled, boolean isPartTime); double disabilityAmount(); }
@Test public void should_get_zero_disability_amount_given_seniority_less_than_two() { OrsExample consolidateConditionalExpression = new OrsExample(1, 0, false); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } @Test public void should_get_zero_disability_amount_given_month_disabled_more_than_12() { OrsExample consolidateConditionalExpression = new OrsExample(2, 13, false); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } @Test public void should_get_zero_disability_amount_given_is_part_time() { OrsExample consolidateConditionalExpression = new OrsExample(2, 1, true); assertEquals(0, consolidateConditionalExpression.disabilityAmount(), 0); } @Test public void should_get_ten_disability_amount_given_seniority_greater_than_one_and_disabled_less_than_13_and_is_not_part_time() { OrsExample consolidateConditionalExpression = new OrsExample(2, 1, false); assertEquals(10, consolidateConditionalExpression.disabilityAmount(), 0); }
AndsExample { public double getCharge() { if (onVacation()) if (lengthOfService() > 10) return 1; return 0.5; } AndsExample(double lengthOfService, boolean onVacation); double getCharge(); }
@Test public void should_get_1_given_is_on_vacation_and_length_of_service_greater_than_10() { AndsExample andsExample = new AndsExample(11, true); assertEquals(1, andsExample.getCharge(), 0); } @Test public void should_get_point_5_given_is_not_on_vacation() { AndsExample andsExample = new AndsExample(11, false); assertEquals(0.5, andsExample.getCharge(), 0); } @Test public void should_get_point_5_given_length_of_service_not_greater_than_10() { AndsExample andsExample = new AndsExample(5, true); assertEquals(0.5, andsExample.getCharge(), 0); }
ConsolidateDuplicateConditionalFragments { public double disabilityAmount() { if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } return total; } ConsolidateDuplicateConditionalFragments(boolean isSpecialDeal, double price); double disabilityAmount(); }
@Test public void should_get_disability_amount_given_is_special_deal() { ConsolidateDuplicateConditionalFragments consolidateDuplicateConditionalFragments = new ConsolidateDuplicateConditionalFragments(true, 10); assertEquals(10.5, consolidateDuplicateConditionalFragments.disabilityAmount(), 0); } @Test public void should_get_zero_disability_amount_given_month_disabled_more_than_12() { ConsolidateDuplicateConditionalFragments consolidateDuplicateConditionalFragments = new ConsolidateDuplicateConditionalFragments(false, 10); assertEquals(10.8, consolidateDuplicateConditionalFragments.disabilityAmount(), 0); }
ChargeCalculator { public double getCharge(Date date, double quantity) { double charge; if (date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * winterRate + winterServiceCharge; else charge = quantity * summerRate; return charge; } double getCharge(Date date, double quantity); }
@Test public void should_get_summer_charge_given_date_is_in_summer() { ChargeCalculator chargeCalculator = new ChargeCalculator(); double charge = chargeCalculator.getCharge(new Date(2011, 7, 1), 100); assertEquals(200, charge, 0); } @Test public void should_get_winter_charge_given_date_is_not_in_summer() { ChargeCalculator chargeCalculator = new ChargeCalculator(); double charge = chargeCalculator.getCharge(new Date(2011, 11, 1), 100); assertEquals(400, charge, 0); }
Client { public String getStatement() { String plan = customer() == null ? "Basic Plan" : customer().getPlan(); String customerName = customer() == null ? "occupant" : customer().getName(); int weeksDelinquent = customer() == null ? 0 : customer().getWeeksDelinquentInLastYear(); return plan + " " + customerName + " " + weeksDelinquent; } Client(Site site); String getStatement(); }
@Test public void should_get_basic_statement_given_does_not_have_customer() { Site site = new Site(null); Client client = new Client(site); assertEquals("Basic Plan occupant 0", client.getStatement()); } @Test public void should_get_customer_statement_given_has_customer() { Site site = new Site(new Customer()); Client client = new Client(site); assertEquals("Real Plan Name 100", client.getStatement()); }
Employee { public int payAmount() throws Exception { switch (employeeType.getEmployeeCode()) { case EmployeeType.ENGINEER: return MonthlySalary; case EmployeeType.SALESMAN: return MonthlySalary + Commission; case EmployeeType.MANAGER: return MonthlySalary + Bonus; default: throw new Exception(); } } Employee(int type); int payAmount(); }
@Test public void should_get_pay_amount_for_engineer_given_type_is_engineer() throws Exception { Employee employee = new Employee(EmployeeType.ENGINEER); assertEquals(100, employee.payAmount()); } @Test public void should_get_pay_amount_for_sales_man_given_type_is_sales_man() throws Exception { Employee employee = new Employee(EmployeeType.SALESMAN); assertEquals(120, employee.payAmount()); } @Test public void should_get_pay_amount_for_manager_given_type_is_manager() throws Exception { Employee employee = new Employee(EmployeeType.MANAGER); assertEquals(150, employee.payAmount()); }
ReplaceNestedConditionalWithGuardClauses { public double getPayAmount() { double result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; } ReplaceNestedConditionalWithGuardClauses(boolean isDead, boolean isSeparated, boolean isRetired); double getPayAmount(); }
@Test public void should_get_dead_amount_pay_given_is_dead() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(true, false, false); assertEquals(400, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } @Test public void should_get_separated_amount_pay_given_is_separated_and_not_dead() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, true, false); assertEquals(300, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } @Test public void should_get_separated_amount_pay_given_is_retired_and_not_dead_and_not_seperated() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, false, true); assertEquals(200, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); } @Test public void should_get_normal_amount_pay_given_is_not_retired_and_not_dead_and_not_seperated() { ReplaceNestedConditionalWithGuardClauses replaceNestedConditionalWithGuardClauses = new ReplaceNestedConditionalWithGuardClauses(false, false, false); assertEquals(100, replaceNestedConditionalWithGuardClauses.getPayAmount(), 0); }
ReversingTheConditions { public double getAdjustedCapital() { double result = 0.0; if (capital > 0.0) { if (intRate > 0.0 && duration > 0.0) { result = (income / duration) * AdjFactor; } } return result; } ReversingTheConditions(double capital, double intRate, double duration, double income); double getAdjustedCapital(); }
@Test public void should_get_zero_adjusted_capital_given_capital_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(-1, 10, 10, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } @Test public void should_get_zero_adjusted_capital_given_init_rate_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, -1, 10, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } @Test public void should_get_zero_adjusted_capital_given_duration_is_less_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, 10, -1, 10); assertEquals(0, reversingTheConditions.getAdjustedCapital(), 0); } @Test public void should_get_adjusted_capital_given_duration_and_capital_and_init_rate_all_are_greater_than_zero() { ReversingTheConditions reversingTheConditions = new ReversingTheConditions(10, 10, 5, 10); assertEquals(4, reversingTheConditions.getAdjustedCapital(), 0); }
InlineTemp { public boolean isAmountOver1000() { double amount = order.getAmount(); return amount > 1000; } InlineTemp(int amount); boolean isAmountOver1000(); }
@Test public void should_get_true_given_amount_over_1000() { InlineTemp inlineTemp = new InlineTemp(2000); assertTrue(inlineTemp.isAmountOver1000()); } @Test public void should_get_false_given_amount_less_than_1000() { InlineTemp inlineTemp = new InlineTemp(500); assertFalse(inlineTemp.isAmountOver1000()); }
Beverage { public String getDescription() { return ""; } protected Beverage(boolean milk, boolean mocha); boolean isMilk(); boolean isMocha(); String getDescription(); abstract double cost(); }
@Test public void should_return_espresso_when_get_espresso_description() { Espresso espresso = new Espresso(false, false); assertTrue(Objects.equals(espresso.getDescription(), "Espresso")); }
InlineMethod { public int getRating() { return (moreThanFiveLateDeliveries()) ? 2 : 1; } InlineMethod(double numberOfLateDeliveries); int getRating(); }
@Test public void should_get_rating_2_given_more_than_five_late_deliveries() { final int numberOfLateDeliveries = 6; InlineMethod inlineMethod = new InlineMethod(numberOfLateDeliveries); assertEquals(2, inlineMethod.getRating()); } @Test public void should_get_rating_1_given_less_than_five_late_deliveries() { final int numberOfLateDeliveries = 4; InlineMethod inlineMethod = new InlineMethod(numberOfLateDeliveries); assertEquals(1, inlineMethod.getRating()); }
ExtractMethod { public String printOwning(String name, int previousAmount) { String customerOwns = ""; double outstanding = 10 + previousAmount; customerOwns += "****/n"; customerOwns += "**Customer Owns**/n"; customerOwns += "****/n"; for (Order order : orders) { outstanding += order.getAmount(); } customerOwns += "name:" + name + "/n"; customerOwns += "amount:" + outstanding; return customerOwns; } ExtractMethod(List<Order> orders); String printOwning(String name, int previousAmount); }
@Test public void should_get_right_customer_owns() { String expectedCustomerOwns = "****/n**Customer Owns**/n****/nname:ExtractMethod/namount:140.0"; List<Order> orders = Arrays.asList(new Order(10), new Order(20)); ExtractMethod extractMethod = new ExtractMethod(orders); String owns = extractMethod.printOwning("ExtractMethod", 100); assertEquals(expectedCustomerOwns, owns); }
RemoveAssignmentsToParameters { public int discount(int inputVal, int quantity, int yearToDate) { if (inputVal > 50) inputVal -= 2; if (quantity > 100) inputVal -= 1; if (yearToDate > 10000) inputVal -= 4; return inputVal; } int discount(int inputVal, int quantity, int yearToDate); }
@Test public void should_get_discount_7_given_value_is_over_50_and_quantity_is_over_100_and_yearToEnd_is_over_10000() { RemoveAssignmentsToParameters removeAssignmentsToParameters = new RemoveAssignmentsToParameters(); assertEquals(53, removeAssignmentsToParameters.discount(60, 200, 20000)); } @Test public void should_get_discount_5_given_value_is_less_than_50_and_quantity_is_over_100_and_yearToEnd_is_over_10000() { RemoveAssignmentsToParameters removeAssignmentsToParameters = new RemoveAssignmentsToParameters(); assertEquals(35, removeAssignmentsToParameters.discount(40, 200, 20000)); }
ReplaceTempWithQuery { public double getPrice() { double basePrice = quantity * itemPrice; double discountFactor; if (basePrice > 1000) discountFactor = 0.95; else discountFactor = 0.98; return basePrice * discountFactor; } ReplaceTempWithQuery(double quantity, double itemPrice); double getPrice(); }
@Test public void should_get_right_discount_given_base_price_is_over_1000() { ReplaceTempWithQuery replaceTempWithQuery = new ReplaceTempWithQuery(1000, 2); assertEquals(1900, replaceTempWithQuery.getPrice(), 2); } @Test public void should_get_right_discount_given_base_price_is_less_than_1000() { ReplaceTempWithQuery replaceTempWithQuery = new ReplaceTempWithQuery(400, 2); assertEquals(784, replaceTempWithQuery.getPrice(), 2); }
ReplaceMethodWithMethodObject { public int gamma(int inputVal, int quantity, int yearToDate) { int importantValue1 = inputVal * quantity; int importantValue2 = inputVal * yearToDate + 100; if ((yearToDate - importantValue1) > 100) importantValue2 -= 20; int importantValue3 = importantValue2 * 7; return importantValue3 - 2 * importantValue1; } int gamma(int inputVal, int quantity, int yearToDate); }
@Test public void should_get_right_gamma_given() { ReplaceMethodWithMethodObject replaceMethodWithMethodObject = new ReplaceMethodWithMethodObject(); int gamma = replaceMethodWithMethodObject.gamma(10, 5, 100); assertEquals(7600, gamma); }
SeparateQueryFromModifier { public String checkSecurity(String[] people) { String found = foundMiscreant(people); return someLaterCode(found); } String checkSecurity(String[] people); }
@Test public void should_get_alert_message_if_people_names_include_don() { String[] peopleNames = new String[]{"Don", "Kent"}; SeparateQueryFromModifier separateQueryFromModifier = new SeparateQueryFromModifier(); String alertMessage = separateQueryFromModifier.checkSecurity(peopleNames); assertEquals("AlertDon", alertMessage); } @Test public void should_get_alert_message_if_people_names_include_john() { String[] peopleNames = new String[]{"John", "Kent"}; SeparateQueryFromModifier separateQueryFromModifier = new SeparateQueryFromModifier(); String alertMessage = separateQueryFromModifier.checkSecurity(peopleNames); assertEquals("AlertJohn", alertMessage); } @Test public void should_not_get_alert_message_if_people_names_does_include_don_and_john() { String[] peopleNames = new String[]{"Martin", "Kent"}; SeparateQueryFromModifier separateQueryFromModifier = new SeparateQueryFromModifier(); String alertMessage = separateQueryFromModifier.checkSecurity(peopleNames); assertEquals("null", alertMessage); }
RemoteControl { public void on(int slot) { if (slot == 1) light.on(); if (slot == 2) ceiling.high(); if (slot == 3) { stereo.on(); stereo.setCdStatus(true); stereo.setVolume(11); } } RemoteControl(Light light, Ceiling ceiling, Stereo stereo); void on(int slot); void off(int slot); }
@Test public void should_turn_on_light_when_press_first_on_button() { Light light = new Light(); RemoteControl remoteControl = new RemoteControl(light, null, null); remoteControl.on(1); assertTrue(light.status()); } @Test public void should_turn_on_ceiling_when_press_second_on_button() { Ceiling ceiling = new Ceiling(); RemoteControl remoteControl = new RemoteControl(null, ceiling, null); remoteControl.on(2); assertEquals(CeilingSpeed.High, ceiling.getSpeed()); } @Test public void should_turn_on_stereo_when_press_third_on_button() { Stereo stereo = new Stereo(); RemoteControl remoteControl = new RemoteControl(null, null, stereo); remoteControl.on(3); assertTrue(stereo.getStereoStatus()); assertTrue(stereo.getCdStatus()); assertEquals(11, stereo.getVolume()); }
HideMethod { public String getLastReadingName() { List<String> readings = Arrays.asList("Refactoring", "Clean Code"); return getLast(readings); } String getLastReadingName(); String getLast(List<String > readings); }
@Test public void should_get_last_reading_name() { HideMethod hideMethod = new HideMethod(); assertEquals("Clean Code", hideMethod.getLastReadingName()); }
DateCalculator { public Date getDate() { return new Date(previousDate.getYear(), previousDate.getMonth(), previousDate.getDate() + 1); } DateCalculator(Date previousDate); Date getDate(); }
@Test public void should_get_correct_next_day() { Date previousDate = new Date(2011, 10, 11); DateCalculator calculateDate = new DateCalculator(previousDate); Date nextDay = new Date(2011, 10, 12); assertEquals(nextDay, calculateDate.getDate()); }
DateManager { public Date getDate() { return new Date(previousDate.getYear(), previousDate.getMonth(), previousDate.getDate() + 1); } DateManager(Date previousDate); Date getDate(); }
@Test public void should_get_correct_next_day() { Date previousDate = new Date(2011, 11, 11); DateManager calculateDate = new DateManager(previousDate); Date nextDay = new Date(2011, 11, 12); assertEquals(nextDay, calculateDate.getDate()); }
PersonForExtractClass { public String getTelephoneNumber() { return ("(" + officeAreaCode + ") ") + officeNumber; } PersonForExtractClass(String officeAreaCode, String officeNumber); String getTelephoneNumber(); String getName(); void setName(String name); }
@Test public void should_get_correct_telephone_number() { PersonForExtractClass personForExtractClass = new PersonForExtractClass("CA", "01"); assertEquals("(CA) 01", personForExtractClass.getTelephoneNumber()); }
IntRange { public boolean includes(int arg) { return arg >= low && arg <= high; } IntRange(int low, int high); boolean includes(int arg); void grow(int factor); }
@Test public void should_not_include_when_number_is_less_than_low_and_greater_than_high() { IntRange intRange = new IntRange(50, 100); assertFalse(intRange.includes(150)); } @Test public void should_include_when_number_is_between_low_and_high() { IntRange intRange = new IntRange(50, 100); assertTrue(intRange.includes(80)); }
Customer { public String getCustomerName() { return customerName; } Customer(String customerName); String getCustomerName(); }
@Test public void should_get_number_of_orders_for_customer() { Order kentOrder1 = new Order("Kent"); Order kentOrder2 = new Order("Kent"); assertEquals("Kent", kentOrder1.getCustomer().getCustomerName()); assertEquals("Kent", kentOrder2.getCustomer().getCustomerName()); }
Currency { public String getCode() { return code; } Currency(String code); String getCode(); }
@Test public void should_two_currencies_with_the_same_unit_are_equal() { Currency usdCurrency1 = new Currency("USD"); Currency usdCurrency2 = new Currency("USD"); assertEquals(usdCurrency1.getCode(), usdCurrency2.getCode()); }
EnergyCalculator { public double potentialEnergy(double mass, double height) { return mass * height * 9.81; } double potentialEnergy(double mass, double height); }
@Test public void should_get_potential_energy() { EnergyCalculator energyCalculator = new EnergyCalculator(); double potentialEnergy = energyCalculator.potentialEnergy(10, 10); assertTrue(potentialEnergy == 981); }
LifelineSite { public Dollars charge() { int usage = readings[0].getAmount() - readings[1].getAmount(); return charge(usage); } void addReading(Reading newReading); Dollars charge(); }
@Test(expected = NullPointerException.class) public void should_throw_exception_given_no_reading() { LifelineSite subject = new LifelineSite(); subject.charge(); }
BusinessSite { public Dollars charge() { int usage = readings[lastReading].getAmount() - readings[lastReading - 1].getAmount(); return charge(usage); } void addReading(Reading newReading); Dollars charge(); }
@Test(expected = NullPointerException.class) public void should_throw_exception_given_no_reading() { BusinessSite subject = new BusinessSite(); subject.charge(); }
ResidentialSite { public Dollars charge() { int i = 0; while (readings[i] != null) i++; int usage = readings[i - 1].getAmount() - readings[i - 2].getAmount(); Date end = readings[i - 1].getDate(); Date start = readings[i - 2].getDate(); start.setDate(start.getDate() + 1); return charge(usage, start, end); } ResidentialSite(Zone zone); void addReading(Reading newReading); Dollars charge(); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void should_throw_exception_given_no_reading() { ResidentialSite subject = CreateResidentialSite(); subject.charge(); }
DisabilitySite { public Dollars charge() { int i; for (i = 0; readings[i] != null; i++) ; int usage = readings[i - 1].getAmount() - readings[i - 2].getAmount(); Date end = readings[i - 1].getDate(); Date start = readings[i - 2].getDate(); start.setDate(start.getDate() + 1); return charge(usage, start, end); } DisabilitySite(Zone zone); void addReading(Reading newReading); Dollars charge(); }
@Test(expected = ArrayIndexOutOfBoundsException.class) public void should_throw_exception_given_no_reading() { DisabilitySite subject = createDisabilitySite(); subject.charge(); }
Pixelate { public static Bitmap fromAsset(@NonNull AssetManager assetManager, @NonNull String path, @NonNull PixelateLayer... layers) throws IOException { return fromInputStream(assetManager.open(path), layers); } static Bitmap fromAsset(@NonNull AssetManager assetManager, @NonNull String path, @NonNull PixelateLayer... layers); static Bitmap fromInputStream(@NonNull InputStream inputStream, @NonNull PixelateLayer... layers); static Bitmap fromBitmap(@NonNull Bitmap in, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @Nullable Rect outBounds, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Canvas canvas, @NonNull Rect outBounds, @NonNull Paint paint, @NonNull PixelateLayer... layers); }
@Test public void testFromAsset() throws Exception { }
Pixelate { public static Bitmap fromInputStream(@NonNull InputStream inputStream, @NonNull PixelateLayer... layers) throws IOException { Bitmap in = BitmapFactory.decodeStream(inputStream); inputStream.close(); Bitmap out = fromBitmap(in, layers); in.recycle(); return out; } static Bitmap fromAsset(@NonNull AssetManager assetManager, @NonNull String path, @NonNull PixelateLayer... layers); static Bitmap fromInputStream(@NonNull InputStream inputStream, @NonNull PixelateLayer... layers); static Bitmap fromBitmap(@NonNull Bitmap in, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @Nullable Rect outBounds, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Canvas canvas, @NonNull Rect outBounds, @NonNull Paint paint, @NonNull PixelateLayer... layers); }
@Test public void testFromInputStream() throws Exception { }
Pixelate { public static Bitmap fromBitmap(@NonNull Bitmap in, @NonNull PixelateLayer... layers) { Bitmap out = Bitmap.createBitmap(in.getWidth(), in.getHeight(), Bitmap.Config.ARGB_8888); render(in, out, layers); return out; } static Bitmap fromAsset(@NonNull AssetManager assetManager, @NonNull String path, @NonNull PixelateLayer... layers); static Bitmap fromInputStream(@NonNull InputStream inputStream, @NonNull PixelateLayer... layers); static Bitmap fromBitmap(@NonNull Bitmap in, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @Nullable Rect outBounds, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Canvas canvas, @NonNull Rect outBounds, @NonNull Paint paint, @NonNull PixelateLayer... layers); }
@Test public void testFromBitmap() throws Exception { }
Pixelate { public static void render(@NonNull Bitmap in, @NonNull Bitmap out, @NonNull PixelateLayer... layers) { render(in, null, out, layers); } static Bitmap fromAsset(@NonNull AssetManager assetManager, @NonNull String path, @NonNull PixelateLayer... layers); static Bitmap fromInputStream(@NonNull InputStream inputStream, @NonNull PixelateLayer... layers); static Bitmap fromBitmap(@NonNull Bitmap in, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Bitmap out, @Nullable Rect outBounds, @NonNull PixelateLayer... layers); static void render(@NonNull Bitmap in, @Nullable Rect inBounds, @NonNull Canvas canvas, @NonNull Rect outBounds, @NonNull Paint paint, @NonNull PixelateLayer... layers); }
@Test public void testRender() throws Exception { }
ArangoDao { public ArangoDatabase db() { return _db; } ArangoDao(Class<E> entityType, ArangoCollection collection); ArangoDao(Class<E> entityType, ArangoCollection collection, IdGenerator idGenerator); ArangoCollection collection(); ArangoCursor<E> cursor(Condition query); ArangoCursor<T> cursor(Condition query, Class<T> type); ArangoCursor<T> cursor(Condition query, final AqlQueryOptions options, Class<T> type); ArangoCursor<T> cursor(final String query, final Map<String, Object> bindVars, final AqlQueryOptions options, Class<T> type); ArangoCursor<T> cursor(final String query, final Map<String, Object> bindVars, Class<T> type); List<T> queryField(Condition condition, String field, Class<T> type); List<T> queryField(Condition condition, String field, AqlQueryOptions options, Class<T> type); List<E> query(Condition condition); List<T> query(Condition condition, Class<T> type); List<T> query(Condition condition, AqlQueryOptions options, Class<T> type); List<E> query(String query); List<T> query(String query, Class<T> type); List<T> query(String query, Map<String, Object> bindVars, Class<T> type); List<T> query(String query, Map<String, Object> bindVars, AqlQueryOptions options, Class<T> type); T queryFieldFirst(Condition condition, String field, Class<T> type); T queryFieldFirst(Condition condition, String field, AqlQueryOptions options, Class<T> type); E queryFirst(final String query); T queryFirst(final String query, Class<T> type); T queryFirst(final String query, Map<String, Object> bindVars, Class<T> type); T queryFirst(final String query, Map<String, Object> bindVars, AqlQueryOptions options, Class<T> type); E queryFirst(Condition query); T queryFirst(Condition query, Class<T> type); T queryFirst(Condition query, AqlQueryOptions options, Class<T> type); long count(Condition query); boolean exist(Condition query); void genarateId(Entity object); void save(E object, DocumentCreateOptions options); void save(E object); void saveSub(Entity object); void saveSub(Entity object, DocumentCreateOptions options); void save(Collection<E> objects, DocumentCreateOptions options); void save(Collection<E> objects); void save(E[] objects, DocumentCreateOptions options); void save(E[] objects); int delete(String key); int delete(String key, DocumentDeleteOptions options); int delete(String[] ids); int delete(String[] ids, DocumentDeleteOptions options); int delete(Condition query, DocumentDeleteOptions options); int delete(Condition query); E find(Condition query); E find(String key); T find(Condition query, Class<T> clazz); T find(String key, Class<T> clazz); T findXById(String key, String field, Class<T> clazz); E[] find(String[] ids); T[] find(String[] ids, Class<T> clazz); List<E> list(Condition query); List<T> list(Condition query, Class<T> clazz); void page(Condition query, PageResult pageResult); void page(Condition query, PageResult pageResult, Class<T> type); @SuppressWarnings("unchecked") void page(Condition query, PageResult pageResult, AqlQueryOptions options, Class<T> type); T findAndDelete(Condition query, Class<T> clazz); T findAndModify(Condition query, Class<T> clazz); void update(Entity entity); void update(Entity entity, DocumentUpdateOptions options); void updateXById(String key, String name, Object val); void updateXById(String key, String name, Object val, DocumentUpdateOptions options); void update(String key, Map<String, Object> update); void update(String key, Map<String, Object> update, DocumentUpdateOptions options); int update(Condition query, Map<String, Object> update); int upsert(Condition query, Map<String, Object> update); ArangoDatabase db(); Class<E> getEntityType(); String getTableName(); }
@Test(groups = "ignore") public void seqTest() throws UnknownHostException { ArangoDatabase db = _fooDao.db(); System.out.println("xxx: " + ArangoUtil.nextSeq(db, "xxx")); System.out.println("xxx: " + ArangoUtil.nextSeq(db, "xxx")); System.out.println("yyy: " + ArangoUtil.nextSeq(db, "yyy")); System.out.println("yyy: " + ArangoUtil.nextSeq(db, "yyy")); }
CronParser { public static Matcher parse(String cron) throws InvalidCronException { return new CronParser(cron).parse(); } CronParser(final char[] cron); CronParser(final String cron); static Matcher parse(String cron); static Matcher parse(final char[] cron); Matcher parse(); }
@Test public void testWeek() { Matcher matcher; matcher = new CronParser("* * * * * */2").parse(); assertFalse(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 2, true))); assertFalse(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 3, true))); assertTrue(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 4, true))); assertFalse(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 5, true))); } @Test public void test() { Matcher matcher; matcher = new CronParser("* * * * *").parse(); matcher = new CronParser("* * *").parse(); matcher = new CronParser("").parse(); matcher = new CronParser("1,3,4 5,6-8 8/3,0-10/2|12,34 * 2,111,33").parse(); matcher = new CronParser("8-10/3,5 1").parse(); int i = 0; } @Test public void testMinute() { Matcher matcher; assertSame(Matcher.MATCH_ALL, new CronParser((String) null).parse()); assertSame(Matcher.MATCH_ALL, new CronParser("* *").parse()); assertSame(Matcher.MATCH_ALL, new CronParser("* * *").parse()); assertSame(Matcher.MATCH_ALL, new CronParser("* * * * * * * * *").parse()); matcher = new CronParser("0-100 * * * *").parse(); assertTrue(matcher instanceof MinuteMatcher); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 3, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 4, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 59, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 60, 1, true))); matcher = new CronParser("*/2 * * * *").parse(); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 100, 1, true))); matcher = new CronParser("54,1-4/2,55,100 * * * *").parse(); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 3, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 4, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 55, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 59, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 60, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 100, 1, true))); matcher = new CronParser("0-59/3,5,8 * * *").parse(); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 3, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 4, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 5, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 6, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 7, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 8, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 59, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 60, 1, true))); matcher = new CronParser("3/2 * * * *").parse(); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 3, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 4, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 59, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 60, 1, true))); } @Test public void testHour() { Matcher matcher; matcher = new CronParser("3,5,8 1,2,3 * *").parse(); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 0, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 2, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 3, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 4, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 5, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 1, 8, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 2, 3, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 1, 3, 3, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 4, 3, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 24, 3, 1, true))); } @Test public void testDay() { Matcher matcher; matcher = new CronParser("* * 2,4,*/3 *").parse(); assertTrue(matcher.match(createTime(1, 1, 1, 0, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 2, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 3, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 4, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 1, 1, 5, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 1, 1, 6, 1, 1, 1, true))); } @Test public void testMouth() { Matcher matcher; matcher = new CronParser("* * * */2 * *").parse(); assertFalse(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 2014, 2, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 2014, 3, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 2014, 4, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 2014, 5, 1, 1, 1, 1, true))); } @Test public void testYear() { Matcher matcher; matcher = new CronParser("* * * * */2 *").parse(); assertTrue(matcher.match(createTime(1, 2010, 1, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 2011, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 2012, 1, 1, 1, 1, 1, true))); assertFalse(matcher.match(createTime(1, 2013, 1, 1, 1, 1, 1, true))); assertTrue(matcher.match(createTime(1, 2014, 1, 1, 1, 1, 1, true))); }
ActionMacroPath { public static Parser newParser() { return new Parser(); } ActionMacroPath(String key, Map<String, String> params); static Parser newParser(); final String key; final Map<String, String> params; }
@Test public void test() { ActionMacroPath.Parser parser = ActionMacroPath.newParser(); parser.add("/user"); parser.add("GET:/user"); parser.add("GET:/user/$id"); parser.add("GET:/user/1234/send/4567"); parser.add("GET:/user/$id/send/$to"); parser.add("GET:/user/$id/fetch/$to"); ActionMacroPath macroPath = null; macroPath = parser.parse("/user"); assertEquals(macroPath.key, "/user"); assertTrue(macroPath.params.isEmpty()); macroPath = parser.parse("GET:/user"); assertEquals(macroPath.key, "GET:/user"); assertTrue(macroPath.params.isEmpty()); macroPath = parser.parse("GET:/user/1234/send/4567"); assertEquals(macroPath.key, "GET:/user/1234/send/4567"); assertTrue(macroPath.params.isEmpty()); macroPath = parser.parse("GET:/user/9527"); assertEquals(macroPath.key, "GET:/user/$id"); assertEquals(macroPath.params.get("id"), "9527"); macroPath = parser.parse("GET:/user/9527/send/12345"); assertEquals(macroPath.key, "GET:/user/$id/send/$to"); assertEquals(macroPath.params.size(), 2); assertEquals(macroPath.params.get("id"), "9527"); assertEquals(macroPath.params.get("to"), "12345"); macroPath = parser.parse("GET:/user/9527/fetch/12345"); assertEquals(macroPath.key, "GET:/user/$id/fetch/$to"); assertEquals(macroPath.params.size(), 2); assertEquals(macroPath.params.get("id"), "9527"); assertEquals(macroPath.params.get("to"), "12345"); }
Scheduler { public void addTask(String cron, Task task) throws InvalidCronException { initialize(); this.addTask(CronParser.parse(cron), this.executorFactory.createTaskExecutor(task)); } Scheduler(); void setDaemon(boolean daemon); void setTimeZone(int timeZone); void setTimeOffset(int timeOffset); int getTimeOffset(); void setUseNotifyThread(boolean useNotifyThread); void setExecutorFactory(TaskExecutorFactory executorFactory); void setExecutorFactory(ExecutorService executorService); boolean isStarted(); boolean isPaused(); boolean isUseNotifyThread(); boolean isDaemon(); void addTask(String cron, Task task); boolean remove(final Task task); void start(); void stop(); void pauseAllIfSupport(); void goonAllIfPaused(); }
@Test(groups = {"ignore"}) public void schedule() throws InterruptedException { Scheduler scheduler = new Scheduler(); scheduler.addTask("*", new Task() { @Override public void execute(TaskContext context) { println(" *", context.getTime()); } @Override public String getTaskName() { return "*"; } }); scheduler.addTask("*/2", new Task() { @Override public void execute(TaskContext context) { println(" */2", context.getTime()); } @Override public String getTaskName() { return "*/2"; } }); scheduler.addTask("*/3", new Task() { @Override public void execute(TaskContext context) { println(" */3", context.getTime()); } @Override public String getTaskName() { return "*/3"; } }); scheduler.addTask("40,41,42,43,44", new Task() { @Override public void execute(TaskContext context) { println(" 40,41,42,43,44", context.getTime()); } @Override public String getTaskName() { return "list"; } }); startScheduler(scheduler); } @Test(groups = {"ignore"}) public void schedule3() { final Scheduler scheduler = new Scheduler(); scheduler.addTask("*", new Task() { @Override public void execute(TaskContext context) { println(" click", context.getTime()); throw new RuntimeException("exception"); } @Override public String getTaskName() { return "exception"; } }); startScheduler(scheduler); } @Test(groups = {"ignore"}) public void schedule4() { final Scheduler scheduler = new Scheduler(); scheduler.addTask("*", new MatchableTask() { @Override public void execute(TaskContext context) { println(" click", context.getTime()); } @Override public String getTaskName() { return "exception"; } @Override public boolean match(Time time) { boolean result = (time.minute + 1) % 3 == 0; println(result ? "run:" : "skip", time); return result; } }); startScheduler(scheduler); }
ClusteringController { public String getRepositoryName() throws RepositoryException{ Session repositorySession = newSession(); try { return repositorySession.getRepository().getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME); } finally { repositorySession.logout(); } } void setNewNodeName( String newNodeName ); String getNewNodeName(); String getNodeNamePattern(); void setNodeNamePattern( String nodeNamePattern ); String getParentPath(); void setParentPath( String parentPath ); Set<String> getNodes(); String searchForNodes(); String loadChildren(); String addChildNode(); String getRepositoryName(); }
@Test public void shouldReturnValidRepositoryName() throws Exception { assertEquals("sample", clusteringController.getRepositoryName()); }
FederationController { public String getRepositoryName() throws RepositoryException{ Session repositorySession = newSession(); try { return repositorySession.getRepository().getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME); } finally { repositorySession.logout(); } } Map<String, String> getExternalSources(); String getExternalSource(); void setExternalSource( String externalSource ); Set<String> getNodes(); String loadChildren(); String getRepositoryName(); }
@Test public void shouldReturnValidRepositoryName() throws Exception { assertEquals("federated-repository", federationController.getRepositoryName()); }
SessionProducer { @RequestScoped @Produces public Session getSession() throws RepositoryException { LOGGER.info("Creating new session..."); return sampleRepository.login(); } @RequestScoped @Produces Session getSession(); void logoutSession( @Disposes final Session session ); }
@Test public void shouldProduceValidSession() throws Exception { assertNotNull(sessionProducer); assertNotNull(sessionProducer.getSession()); }
CDIController { public String getRepositoryName() { return repositorySession.getRepository().getDescriptor(org.modeshape.jcr.api.Repository.REPOSITORY_NAME); } void setNewNodeName( String newNodeName ); String getNewNodeName(); String getParentPath(); void setParentPath( String parentPath ); Set<String> getChildren(); void loadChildren(); void addChildNode(); String getRepositoryName(); }
@Test public void shouldReturnValidRepositoryName() throws Exception { assertEquals("sample", cdiController.getRepositoryName()); }
Helper { public static ITabularFormula createRandomFormula(Random random, int varCount, int clausesCount) { int mMax = getMaxNumberOfUniqueTriplets(varCount); if (clausesCount > mMax) { throw new IllegalArgumentException(MessageFormat .format("3-SAT formula of {0} variables may have at most {1} valuable clauses, but requested to create formula with " + clausesCount + " clauses", varCount, mMax)); } ITabularFormula formula = new SimpleFormula(); for (int i = 0; i < clausesCount && formula.getPermutation().size() < varCount; i++) { formula.add(createRandomTriplet(random, varCount)); } return formula; } static ObjectArrayList createCTF(ITabularFormula formula); static ITabularFormula createRandomFormula(Random random, int varCount, int clausesCount); static ITriplet createRandomTriplet(Random random, int varCount); static void prettyPrint(ITabularFormula formula); static StringBuilder buildPrettyOutput(ITabularFormula formula); static void saveToDIMACSFileFormat(ITabularFormula formula, String filename); static ITabularFormula loadFromFile(String filename); static ITabularFormula createFormula(int... values); static ITabularFormula createRandomFormula(int seed, int nMax); static void printLine(char c, int length); static void unify(ObjectArrayList cts); static int getCanonicalVarName3(int varName1, int varName2, int[] canonicalName); static void saveCTS(String filenamePrefix, ObjectArrayList cts); static void printFormulas(ObjectArrayList formulas); static void printBits(byte keys); static void completeToCTS(ObjectArrayList ctf, IPermutation variables); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, Properties statistics); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, ICompactTripletsStructure sBasic, Properties statistics); static void writeToImage(IHyperStructure hs, final ObjectArrayList route, final ObjectArrayList markers, String filename); static void convertCTStructuresToRomanovSKTFileFormat(ObjectArrayList cts, String filename); static ObjectArrayList findNonEmptyIntersections(IHyperStructure hs, IVertex vertex); static boolean evaluate(ObjectArrayList ctf, ObjectArrayList route); static ObjectArrayList cloneStructures(ObjectArrayList ct); static int readInt(InputStream input); static String getImplementationVersionFromManifest(String implementationTitle); static ObjectArrayList loadHSS(String hssPath); static void saveHSS(String hssPath, ObjectArrayList hss); static ObjectArrayList findHSSRouteByReduce(ObjectArrayList hss, String hssTempPath); static final String IMPLEMENTATION_VERSION; static final String INITIAL_FORMULA_LOAD_TIME; static final String INITIAL_FORMULA_VAR_COUNT; static final String INITIAL_FORMULA_CLAUSES_COUNT; static final String CTF_CREATION_TIME; static final String CTF_COUNT; static final String CTS_CREATION_TIME; static final String CTS_UNIFICATION_TIME; static final String BASIC_CTS_INITIAL_CLAUSES_COUNT; static final String HSS_CREATION_TIME; static final String NUMBER_OF_HSS_TIERS_BUILT; static final String BASIC_CTS_FINAL_CLAUSES_COUNT; static final String SEARCH_HSS_ROUTE_TIME; static boolean UsePrettyPrint; static boolean EnableAssertions; static boolean UseUniversalVarNames; }
@Test public void testCreateRandomFormulaWithRespectToMaxM() { ITabularFormula formula = Helper.createRandomFormula(new Random(), 3, 6); assertEquals(3, formula.getVarCount()); try { formula = Helper.createRandomFormula(new Random(), 4, 700); Assert.fail("This implementation assumes duplicated triplets are not allowed"); } catch (IllegalArgumentException e) { assertEquals("3-SAT formula of 4 variables may have at most 64 valuable clauses, but requested to create formula with 700 clauses", e.getMessage()); } }
SimpleTier extends SimpleTripletPermutation implements ITier { public void swapAB() { super.swapAB(); if (size == 0) { return; } int keys_oo51oooo = keys_73516240 & 0x30; int keys_oooo62oo = keys_73516240 & 0x0C; keys_73516240 = (byte) ((keys_73516240 & 0xC3) | ((keys_oo51oooo >> 2) & 0x3F) | (keys_oooo62oo << 2)); } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testSwapAB() { ITier tier; tier = new SimpleTier(1, 2, 3); tier.add(_000_instance); tier.swapAB(); assertTrue(tier.contains(_000_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_001_instance); tier.swapAB(); assertTrue(tier.contains(_001_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_010_instance); tier.swapAB(); assertTrue(tier.contains(_100_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_011_instance); tier.swapAB(); assertTrue(tier.contains(_101_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_100_instance); tier.swapAB(); assertTrue(tier.contains(_010_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_101_instance); tier.swapAB(); assertTrue(tier.contains(_011_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_110_instance); tier.swapAB(); assertTrue(tier.contains(_110_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_111_instance); tier.swapAB(); assertTrue(tier.contains(_111_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void swapAC() { super.swapAC(); if (size == 0) { return; } int keys_o3o1oooo = keys_73516240 & 0x50; int keys_oooo6o4o = keys_73516240 & 0x0A; keys_73516240 = (byte) ((keys_73516240 & 0xA5) | ((keys_o3o1oooo >> 3) & 0x1F) | (keys_oooo6o4o << 3)); } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testSwapAC() { ITier tier; tier = new SimpleTier(1, 2, 3); tier.add(_000_instance); tier.swapAC(); assertTrue(tier.contains(_000_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_001_instance); tier.swapAC(); assertTrue(tier.contains(_100_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_010_instance); tier.swapAC(); assertTrue(tier.contains(_010_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_011_instance); tier.swapAC(); assertTrue(tier.contains(_110_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_100_instance); tier.swapAC(); assertTrue(tier.contains(_001_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_101_instance); tier.swapAC(); assertTrue(tier.contains(_101_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_110_instance); tier.swapAC(); assertTrue(tier.contains(_011_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_111_instance); tier.swapAC(); assertTrue(tier.contains(_111_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void swapBC() { super.swapBC(); if (size == 0) { return; } int keys_o3ooo2oo = keys_73516240 & 0x44; int keys_oo5ooo4o = keys_73516240 & 0x22; keys_73516240 = (byte) ((keys_73516240 & 0x99) | ((keys_o3ooo2oo >> 1) & 0x7F) | (keys_oo5ooo4o << 1)); } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testSwapBC() { ITier tier; tier = new SimpleTier(1, 2, 3); tier.add(_000_instance); tier.swapBC(); assertTrue(tier.contains(_000_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_001_instance); tier.swapBC(); assertTrue(tier.contains(_010_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_010_instance); tier.swapBC(); assertTrue(tier.contains(_001_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_011_instance); tier.swapBC(); assertTrue(tier.contains(_011_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_100_instance); tier.swapBC(); assertTrue(tier.contains(_100_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_101_instance); tier.swapBC(); assertTrue(tier.contains(_110_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_110_instance); tier.swapBC(); assertTrue(tier.contains(_101_instance)); tier = new SimpleTier(1, 2, 3); tier.add(_111_instance); tier.swapBC(); assertTrue(tier.contains(_111_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void adjoinRight(ITier tier) { int tier_keys_73516240 = ((SimpleTier) tier).keys_73516240; int this_keys_o6o2o4o0 = (((tier_keys_73516240 >> 1) & 0x7F) | tier_keys_73516240) & 0x55; int this_keys_7o3o5o1o = ((this_keys_o6o2o4o0 << 1)); int this_keys_76325410 = (this_keys_o6o2o4o0 | this_keys_7o3o5o1o) & get_keys_76325410(); keys_73516240 = get_keys_73516240_from(this_keys_76325410); updateSize(); } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testAdjoinRight() { ITier t1 = new SimpleTier(1, 2, 3); t1.add(_000_instance); t1.add(_001_instance); t1.add(_011_instance); ITier t2 = new SimpleTier(2, 3, 4); t2.add(_001_instance); t2.add(_001_instance); t2.add(_111_instance); t1.adjoinRight(t2); assertEquals(2, t1.size()); assertTrue(t1.contains(_000_instance)); assertTrue(t1.contains(_011_instance)); assertTrue(!t1.contains(_001_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void adjoinLeft(ITier tier) { int tier_keys_76325410 = ((SimpleTier) tier).get_keys_76325410(); int this_keys_o3o1o2o0 = (((tier_keys_76325410 >> 1) & 0x7F) | tier_keys_76325410) & 0x55; int this_keys_7o5o6o4o = ((this_keys_o3o1o2o0 << 1)); keys_73516240 = (byte)((this_keys_7o5o6o4o | this_keys_o3o1o2o0) & keys_73516240); updateSize(); } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testAdjoinLeft() { ITier t1 = new SimpleTier(1, 2, 3); t1.add(_001_instance); t1.add(_011_instance); t1.add(_111_instance); ITier t2 = new SimpleTier(2, 3, 4); t2.add(_000_instance); t2.add(_001_instance); t2.add(_011_instance); t2.adjoinLeft(t1); assertEquals(1, t2.size()); assertTrue(t2.contains(_011_instance)); assertTrue(!t2.contains(_000_instance)); assertTrue(!t2.contains(_001_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void inverse() { keys_73516240 = (byte)(~keys_73516240); size = 8 - size; } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testInverse() { ITier t2 = new SimpleTier(1, 2, 3); t2.add(_001_instance); t2.add(_101_instance); t2.inverse(); assertEquals(6, t2.size()); assertTrue(t2.contains(_000_instance)); assertTrue(t2.contains(_010_instance)); assertTrue(t2.contains(_011_instance)); assertTrue(t2.contains(_100_instance)); assertTrue(t2.contains(_110_instance)); assertTrue(t2.contains(_111_instance)); assertTrue(!t2.contains(_001_instance)); assertTrue(!t2.contains(_101_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void concretize(int varName, Value value) { if (Helper.EnableAssertions) { if (value != Value.AllPlain && value != Value.AllNegative) { throw new IllegalArgumentException( "Value should be one of (" + Value.AllPlain + ", " + Value.AllNegative + ") but was " + value); } } if (getAName() == varName) { keys_73516240 = (byte)(value == Value.AllPlain ? keys_73516240 & 0x0F : keys_73516240 & 0xF0); updateSize(); } else if (getBName() == varName) { keys_73516240 = (byte)(value == Value.AllPlain ? keys_73516240 & 0x33 : keys_73516240 & 0xCC); updateSize(); } else if (getCName() == varName) { keys_73516240 = (byte)(value == Value.AllPlain ? keys_73516240 & 0x55 : keys_73516240 & 0xAA); updateSize(); } else { throw new IllegalArgumentException("Can't concretize tier on varName=" + varName + " because varName is not from the tier's permutation"); } } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testConcretize() { SimpleTier tier; tier = SimpleTier.createCompleteTier(1, 2, 3); tier.concretize(1, Value.AllPlain); assertEquals(4, tier.size()); assertTrue(tier.contains(_000_instance)); assertTrue(tier.contains(_001_instance)); assertTrue(tier.contains(_010_instance)); assertTrue(tier.contains(_011_instance)); tier = SimpleTier.createCompleteTier(1, 2, 3); tier.concretize(2, Value.AllPlain); assertEquals(4, tier.size()); assertTrue(tier.contains(_000_instance)); assertTrue(tier.contains(_001_instance)); assertTrue(tier.contains(_100_instance)); assertTrue(tier.contains(_101_instance)); tier = SimpleTier.createCompleteTier(1, 2, 3); tier.concretize(3, Value.AllPlain); assertEquals(4, tier.size()); assertTrue(tier.contains(_000_instance)); assertTrue(tier.contains(_010_instance)); assertTrue(tier.contains(_100_instance)); assertTrue(tier.contains(_110_instance)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public Value valueOfA() { return size == 0 ? Value.Mixed : (byte)(keys_73516240 & 0x0F) == keys_73516240 ? Value.AllPlain : (byte)(keys_73516240 & 0xF0) == keys_73516240 ? Value.AllNegative : Value.Mixed; } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testValueOfA() { SimpleTier tier = new SimpleTier(1, 2, 3); Value value = tier.valueOfA(); assertEquals("Value of empty tier", Value.Mixed, value); tier.add(_000_instance); tier.add(_001_instance); tier.add(_010_instance); tier.add(_011_instance); value = tier.valueOfA(); assertEquals("Value of full a=0 tier", Value.AllPlain, value); tier = new SimpleTier(1, 2, 3); tier.add(_100_instance); tier.add(_101_instance); tier.add(_110_instance); tier.add(_111_instance); value = tier.valueOfA(); assertEquals("Value of full a=1 tier", Value.AllNegative, value); tier.add(_001_instance); value = tier.valueOfA(); assertEquals("Value of a=0 and a=1 tier", Value.Mixed, value); }
SimpleTier extends SimpleTripletPermutation implements ITier { public Value valueOfB() { return size == 0 ? Value.Mixed : (byte)(keys_73516240 & 0x33) == keys_73516240 ? Value.AllPlain : (byte)(keys_73516240 & 0xCC) == keys_73516240 ? Value.AllNegative : Value.Mixed; } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testValueOfB() { SimpleTier tier = new SimpleTier(1, 2, 3); Value value = tier.valueOfB(); assertEquals("Value of empty tier", Value.Mixed, value); tier.add(_000_instance); tier.add(_001_instance); tier.add(_100_instance); tier.add(_101_instance); value = tier.valueOfB(); assertEquals("Value of full b=0 tier", Value.AllPlain, value); tier = new SimpleTier(1, 2, 3); tier.add(_010_instance); tier.add(_011_instance); tier.add(_110_instance); tier.add(_111_instance); value = tier.valueOfB(); assertEquals("Value of full b=1 tier", Value.AllNegative, value); tier.add(_001_instance); value = tier.valueOfB(); assertEquals("Value of b=0 and b=1 tier", Value.Mixed, value); }
SimpleTier extends SimpleTripletPermutation implements ITier { public Value valueOfC() { return size == 0 ? Value.Mixed : (byte)(keys_73516240 & 0x55) == keys_73516240 ? Value.AllPlain : (byte)(keys_73516240 & 0xAA) == keys_73516240 ? Value.AllNegative : Value.Mixed; } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testValueOfC() { SimpleTier tier = new SimpleTier(1, 2, 3); Value value = tier.valueOfC(); assertEquals("Value of empty tier", Value.Mixed, value); tier.add(_000_instance); tier.add(_010_instance); tier.add(_100_instance); tier.add(_110_instance); value = tier.valueOfC(); assertEquals("Value of full c=0 tier", Value.AllPlain, value); tier = new SimpleTier(1, 2, 3); tier.add(_001_instance); tier.add(_011_instance); tier.add(_101_instance); tier.add(_111_instance); value = tier.valueOfC(); assertEquals("Value of full c=1 tier", Value.AllNegative, value); tier.add(_000_instance); value = tier.valueOfC(); assertEquals("Value of c=0 and c=1 tier", Value.Mixed, value); }
Helper { public static void unify(ObjectArrayList cts) throws EmptyStructureException { if (cts.size() < 2) { throw new IllegalArgumentException("Unification is a q-ary operation where q should be > 1"); } VarPairsIndex index = VarPairsIndexFactory.getInstance().buildIndex(cts); unify(index, ((ICompactTripletsStructureHolder) cts.get(0)).getCTS().getPermutation(), cts, 1); } static ObjectArrayList createCTF(ITabularFormula formula); static ITabularFormula createRandomFormula(Random random, int varCount, int clausesCount); static ITriplet createRandomTriplet(Random random, int varCount); static void prettyPrint(ITabularFormula formula); static StringBuilder buildPrettyOutput(ITabularFormula formula); static void saveToDIMACSFileFormat(ITabularFormula formula, String filename); static ITabularFormula loadFromFile(String filename); static ITabularFormula createFormula(int... values); static ITabularFormula createRandomFormula(int seed, int nMax); static void printLine(char c, int length); static void unify(ObjectArrayList cts); static int getCanonicalVarName3(int varName1, int varName2, int[] canonicalName); static void saveCTS(String filenamePrefix, ObjectArrayList cts); static void printFormulas(ObjectArrayList formulas); static void printBits(byte keys); static void completeToCTS(ObjectArrayList ctf, IPermutation variables); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, Properties statistics); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, ICompactTripletsStructure sBasic, Properties statistics); static void writeToImage(IHyperStructure hs, final ObjectArrayList route, final ObjectArrayList markers, String filename); static void convertCTStructuresToRomanovSKTFileFormat(ObjectArrayList cts, String filename); static ObjectArrayList findNonEmptyIntersections(IHyperStructure hs, IVertex vertex); static boolean evaluate(ObjectArrayList ctf, ObjectArrayList route); static ObjectArrayList cloneStructures(ObjectArrayList ct); static int readInt(InputStream input); static String getImplementationVersionFromManifest(String implementationTitle); static ObjectArrayList loadHSS(String hssPath); static void saveHSS(String hssPath, ObjectArrayList hss); static ObjectArrayList findHSSRouteByReduce(ObjectArrayList hss, String hssTempPath); static final String IMPLEMENTATION_VERSION; static final String INITIAL_FORMULA_LOAD_TIME; static final String INITIAL_FORMULA_VAR_COUNT; static final String INITIAL_FORMULA_CLAUSES_COUNT; static final String CTF_CREATION_TIME; static final String CTF_COUNT; static final String CTS_CREATION_TIME; static final String CTS_UNIFICATION_TIME; static final String BASIC_CTS_INITIAL_CLAUSES_COUNT; static final String HSS_CREATION_TIME; static final String NUMBER_OF_HSS_TIERS_BUILT; static final String BASIC_CTS_FINAL_CLAUSES_COUNT; static final String SEARCH_HSS_ROUTE_TIME; static boolean UsePrettyPrint; static boolean EnableAssertions; static boolean UseUniversalVarNames; }
@Test public void testUnify() throws Exception { ICompactTripletsStructure s1 = (ICompactTripletsStructure) Helper.createFormula( new int[] { 1, 2, -3, -1, 2, -3, -1, -2, 3, 2, -3, 4, 2, -3, -4, -2, 3, 4, -2, 3, -4, 3, 4, -5, 3, -4, 5, 3, -4, -5, -3, 4, -5, -3, -4, -5, 4, -5, -6, -4, 5, 6, -4, -5, 6, -4, -5, -6, 5, 6, -7, -5, 6, -7, -5, -6, 7, 6, -7, -8, -6, 7, 8 }); assertEquals(21, s1.getClausesCount()); Helper.prettyPrint(s1); ICompactTripletsStructure s2 = (ICompactTripletsStructure) Helper.createFormula( new int[] { 8, 7, 2, 8, -7, -2, -8, -7, 2, 7, 2, -5, -7, 2, -5, -7, -2, 5, 2, -5, 1, 2, -5, -1, -2, 5, -1, -5, 1, 6, -5, 1, -6, 5, -1, 6, -5, -1, -6, 1, 6, -3, 1, -6, -3, -1, 6, 3, -1, -6, -3, 6, -3, -4, 6, 3, -4, -6, -3, 4, -6, -3, -4 }); assertEquals(21, s2.getClausesCount()); Helper.prettyPrint(s2); ObjectArrayList cts = new ObjectArrayList(new ITabularFormula[] {s1, s2}); Helper.unify(cts); assertEquals(13, s1.getClausesCount()); assertEquals(15, s2.getClausesCount()); Helper.prettyPrint(s1); Helper.prettyPrint(s2); assertTrue(s1.getTier(0).contains(_001_instance)); assertTrue(s1.getTier(0).contains(_101_instance)); assertTrue(s1.getTier(1).contains(_010_instance)); assertTrue(s1.getTier(1).contains(_011_instance)); assertTrue(s1.getTier(2).contains(_101_instance)); assertTrue(s1.getTier(2).contains(_111_instance)); assertTrue(s1.getTier(3).contains(_011_instance)); assertTrue(s1.getTier(3).contains(_110_instance)); assertTrue(s1.getTier(3).contains(_111_instance)); assertTrue(s1.getTier(4).contains(_101_instance)); assertTrue(s1.getTier(4).contains(_110_instance)); assertTrue(s1.getTier(5).contains(_011_instance)); assertTrue(s1.getTier(5).contains(_100_instance)); assertTrue(s2.getTier(0).contains(_000_instance)); assertTrue(s2.getTier(0).contains(_110_instance)); assertTrue(s2.getTier(1).contains(_001_instance)); assertTrue(s2.getTier(1).contains(_101_instance)); assertTrue(s2.getTier(2).contains(_010_instance)); assertTrue(s2.getTier(2).contains(_011_instance)); assertTrue(s2.getTier(3).contains(_100_instance)); assertTrue(s2.getTier(3).contains(_101_instance)); assertTrue(s2.getTier(3).contains(_111_instance)); assertTrue(s2.getTier(4).contains(_001_instance)); assertTrue(s2.getTier(4).contains(_011_instance)); assertTrue(s2.getTier(4).contains(_111_instance)); assertTrue(s2.getTier(5).contains(_011_instance)); assertTrue(s2.getTier(5).contains(_110_instance)); assertTrue(s2.getTier(5).contains(_111_instance)); }
Join3AsIs implements IJoinMethod { public boolean tryJoin(ITabularFormula formula, ITier tier) { ITier existingTier = formula.findTierFor(tier); if (existingTier != null) { formula.unionOrAdd(existingTier); return true; } return false; } boolean tryJoin(ITabularFormula formula, ITier tier); }
@Test public void testJoin2BetweenTiers() throws Throwable { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 3; a2 <= 5; a2++) for (int b2 = 3; b2 <= 5; b2++) for (int c2 = 3; c2 <= 5; c2++) for (int a3 = 5; a3 <= 7; a3++) for (int b3 = 5; b3 <= 7; b3++) for (int c3 = 5; c3 <= 7; c3++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; if (a3 == b3 || a3 == c3 || b3 == c3) continue; Join2BetweenTiers method = new Join2BetweenTiers(); ITabularFormula formula = createFormula(a1, b1, c1, a3, b3, c3); SimpleTier tier = new SimpleTier(a2, b2, c2); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(3, formula.getPermutation().get(2)); assertEquals(4, formula.getPermutation().get(3)); assertEquals(5, formula.getPermutation().get(4)); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (Throwable t) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw t; } } } @Test public void testJoin2BetweenTiers_BitsAreOnTheSamePlaces() throws Throwable { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -5; a2 <= 5; a2 = a2 == -3 ? 3 : a2+1) for (int b2 = -5; b2 <= 5; b2 = b2 == -3 ? 3 : b2+1) for (int c2 = -5; c2 <= 5; c2 = c2 == -3 ? 3 : c2+1) for (int a3 = -7; a3 <= 7; a3 = a3 == -5 ? 5 : a3+1) for (int b3 = -7; b3 <= 7; b3 = b3 == -5 ? 5 : b3+1) for (int c3 = -7; c3 <= 7; c3 = c3 == -5 ? 5 : c3+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; if (Math.abs(a3) == Math.abs(b3) || Math.abs(a3) == Math.abs(c3) || Math.abs(b3) == Math.abs(c3)) continue; Join2BetweenTiers method = new Join2BetweenTiers(); ITabularFormula formula = createFormula(a1, b1, c1, a3, b3, c3); ITier tier0 = formula.getTier(0); ITier tier1 = formula.getTier(1); SimpleTier tier = new SimpleTier(Math.abs(a2), Math.abs(b2), Math.abs(c2)); tier.add(new SimpleTriplet(a2, b2, c2)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a1); assertValueEquals(tier0, b1); assertValueEquals(tier0, c1); assertValueEquals(tier, a2); assertValueEquals(tier, b2); assertValueEquals(tier, c2); assertValueEquals(tier1, a3); assertValueEquals(tier1, b3); assertValueEquals(tier1, c3); } catch (Throwable t) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw t; } } } @Test public void testJoin2BetweenTiers_ThreeTiers() throws Throwable { Join2BetweenTiers method = new Join2BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 2, 3, 4, 6, 7, 8); SimpleTier tier = new SimpleTier(4, 5, 6); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue(formula.getPermutation().sameAs( createPermutation(1, 2, 3, 4, 5, 6, 7, 8))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } @Test public void testJoin2BetweenTiers_ThreeTiers2() throws Throwable { Join2BetweenTiers method = new Join2BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 3, 5, 4, 8, 7, 9); SimpleTier tier = new SimpleTier(5, 6, 7); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue(formula.getPermutation().sameAs( createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } @Test public void testJoin2BetweenTiers_ThreeTiers4() throws EmptyStructureException { Join2BetweenTiers method = new Join2BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 3, 5, 4, 11, 12, 13, 7, 8, 9, 8, 9, 10); SimpleTier tier = new SimpleTier(5, 6, 7); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } @Test public void tryJoin3BetweenTiers_2Left1Right() throws Throwable { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 1; a2 <= 3; a2++) for (int b2 = 1; b2 <= 3; b2++) for (int c2 = 4; c2 <= 6; c2++) for (int a3 = 4; a3 <= 6; a3++) for (int b3 = 4; b3 <= 6; b3++) for (int c3 = 4; c3 <= 6; c3++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; if (a3 == b3 || a3 == c3 || b3 == c3) continue; Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(a1, b1, c1, a3, b3, c3); SimpleTier tier = new SimpleTier(a2, b2, c2); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(1, formula.getPermutation().indexOf(tier.getAName())); assertEquals(2, formula.getPermutation().indexOf(tier.getBName())); assertEquals(3, formula.getPermutation().indexOf(tier.getCName())); formula.complete(createPermutation(1, 2, 3, 4, 5, 6)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (Throwable t) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw t; } } } @Test public void tryJoin3BetweenTiers_2Left1Right_BitsAreOnTheSamePlaces() throws Throwable { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -3; a2 <= 3; a2 = a2 == -1 ? 1 : a2+1) for (int b2 = -3; b2 <= 3; b2 = b2 == -1 ? 1 : b2+1) for (int c2 = -6; c2 <= 6; c2 = c2 == -4 ? 4 : c2+1) for (int a3 = -6; a3 <= 6; a3 = a3 == -4 ? 4 : a3+1) for (int b3 = -6; b3 <= 6; b3 = b3 == -4 ? 4 : b3+1) for (int c3 = -6; c3 <= 6; c3 = c3 == -4 ? 4 : c3+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; if (Math.abs(a3) == Math.abs(b3) || Math.abs(a3) == Math.abs(c3) || Math.abs(b3) == Math.abs(c3)) continue; Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(a1, b1, c1, a3, b3, c3); ITier tier0 = formula.getTier(0); ITier tier1 = formula.getTier(1); SimpleTier tier = new SimpleTier(Math.abs(a2), Math.abs(b2), Math.abs(c2)); tier.add(new SimpleTriplet(a2, b2, c2)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a1); assertValueEquals(tier0, b1); assertValueEquals(tier0, c1); assertValueEquals(tier, a2); assertValueEquals(tier, b2); assertValueEquals(tier, c2); assertValueEquals(tier1, a3); assertValueEquals(tier1, b3); assertValueEquals(tier1, c3); } catch (Throwable t) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw t; } } } @Test public void testJoin3BetweenTiers_2Left1Right_ThreeTiers() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 4, 5, 6, 7, 8, 9); SimpleTier tier = new SimpleTier(2, 3, 7); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(1, 2, 3, 7, 8, 9, 4, 5, 6))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void testJoin3BetweenTiers_2Left1Right_ThreeTiers2() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 2, 3, 4, 4, 6, 5, 7, 8, 9); SimpleTier tier = new SimpleTier(5, 6, 7); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(1, 2, 3, 4, 6, 5, 7, 8, 9))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void testJoin3BetweenTiers_2Left1Right_ThreeTiers3() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 4, 5, 6, 5, 6, 7, 8, 9, 10); SimpleTier tier = new SimpleTier(2, 3, 8); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(1, 2, 3, 8, 9, 10, 4, 5, 6, 7))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void tryJoin3BetweenTiers_1Left2Right() throws EmptyStructureException { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 1; a2 <= 3; a2++) for (int b2 = 4; b2 <= 6; b2++) for (int c2 = 4; c2 <= 6; c2++) for (int a3 = 4; a3 <= 6; a3++) for (int b3 = 4; b3 <= 6; b3++) for (int c3 = 4; c3 <= 6; c3++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; if (a3 == b3 || a3 == c3 || b3 == c3) continue; Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(a1, b1, c1, a3, b3, c3); SimpleTier tier = new SimpleTier(a2, b2, c2); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(2, formula.getPermutation().indexOf(tier.getAName())); assertEquals(3, formula.getPermutation().indexOf(tier.getBName())); assertEquals(4, formula.getPermutation().indexOf(tier.getCName())); formula.complete(createPermutation(1, 2, 3, 4, 5, 6)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin3BetweenTiers_1Left2Right_BitsAreOnTheSamePlaces() throws EmptyStructureException { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -3; a2 <= 3; a2 = a2 == -1 ? 1 : a2+1) for (int b2 = -6; b2 <= 6; b2 = b2 == -4 ? 4 : b2+1) for (int c2 = -6; c2 <= 6; c2 = c2 == -4 ? 4 : c2+1) for (int a3 = -6; a3 <= 6; a3 = a3 == -4 ? 4 : a3+1) for (int b3 = -6; b3 <= 6; b3 = b3 == -4 ? 4 : b3+1) for (int c3 = -6; c3 <= 6; c3 = c3 == -4 ? 4 : c3+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; if (Math.abs(a3) == Math.abs(b3) || Math.abs(a3) == Math.abs(c3) || Math.abs(b3) == Math.abs(c3)) continue; Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(a1, b1, c1, a3, b3, c3); ITier tier0 = formula.getTier(0); ITier tier1 = formula.getTier(1); SimpleTier tier = new SimpleTier(Math.abs(a2), Math.abs(b2), Math.abs(c2)); tier.add(new SimpleTriplet(a2, b2, c2)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a1); assertValueEquals(tier0, b1); assertValueEquals(tier0, c1); assertValueEquals(tier, a2); assertValueEquals(tier, b2); assertValueEquals(tier, c2); assertValueEquals(tier1, a3); assertValueEquals(tier1, b3); assertValueEquals(tier1, c3); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void testJoin3BetweenTiers_1Left2Right_ThreeTiers() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 4, 5, 6, 7, 8, 9); SimpleTier tier = new SimpleTier(3, 7, 8); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(4, 5, 6, 1, 2, 3, 7, 8, 9))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void testJoin3BetweenTiers_1Left2Right_ThreeTiers2() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 2, 3, 4, 4, 6, 5, 7, 8, 9); SimpleTier tier = new SimpleTier(6, 7, 8); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void testJoin3BetweenTiers_1Left2Right_ThreeTiers3() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 2, 3, 4, 5, 6, 5, 6, 7, 8, 9, 10); SimpleTier tier = new SimpleTier(3, 8, 9); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(4, 5, 6, 7, 1, 2, 3, 8, 9, 10))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void testJoin3BetweenTiers_1Left2Right_ThreeTiers4() throws EmptyStructureException { Join3BetweenTiers method = new Join3BetweenTiers(); ITabularFormula formula = createFormula(1, 3, 8, 5, 6, 7); SimpleTier tier = new SimpleTier(6, 8, 7); tier.add(_101_instance); assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Permutation should match", formula.getPermutation().sameAs( createPermutation(1, 3, 8, 6, 7, 5))); formula.complete(createPermutation(1, 2, 3, 4, 5, 6, 7, 8)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } @Test public void tryJoin1Left() throws EmptyStructureException { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 3; a2 <= 5; a2++) for (int b2 = 3; b2 <= 5; b2++) for (int c2 = 3; c2 <= 5; c2++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; Join1Left method = new Join1Left(); ITabularFormula formula = createFormula(a2, b2, c2); SimpleTier tier = new SimpleTier(a1, b1, c1); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(0, formula.getPermutation().indexOf(tier.getAName())); assertEquals(1, formula.getPermutation().indexOf(tier.getBName())); assertEquals(2, formula.getPermutation().indexOf(tier.getCName())); formula.complete(createPermutation(1, 2, 3, 4, 5)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin1Left_BitsAreOnTheSamePlaces() throws EmptyStructureException { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -5; a2 <= 5; a2 = a2 == -3 ? 3 : a2+1) for (int b2 = -5; b2 <= 5; b2 = b2 == -3 ? 3 : b2+1) for (int c2 = -5; c2 <= 5; c2 = c2 == -3 ? 3 : c2+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; Join1Left method = new Join1Left(); ITabularFormula formula = createFormula(a2, b2, c2); ITier tier0 = formula.getTier(0); SimpleTier tier = new SimpleTier(Math.abs(a1), Math.abs(b1), Math.abs(c1)); tier.add(new SimpleTriplet(a1, b1, c1)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a2); assertValueEquals(tier0, b2); assertValueEquals(tier0, c2); assertValueEquals(tier, a1); assertValueEquals(tier, b1); assertValueEquals(tier, c1); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin1Right() throws EmptyStructureException { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 3; a2 <= 5; a2++) for (int b2 = 3; b2 <= 5; b2++) for (int c2 = 3; c2 <= 5; c2++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; Join1Right method = new Join1Right(); ITabularFormula formula = createFormula(a2, b2, c2); SimpleTier tier = new SimpleTier(a1, b1, c1); tier.add(_101_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(2, formula.getPermutation().indexOf(tier.getAName())); assertEquals(3, formula.getPermutation().indexOf(tier.getBName())); assertEquals(4, formula.getPermutation().indexOf(tier.getCName())); formula.complete(createPermutation(1, 2, 3, 4, 5)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin1Right_BitsAreOnTheSamePlaces() throws EmptyStructureException { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -5; a2 <= 5; a2 = a2 == -3 ? 3 : a2+1) for (int b2 = -5; b2 <= 5; b2 = b2 == -3 ? 3 : b2+1) for (int c2 = -5; c2 <= 5; c2 = c2 == -3 ? 3 : c2+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; Join1Right method = new Join1Right(); ITabularFormula formula = createFormula(a2, b2, c2); ITier tier0 = formula.getTier(0); SimpleTier tier = new SimpleTier(Math.abs(a1), Math.abs(b1), Math.abs(c1)); tier.add(new SimpleTriplet(a1, b1, c1)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a2); assertValueEquals(tier0, b2); assertValueEquals(tier0, c2); assertValueEquals(tier, a1); assertValueEquals(tier, b1); assertValueEquals(tier, c1); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin2Left() throws EmptyStructureException { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 2; a2 <= 4; a2++) for (int b2 = 2; b2 <= 4; b2++) for (int c2 = 2; c2 <= 4; c2++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; Join2Left method = new Join2Left(); ITabularFormula formula = createFormula(a2, b2, c2); SimpleTier tier = new SimpleTier(a1, b1, c1); tier.add(_000_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(0, formula.getPermutation().indexOf(tier.getAName())); assertEquals(1, formula.getPermutation().indexOf(tier.getBName())); assertEquals(2, formula.getPermutation().indexOf(tier.getCName())); formula.complete(createPermutation(1, 2, 3, 4)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin2Left_BitsOnTheirPlaces() throws EmptyStructureException { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -4; a2 <= 4; a2 = a2 == -2 ? 2 : a2+1) for (int b2 = -4; b2 <= 4; b2 = b2 == -2 ? 2 : b2+1) for (int c2 = -4; c2 <= 4; c2 = c2 == -2 ? 2 : c2+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; Join2Left method = new Join2Left(); ITabularFormula formula = createFormula(a2, b2, c2); ITier tier0 = formula.getTier(0); SimpleTier tier = new SimpleTier(Math.abs(a1), Math.abs(b1), Math.abs(c1)); tier.add(new SimpleTriplet(a1, b1, c1)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a2); assertValueEquals(tier0, b2); assertValueEquals(tier0, c2); assertValueEquals(tier, a1); assertValueEquals(tier, b1); assertValueEquals(tier, c1); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin2Right() throws EmptyStructureException { for (int a1 = 1; a1 <= 3; a1++) for (int b1 = 1; b1 <= 3; b1++) for (int c1 = 1; c1 <= 3; c1++) for (int a2 = 2; a2 <= 4; a2++) for (int b2 = 2; b2 <= 4; b2++) for (int c2 = 2; c2 <= 4; c2++) { if (a1 == b1 || a1 == c1 || b1 == c1) continue; if (a2 == b2 || a2 == c2 || b2 == c2) continue; Join2Right method = new Join2Right(); ITabularFormula formula = createFormula(a2, b2, c2); SimpleTier tier = new SimpleTier(a1, b1, c1); tier.add(_000_instance); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertEquals(1, formula.getPermutation().indexOf(tier.getAName())); assertEquals(2, formula.getPermutation().indexOf(tier.getBName())); assertEquals(3, formula.getPermutation().indexOf(tier.getCName())); formula.complete(createPermutation(1, 2, 3, 4)); assertTrue(((ICompactTripletsStructure)formula).tiersSorted()); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } } @Test public void tryJoin2Right_BitsOnTheirPlaces() throws EmptyStructureException { for (int a1 = -3; a1 <= 3; a1 = a1 == -1 ? 1 : a1+1) for (int b1 = -3; b1 <= 3; b1 = b1 == -1 ? 1 : b1+1) for (int c1 = -3; c1 <= 3; c1 = c1 == -1 ? 1 : c1+1) for (int a2 = -4; a2 <= 4; a2 = a2 == -2 ? 2 : a2+1) for (int b2 = -4; b2 <= 4; b2 = b2 == -2 ? 2 : b2+1) for (int c2 = -4; c2 <= 4; c2 = c2 == -2 ? 2 : c2+1) { if (Math.abs(a1) == Math.abs(b1) || Math.abs(a1) == Math.abs(c1) || Math.abs(b1) == Math.abs(c1)) continue; if (Math.abs(a2) == Math.abs(b2) || Math.abs(a2) == Math.abs(c2) || Math.abs(b2) == Math.abs(c2)) continue; Join2Right method = new Join2Right(); ITabularFormula formula = createFormula(a2, b2, c2); ITier tier0 = formula.getTier(0); SimpleTier tier = new SimpleTier(Math.abs(a1), Math.abs(b1), Math.abs(c1)); tier.add(new SimpleTriplet(a1, b1, c1)); try { assertTrue("Should join", method.tryJoin(formula, tier)); assertTrue("Debugger", true); assertValueEquals(tier0, a2); assertValueEquals(tier0, b2); assertValueEquals(tier0, c2); assertValueEquals(tier, a1); assertValueEquals(tier, b1); assertValueEquals(tier, c1); } catch (AssertionError e) { System.out.println("Formula: " + formula); System.out.println("Tier: " + tier); throw e; } } }
Helper { public static int getCanonicalVarName3(int varName1, int varName2, int[] canonicalName) { int varName3; if (varName1 == canonicalName[1]) { if (varName2 == canonicalName[2]) { varName3 = canonicalName[0]; } else { varName3 = canonicalName[2]; } } else { if (varName2 == canonicalName[1]) { if (varName1 > varName2) { varName3 = canonicalName[0]; } else { varName3 = canonicalName[2]; } } else { varName3 = canonicalName[1]; } } return varName3; } static ObjectArrayList createCTF(ITabularFormula formula); static ITabularFormula createRandomFormula(Random random, int varCount, int clausesCount); static ITriplet createRandomTriplet(Random random, int varCount); static void prettyPrint(ITabularFormula formula); static StringBuilder buildPrettyOutput(ITabularFormula formula); static void saveToDIMACSFileFormat(ITabularFormula formula, String filename); static ITabularFormula loadFromFile(String filename); static ITabularFormula createFormula(int... values); static ITabularFormula createRandomFormula(int seed, int nMax); static void printLine(char c, int length); static void unify(ObjectArrayList cts); static int getCanonicalVarName3(int varName1, int varName2, int[] canonicalName); static void saveCTS(String filenamePrefix, ObjectArrayList cts); static void printFormulas(ObjectArrayList formulas); static void printBits(byte keys); static void completeToCTS(ObjectArrayList ctf, IPermutation variables); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, Properties statistics); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, ICompactTripletsStructure sBasic, Properties statistics); static void writeToImage(IHyperStructure hs, final ObjectArrayList route, final ObjectArrayList markers, String filename); static void convertCTStructuresToRomanovSKTFileFormat(ObjectArrayList cts, String filename); static ObjectArrayList findNonEmptyIntersections(IHyperStructure hs, IVertex vertex); static boolean evaluate(ObjectArrayList ctf, ObjectArrayList route); static ObjectArrayList cloneStructures(ObjectArrayList ct); static int readInt(InputStream input); static String getImplementationVersionFromManifest(String implementationTitle); static ObjectArrayList loadHSS(String hssPath); static void saveHSS(String hssPath, ObjectArrayList hss); static ObjectArrayList findHSSRouteByReduce(ObjectArrayList hss, String hssTempPath); static final String IMPLEMENTATION_VERSION; static final String INITIAL_FORMULA_LOAD_TIME; static final String INITIAL_FORMULA_VAR_COUNT; static final String INITIAL_FORMULA_CLAUSES_COUNT; static final String CTF_CREATION_TIME; static final String CTF_COUNT; static final String CTS_CREATION_TIME; static final String CTS_UNIFICATION_TIME; static final String BASIC_CTS_INITIAL_CLAUSES_COUNT; static final String HSS_CREATION_TIME; static final String NUMBER_OF_HSS_TIERS_BUILT; static final String BASIC_CTS_FINAL_CLAUSES_COUNT; static final String SEARCH_HSS_ROUTE_TIME; static boolean UsePrettyPrint; static boolean EnableAssertions; static boolean UseUniversalVarNames; }
@Test public void testGetCanonicalVarName3() { assertEquals(3, Helper.getCanonicalVarName3(1, 2, new int[] {1, 2, 3})); assertEquals(3, Helper.getCanonicalVarName3(2, 1, new int[] {1, 2, 3})); assertEquals(1, Helper.getCanonicalVarName3(2, 3, new int[] {1, 2, 3})); assertEquals(1, Helper.getCanonicalVarName3(3, 2, new int[] {1, 2, 3})); assertEquals(2, Helper.getCanonicalVarName3(1, 3, new int[] {1, 2, 3})); assertEquals(2, Helper.getCanonicalVarName3(3, 1, new int[] {1, 2, 3})); }
Helper { public static ObjectArrayList createCTF(ITabularFormula formula) { ObjectArrayList ctf = new ObjectArrayList(); ObjectArrayList tiers = formula.getTiers(); ITabularFormula f = new SimpleFormula(); f.unionOrAdd(formula.getTier(0).clone()); ctf.add(f); for (int i = 1; i < tiers.size(); i++) { ITier tier = ((ITier) tiers.get(i)).clone(); if (!joinTier(ctf, tier)) { f = new SimpleFormula(); f.unionOrAdd(tier); ctf.add(f); } } return ctf; } static ObjectArrayList createCTF(ITabularFormula formula); static ITabularFormula createRandomFormula(Random random, int varCount, int clausesCount); static ITriplet createRandomTriplet(Random random, int varCount); static void prettyPrint(ITabularFormula formula); static StringBuilder buildPrettyOutput(ITabularFormula formula); static void saveToDIMACSFileFormat(ITabularFormula formula, String filename); static ITabularFormula loadFromFile(String filename); static ITabularFormula createFormula(int... values); static ITabularFormula createRandomFormula(int seed, int nMax); static void printLine(char c, int length); static void unify(ObjectArrayList cts); static int getCanonicalVarName3(int varName1, int varName2, int[] canonicalName); static void saveCTS(String filenamePrefix, ObjectArrayList cts); static void printFormulas(ObjectArrayList formulas); static void printBits(byte keys); static void completeToCTS(ObjectArrayList ctf, IPermutation variables); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, Properties statistics); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, ICompactTripletsStructure sBasic, Properties statistics); static void writeToImage(IHyperStructure hs, final ObjectArrayList route, final ObjectArrayList markers, String filename); static void convertCTStructuresToRomanovSKTFileFormat(ObjectArrayList cts, String filename); static ObjectArrayList findNonEmptyIntersections(IHyperStructure hs, IVertex vertex); static boolean evaluate(ObjectArrayList ctf, ObjectArrayList route); static ObjectArrayList cloneStructures(ObjectArrayList ct); static int readInt(InputStream input); static String getImplementationVersionFromManifest(String implementationTitle); static ObjectArrayList loadHSS(String hssPath); static void saveHSS(String hssPath, ObjectArrayList hss); static ObjectArrayList findHSSRouteByReduce(ObjectArrayList hss, String hssTempPath); static final String IMPLEMENTATION_VERSION; static final String INITIAL_FORMULA_LOAD_TIME; static final String INITIAL_FORMULA_VAR_COUNT; static final String INITIAL_FORMULA_CLAUSES_COUNT; static final String CTF_CREATION_TIME; static final String CTF_COUNT; static final String CTS_CREATION_TIME; static final String CTS_UNIFICATION_TIME; static final String BASIC_CTS_INITIAL_CLAUSES_COUNT; static final String HSS_CREATION_TIME; static final String NUMBER_OF_HSS_TIERS_BUILT; static final String BASIC_CTS_FINAL_CLAUSES_COUNT; static final String SEARCH_HSS_ROUTE_TIME; static boolean UsePrettyPrint; static boolean EnableAssertions; static boolean UseUniversalVarNames; }
@Test public void testCreateCTF() { for (int n = 7; n < 100; n++) { try { System.out.println(n); ITabularFormula formula = Helper.createRandomFormula(21, n); ObjectArrayList ctf = Helper.createCTF(formula); Helper.completeToCTS(ctf, formula.getPermutation()); } catch (EmptyStructureException e) { } } }
Helper { public static void convertCTStructuresToRomanovSKTFileFormat(ObjectArrayList cts, String filename) throws FileNotFoundException, IOException { OutputStream os = null; try { os = new FileOutputStream(new File(filename)); for (int i = 0; i < cts.size(); i++) { ITabularFormula f = (ITabularFormula) cts.get(i); for (int j = 0; j < f.getTiers().size(); j++) { ITier tier = f.getTier(j); for (ITripletValue tripletValue : tier) { int a = (tripletValue.isNotA() ? -1 : 1) * tier.getAName(); int b = (tripletValue.isNotB() ? -1 : 1) * tier.getBName(); int c = (tripletValue.isNotC() ? -1 : 1) * tier.getCName(); writeJavaIntAsDelphiLongInt(os, a); writeJavaIntAsDelphiLongInt(os, b); writeJavaIntAsDelphiLongInt(os, c); } } writeJavaIntAsDelphiLongInt(os, 0); writeJavaIntAsDelphiLongInt(os, 0); writeJavaIntAsDelphiLongInt(os, 0); } } finally { if (os != null) { os.close(); } } } static ObjectArrayList createCTF(ITabularFormula formula); static ITabularFormula createRandomFormula(Random random, int varCount, int clausesCount); static ITriplet createRandomTriplet(Random random, int varCount); static void prettyPrint(ITabularFormula formula); static StringBuilder buildPrettyOutput(ITabularFormula formula); static void saveToDIMACSFileFormat(ITabularFormula formula, String filename); static ITabularFormula loadFromFile(String filename); static ITabularFormula createFormula(int... values); static ITabularFormula createRandomFormula(int seed, int nMax); static void printLine(char c, int length); static void unify(ObjectArrayList cts); static int getCanonicalVarName3(int varName1, int varName2, int[] canonicalName); static void saveCTS(String filenamePrefix, ObjectArrayList cts); static void printFormulas(ObjectArrayList formulas); static void printBits(byte keys); static void completeToCTS(ObjectArrayList ctf, IPermutation variables); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, Properties statistics); static ObjectArrayList createHyperStructuresSystem(ObjectArrayList cts, ICompactTripletsStructure sBasic, Properties statistics); static void writeToImage(IHyperStructure hs, final ObjectArrayList route, final ObjectArrayList markers, String filename); static void convertCTStructuresToRomanovSKTFileFormat(ObjectArrayList cts, String filename); static ObjectArrayList findNonEmptyIntersections(IHyperStructure hs, IVertex vertex); static boolean evaluate(ObjectArrayList ctf, ObjectArrayList route); static ObjectArrayList cloneStructures(ObjectArrayList ct); static int readInt(InputStream input); static String getImplementationVersionFromManifest(String implementationTitle); static ObjectArrayList loadHSS(String hssPath); static void saveHSS(String hssPath, ObjectArrayList hss); static ObjectArrayList findHSSRouteByReduce(ObjectArrayList hss, String hssTempPath); static final String IMPLEMENTATION_VERSION; static final String INITIAL_FORMULA_LOAD_TIME; static final String INITIAL_FORMULA_VAR_COUNT; static final String INITIAL_FORMULA_CLAUSES_COUNT; static final String CTF_CREATION_TIME; static final String CTF_COUNT; static final String CTS_CREATION_TIME; static final String CTS_UNIFICATION_TIME; static final String BASIC_CTS_INITIAL_CLAUSES_COUNT; static final String HSS_CREATION_TIME; static final String NUMBER_OF_HSS_TIERS_BUILT; static final String BASIC_CTS_FINAL_CLAUSES_COUNT; static final String SEARCH_HSS_ROUTE_TIME; static boolean UsePrettyPrint; static boolean EnableAssertions; static boolean UseUniversalVarNames; }
@Test public void testConvertCTStructuresToRomanovSKTFileFormat() throws Exception { String filename = "target/test-classes/cnf-v22-c73-12.cnf"; File file = new File(filename); ITabularFormula formula = Helper.loadFromFile(filename); ObjectArrayList ctf = Helper.createCTF(formula); System.out.println("CTF: " + ctf.size()); Helper.completeToCTS(ctf, formula.getPermutation()); System.out.println("CTS: " + ctf.size()); Helper.convertCTStructuresToRomanovSKTFileFormat(ctf, "target/" + file.getName() + ".skt"); Helper.saveToDIMACSFileFormat((ITabularFormula) ctf.get(0), "target/" + file.getName() + "-cts-0.cnf"); }
SimplePermutation implements IPermutation { public int indexOf(int varName) { return permutationHash.containsKey(varName) ? permutationHash.get(varName) : -1; } SimplePermutation(); boolean contains(int varName); int indexOf(int varName); void put(int[] varNames); void add(int varName); void add(int index, int varName); void shiftToStart(int from, int to); void shiftToEnd(int from, int to); void swap(int varName1, int varName2); int size(); int[] elements(); int get(int index); String toString(); boolean sameAs(IPermutation permutation); static IPermutation createPermutation(int... variables); int elementsHash(); }
@Test public void testIndexOf() { IPermutation sp = new SimplePermutation(); sp.add(4); sp.add(6); sp.add(7); Assert.assertEquals(0, sp.indexOf(4)); Assert.assertEquals(1, sp.indexOf(6)); Assert.assertEquals(2, sp.indexOf(7)); sp.add(1, 9); Assert.assertEquals(0, sp.indexOf(4)); Assert.assertEquals(1, sp.indexOf(9)); Assert.assertEquals(2, sp.indexOf(6)); Assert.assertEquals(3, sp.indexOf(7)); sp.add(3); Assert.assertEquals(0, sp.indexOf(4)); Assert.assertEquals(1, sp.indexOf(9)); Assert.assertEquals(2, sp.indexOf(6)); Assert.assertEquals(3, sp.indexOf(7)); Assert.assertEquals(4, sp.indexOf(3)); sp.add(0, 5); Assert.assertEquals(0, sp.indexOf(5)); Assert.assertEquals(1, sp.indexOf(4)); Assert.assertEquals(2, sp.indexOf(9)); Assert.assertEquals(3, sp.indexOf(6)); Assert.assertEquals(4, sp.indexOf(7)); Assert.assertEquals(5, sp.indexOf(3)); }
SimplePermutation implements IPermutation { public void shiftToStart(int from, int to) { if (to <= from) { throw new IllegalArgumentException("to <= from"); } int[] buffer = new int[from]; int[] elements = permutation.elements(); System.arraycopy(elements, 0, buffer, 0, from); System.arraycopy(elements, from, elements, 0, to - from + 1); System.arraycopy(buffer, 0, elements, to - from + 1, from); for (int i = 0; i <= to; i++) { int varName = elements[i]; permutationHash.put(varName, i); positionHash.put(i, varName); } elementsHashDirty = true; } SimplePermutation(); boolean contains(int varName); int indexOf(int varName); void put(int[] varNames); void add(int varName); void add(int index, int varName); void shiftToStart(int from, int to); void shiftToEnd(int from, int to); void swap(int varName1, int varName2); int size(); int[] elements(); int get(int index); String toString(); boolean sameAs(IPermutation permutation); static IPermutation createPermutation(int... variables); int elementsHash(); }
@Test public void testShiftToStart() { IPermutation permutation = createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9); permutation.shiftToStart(4, 6); Assert.assertTrue(permutation.sameAs(createPermutation(5, 6, 7, 1, 2, 3, 4, 8, 9))); assertEquals(0, permutation.indexOf(5)); assertEquals(1, permutation.indexOf(6)); assertEquals(2, permutation.indexOf(7)); assertEquals(3, permutation.indexOf(1)); assertEquals(4, permutation.indexOf(2)); assertEquals(5, permutation.indexOf(3)); assertEquals(6, permutation.indexOf(4)); assertEquals(7, permutation.indexOf(8)); assertEquals(8, permutation.indexOf(9)); }
SimplePermutation implements IPermutation { public void shiftToEnd(int from, int to) { if (to <= from) { throw new IllegalArgumentException("to <= from"); } int[] buffer = new int[permutation.size() - to - 1]; int[] elements = permutation.elements(); System.arraycopy(elements, to + 1, buffer, 0, permutation.size() - to - 1); System.arraycopy(elements, from, elements, permutation.size() - (to - from) - 1, to - from + 1); System.arraycopy(buffer, 0, elements, from, permutation.size() - to - 1); for (int i = from; i < permutation.size(); i++) { int varName = elements[i]; permutationHash.put(varName, i); positionHash.put(i, varName); } elementsHashDirty = true; } SimplePermutation(); boolean contains(int varName); int indexOf(int varName); void put(int[] varNames); void add(int varName); void add(int index, int varName); void shiftToStart(int from, int to); void shiftToEnd(int from, int to); void swap(int varName1, int varName2); int size(); int[] elements(); int get(int index); String toString(); boolean sameAs(IPermutation permutation); static IPermutation createPermutation(int... variables); int elementsHash(); }
@Test public void testShiftToEnd() { IPermutation permutation = createPermutation(1, 2, 3, 4, 5, 6, 7, 8, 9); permutation.shiftToEnd(4, 6); Assert.assertTrue(permutation.sameAs(createPermutation(1, 2, 3, 4, 8, 9, 5, 6, 7))); assertEquals(0, permutation.indexOf(1)); assertEquals(1, permutation.indexOf(2)); assertEquals(2, permutation.indexOf(3)); assertEquals(3, permutation.indexOf(4)); assertEquals(4, permutation.indexOf(8)); assertEquals(5, permutation.indexOf(9)); assertEquals(6, permutation.indexOf(5)); assertEquals(7, permutation.indexOf(6)); assertEquals(8, permutation.indexOf(7)); }
SimpleFormula implements ICompactTripletsStructure, ICompactTripletsStructureHolder { public boolean evaluate(Properties properties) { boolean result = true; for (int j = 0; j < getTiers().size(); j++) { for (ITripletValue tiplet : getTier(j)) { ITripletPermutation permutation = getTier(j); boolean aValue = parseBoolean(String.valueOf(properties.get("_" + permutation.getAName()))); boolean bValue = parseBoolean(String.valueOf(properties.get("_" + permutation.getBName()))); boolean cValue = parseBoolean(String.valueOf(properties.get("_" + permutation.getCName()))); if (tiplet.isNotA()) aValue = !aValue; if (tiplet.isNotB()) bValue = !bValue; if (tiplet.isNotC()) cValue = !cValue; result = result && (aValue || bValue || cValue); if (!result) { return result; } } } return result; } SimpleFormula(); SimpleFormula(IPermutation permutation); private SimpleFormula(SimpleFormula formula, final boolean fillTiersHash3); SimpleFormula clone(); void clear(); int getClausesCount(); int getVarCount(); ObjectArrayList getTiers(); boolean tiersSorted(); void sortTiers(); void complete(IPermutation variables); void add(ITriplet triplet); ObjectArrayList findTiersFor(int varName); ObjectArrayList findTiersFor(int varName1, int varName2); void unionOrAdd(ITier tier); ITier findTierFor(ITripletPermutation tripletPermutation); IPermutation getPermutation(); CleanupStatus cleanup(int from, int to); boolean cleanup(); void union(ICompactTripletsStructure cts); void intersect(ICompactTripletsStructure cts); CleanupStatus concretize(int varName, Value value); boolean concretize(ITripletPermutation tripletPermutation, ITripletValue tripletValue); boolean isEmpty(); String toString(); Value valueOf(int varName); ICompactTripletsStructure getCTS(); ITier getTier(int tierIndex); boolean evaluate(Properties properties); boolean evaluate(ObjectArrayList route); boolean equals(Object obj); boolean containsAllValuesOf(ITier anotherTier); boolean isElementary(); void clearTierHash3(); void setVarMappings(OpenIntIntHashMap internalToOriginalMap); int getOriginalVarName(int varName); }
@Test public void testEvaluate() { ITabularFormula formula = Helper.createFormula(1, 2, 3); ObjectArrayList route = new ObjectArrayList(); route.add(new SimpleVertex(new SimpleTripletPermutation(1, 2, 3), 0, _111_instance, null)); assertTrue(formula.evaluate(route)); }
SimpleTier extends SimpleTripletPermutation implements ITier { public void add(ITripletValue triplet) { if (!contains(triplet)) { keys_73516240 = (byte)(keys_73516240 | triplet.getTierKey()); size++; } } SimpleTier(int a, int b, int c); private SimpleTier(SimpleTier tier); static SimpleTier createCompleteTier(int a, int b, int c); ITier clone(); void add(ITripletValue triplet); void intersect(ITripletValue tripletValue); int size(); boolean contains(ITripletValue triplet); void remove(ITripletValue triplet); Iterator<ITripletValue> iterator(); void swapAB(); void swapAC(); void swapBC(); String toString(); void adjoinRight(ITier tier); void adjoinLeft(ITier tier); boolean isEmpty(); void intersect(ITier tier); void union(ITier tier); void concretize(int varName, Value value); Value valueOfA(); Value valueOfB(); Value valueOfC(); void inverse(); boolean equals(Object obj); }
@Test public void testTripletsIterator() { ITier tier = new SimpleTier(1, 2, 3); tier.add(_000_instance); tier.add(_010_instance); for (ITripletValue tripletValue : tier) { System.out.println(tripletValue); } }
DefaultPreconditions implements Preconditions { @Override public boolean isConnecting(TGDevice device) { return device != null && device.getState() == TGDevice.STATE_CONNECTING; } @Override boolean isConnecting(TGDevice device); @Override boolean isConnected(TGDevice device); @Override boolean canConnect(TGDevice device); @Override boolean isBluetoothAdapterInitialized(); @Override boolean isBluetoothAdapterInitialized(BluetoothAdapter bluetoothAdapter); @Override boolean isBluetoothEnabled(); @Override boolean isBluetoothEnabled(BluetoothAdapter bluetoothAdapter); }
@Test public void shouldBeConnecting() { when(tgDevice.getState()).thenReturn(TGDevice.STATE_CONNECTING); boolean isConnecting = preconditions.isConnecting(tgDevice); assertThat(isConnecting).isTrue(); } @Test public void shouldNotBeConnecting() { when(tgDevice.getState()).thenReturn(TGDevice.STATE_DISCONNECTED); boolean isConnecting = preconditions.isConnecting(tgDevice); assertThat(isConnecting).isFalse(); } @Test public void shouldNotBeConnectingWhenDeviceIsNull() { boolean isConnecting = preconditions.isConnecting(null); assertThat(isConnecting).isFalse(); }
DefaultPreconditions implements Preconditions { @Override public boolean isBluetoothAdapterInitialized() { return isBluetoothAdapterInitialized(BluetoothAdapter.getDefaultAdapter()); } @Override boolean isConnecting(TGDevice device); @Override boolean isConnected(TGDevice device); @Override boolean canConnect(TGDevice device); @Override boolean isBluetoothAdapterInitialized(); @Override boolean isBluetoothAdapterInitialized(BluetoothAdapter bluetoothAdapter); @Override boolean isBluetoothEnabled(); @Override boolean isBluetoothEnabled(BluetoothAdapter bluetoothAdapter); }
@Test public void bluetoothAdapterShouldBeInitialized() { boolean isInitialized = preconditions.isBluetoothAdapterInitialized(); assertThat(isInitialized).isTrue(); } @Test public void bluetoothAdapterShouldNotBeInitializedWhenItsNull() { boolean isInitialized = preconditions.isBluetoothAdapterInitialized(null); assertThat(isInitialized).isFalse(); } @Test public void bluetoothAdapterShouldBeInitializedWhenItsNotNull() { boolean isInitialized = preconditions.isBluetoothAdapterInitialized(bluetoothAdapter); assertThat(isInitialized).isTrue(); }
DefaultPreconditions implements Preconditions { @Override public boolean isBluetoothEnabled() { return isBluetoothEnabled(BluetoothAdapter.getDefaultAdapter()); } @Override boolean isConnecting(TGDevice device); @Override boolean isConnected(TGDevice device); @Override boolean canConnect(TGDevice device); @Override boolean isBluetoothAdapterInitialized(); @Override boolean isBluetoothAdapterInitialized(BluetoothAdapter bluetoothAdapter); @Override boolean isBluetoothEnabled(); @Override boolean isBluetoothEnabled(BluetoothAdapter bluetoothAdapter); }
@Test public void bluetoothShouldBeEnabled() { when(bluetoothAdapter.isEnabled()).thenReturn(true); boolean isEnabled = preconditions.isBluetoothEnabled(bluetoothAdapter); assertThat(isEnabled).isTrue(); } @Test public void bluetoothShouldNotBeEnabled() { when(bluetoothAdapter.isEnabled()).thenReturn(false); boolean isEnabled = preconditions.isBluetoothEnabled(bluetoothAdapter); assertThat(isEnabled).isFalse(); } @Test public void bluetoothShouldNotBeEnabledWhenAdapterIsNull() { boolean isEnabled = preconditions.isBluetoothEnabled(null); assertThat(isEnabled).isFalse(); }
NeuroSky { public void connect() throws BluetoothNotEnabledException { if (!preconditions.isBluetoothEnabled()) { throw new BluetoothNotEnabledException(); } if (canConnect()) { openConnection(); } } NeuroSky(final DeviceMessageListener listener); protected NeuroSky(final DeviceMessageListener listener, @NonNull Preconditions preconditions); void connect(); void disconnect(); void enableRawSignal(); void disableRawSignal(); boolean isRawSignalEnabled(); void start(); void stop(); boolean canConnect(); boolean isConnected(); boolean isConnecting(); TGDevice getDevice(); DeviceMessageHandler getHandler(); }
@Test(expected = BluetoothNotEnabledException.class) public void shouldThrowAnExceptionWhenTryingToConnectToDeviceWithBluetoothDisabled() { NeuroSky neuroSky = new NeuroSky(deviceMessageListener); neuroSky.connect(); }
DeviceMessageHandler extends Handler { @Override public void handleMessage(Message message) { super.handleMessage(message); if (listener != null) { listener.onMessageReceived(message); } } DeviceMessageHandler(final DeviceMessageListener deviceMessageListener); @Override void handleMessage(Message message); }
@Test public void shouldHandleMessage() { DeviceMessageHandler handler = new DeviceMessageHandler(deviceMessageListener); handler.handleMessage(message); verify(deviceMessageListener).onMessageReceived(message); } @Test public void shouldNotHandleMessage() { DeviceMessageHandler handler = new DeviceMessageHandler(null); handler.handleMessage(message); verify(deviceMessageListener, times(0)).onMessageReceived(message); }
EventBus { public static EventBus create() { return new EventBus(); } private EventBus(); static EventBus create(); void send(final BrainEvent object); @SuppressWarnings("unchecked") Flowable<BrainEvent> receive(BackpressureStrategy backpressureStrategy); }
@Test public void shouldCreateBus() { EventBus bus = EventBus.create(); assertThat(bus).isNotNull(); }
RxNeuroSky { public Completable connect() { return Completable.create(emitter -> { if (!preconditions.isBluetoothEnabled()) { emitter.onError(new BluetoothNotEnabledException()); } if (preconditions.canConnect(device)) { openConnection(); emitter.onComplete(); } else { emitter.onError(new BluetoothConnectingOrConnectedException()); } }); } RxNeuroSky(); protected RxNeuroSky(final DeviceMessageListener listener); protected RxNeuroSky(final DeviceMessageListener listener, @NonNull Preconditions preconditions); Flowable<BrainEvent> stream(BackpressureStrategy backpressureStrategy); Flowable<BrainEvent> stream(); Completable connect(); Completable disconnect(); void enableRawSignal(); void disableRawSignal(); boolean isRawSignalEnabled(); Completable start(); Completable stop(); TGDevice getDevice(); DeviceMessageHandler getHandler(); }
@Test public void shouldThrowAnErrorWhenTryingToConnectToDeviceWithBluetoothDisabled() { RxNeuroSky neuroSky = new RxNeuroSky(); Throwable throwable = neuroSky.connect().blockingGet(); assertThat(throwable).isInstanceOf(BluetoothNotEnabledException.class); assertThat(throwable.getMessage()).isEqualTo(new BluetoothNotEnabledException().getMessage()); }