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(); @Ov... | @Test public void expectedRankRegressionTestCorrectInput() throws ParsingFailedException, TrainModelsFailedException, PredictionFailedException, LossException { File file = new File(getTestRessourcePathFor(OBJECT_RANKING_DATASET_B)); ExpectedRankRegression expectedRankRegressionAlgorithm = new ExpectedRankRegression();... |
AAlgorithm implements IAlgorithm { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getAlgorithmConfiguration().overrideConfiguration(jsonObject); } AAlgorithm(); AAlgorithm(String algorithmIdentifier); @Override AAlgorithmConfiguration getDefaultAlgorithmConfigura... | @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 (ParameterVali... |
PlackettLuceModelFittingAlgorithm extends ARankingDistributionFittingAlgorithm<PlackettLuceModelFittingAlgorithmConfiguration> { @Override public PlackettLuceModel fit(IDistributionSampleSet<Ranking> sampleSet) throws FittingDistributionFailedException { assertCorrectSampleSetType(sampleSet); initializeAlgorithm((Plack... | @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(expecte... |
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 =... | @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<SnippetEn... |
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.... | @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 filt... | @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, ... |
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.... | @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, fullSmsBod... | @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}}"; Str... |
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("([.\\[\\]{}()*+\\-?^$|])", "\\\\$... | @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.findTemplate... |
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; tagCategori... | @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").i... |
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(... | @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.ordina... |
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(... | @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... |
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().le... |
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.notifyA... | @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); sleepM... |
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, OnCurrenc... | @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(Curr... |
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... | @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 ge... | @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.... |
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... | @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_c... |
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.at... | @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(... |
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)}); ... | @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)... |
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... | @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(-2... |
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 ent... | @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_CATEGOR... |
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.getCoun... | @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, re... |
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_wh... |
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... |
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 eje... | @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... | @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... |
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<Strin... | @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> getProte... | @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(); ... | @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... |
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> peop... | @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_mess... |
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_1... |
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); assert... |
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 sho... |
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() { ChargeCalcu... |
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 + " " +... | @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 ... |
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);... | @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 ... |
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(b... | @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_g... |
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... |
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... |
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 += "na... | @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("Extrac... |
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_... |
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 r... |
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 ... | @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", alert... |
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()... |
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(8... |
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); } Residential... | @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); } Disabilit... | @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.... | @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 AssetManag... | @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 ... | @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 inpu... | @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... | @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: "... |
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(m... |
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; macroP... |
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();... | @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(... |
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 newNodeN... | @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> getExternalSourc... | @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();... | @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 re... | @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"... |
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)); } S... | @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_i... |
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)); } S... | @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_i... |
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)); } S... | @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_i... |
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_... | @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(_... |
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_7351... | @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(_01... |
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 triple... | @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)); as... |
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 + ") bu... | @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(_0... |
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 SimpleTi... | @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... |
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 SimpleTi... | @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... |
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 SimpleTi... | @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... |
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, ((ICompactTripletsStructure... | @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, ... |
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... |
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 > varNam... | @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 ... |
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 = ((ITie... | @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); fo... | @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... |
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)... | @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)); A... |
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,... | @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)); assertEqu... |
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... | @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(... |
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 = parseBoolea... | @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, i... | @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 devi... | @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); boole... |
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... | @Test public void bluetoothAdapterShouldBeInitialized() { boolean isInitialized = preconditions.isBluetoothAdapterInitialized(); assertThat(isInitialized).isTrue(); }
@Test public void bluetoothAdapterShouldNotBeInitializedWhenItsNull() { boolean isInitialized = preconditions.isBluetoothAdapterInitialized(null); assert... |
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 bo... | @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 is... |
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 Preco... | @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)... |
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 BluetoothConnectingOrConnected... | @Test public void shouldThrowAnErrorWhenTryingToConnectToDeviceWithBluetoothDisabled() { RxNeuroSky neuroSky = new RxNeuroSky(); Throwable throwable = neuroSky.connect().blockingGet(); assertThat(throwable).isInstanceOf(BluetoothNotEnabledException.class); assertThat(throwable.getMessage()).isEqualTo(new BluetoothNotEn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.