src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
BasicHttpClient extends AbstractHttpClient { public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } BasicHttpClient(URL url, String userName, String password); BasicHttpClient(URL url, String userName, String password, Map<String, String> config); void auth(HttpRequest req); @Override... | @Test(enabled = false,description = "http-get of remote address") public void testGetHttp() throws Exception { System.out.println("Get-http"); URL targetUrl = new URL("http: BasicHttpClient instance = new BasicHttpClient(targetUrl, "anon", "anon"); JSONObject result = instance.Get(targetUrl, getArgs.toJSONString()); as... |
DriverSettings extends AbstractPropSettings { public String getChromeDriverPath() { return getProperty("ChromeDriverPath", chromeDriverPath); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(Stri... | @Test public void testGetChromeDriverPath() { String expResult; if (isWin) { expResult = "./lib/Drivers/chromedriver.exe"; } else { expResult = "./lib/Drivers/chromedriver"; } String result = ds.getChromeDriverPath(); assertEquals(result, expResult); } |
JIRAClient { public boolean isConnected() { try { DLogger.Log(client.Get(new URL(client.url + PROJECT)).toString()); return true; } catch (Exception ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); return false; } } JIRAClient(String urlStr, String userName, String password, Map options); int updateResult(int status, ... | @Test(enabled = false) public void testConnection() throws MalformedURLException { JIRASync sync = new JIRASync(Data.server, Data.uname, Data.pass, Data.project); Assert.assertTrue(sync.isConnected()); } |
JIRAClient { @SuppressWarnings("unchecked") public JSONObject createIssue(JSONObject issue, List<File> attachments) { JSONObject res = null; try { res = client.post(new URL(client.url + ISSUE), issue.toString()); String restAttach = ISSUE_ATTACHMENTS.replace("issuekey", (String) res.get("id")); if (attachments != null ... | @Test(enabled = false) public void testCreateIssue_JSONObject_List() throws MalformedURLException { JSONObject res = null; JIRAClient jc = new JIRAClient(Data.server, Data.uname, Data.pass, null); Map issue = getIssue(Data.project); List<File> attach = null; res = jc.createIssue((JSONObject) issue, attach); } |
DriverSettings extends AbstractPropSettings { public String getIEDriverPath() { return getProperty("IEDriverPath", "./lib/Drivers/IEDriverServer.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDrive... | @Test public void testGetIEDriverPath() { String expResult = "./lib/Drivers/IEDriverServer.exe"; String result = ds.getIEDriverPath(); assertEquals(result, expResult); } |
DriverSettings extends AbstractPropSettings { public String getEdgeDriverPath() { return getProperty("EdgeDriverPath", "./lib/Drivers/MicrosoftWebDriver.exe"); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void se... | @Test public void testGetEdgeDriverPath() { String expResult = "./lib/Drivers/MicrosoftWebDriver.exe"; String result = ds.getEdgeDriverPath(); assertEquals(result, expResult); } |
DriverSettings extends AbstractPropSettings { public void setGeckcoDriverPath(String path) { setProperty("GeckoDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); v... | @Test public void testSetGeckcoDriverPath() { String path = "./lib/gk"; ds.setGeckcoDriverPath(path); assertEquals(ds.getGeckcoDriverPath(), path); } |
DriverSettings extends AbstractPropSettings { public void setChromeDriverPath(String path) { setProperty("ChromeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); ... | @Test public void testSetChromeDriverPath() { String path = "./lib/chrome"; ds.setChromeDriverPath(path); assertEquals(ds.getChromeDriverPath(), path); } |
DriverSettings extends AbstractPropSettings { public void setIEDriverPath(String path) { setProperty("IEDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void set... | @Test public void testSetIEDriverPath() { String path = "./lib/ie"; ds.setIEDriverPath(path); assertEquals(ds.getIEDriverPath(), path); } |
DriverSettings extends AbstractPropSettings { public void setEdgeDriverPath(String path) { setProperty("EdgeDriverPath", path); } DriverSettings(String location); void setFirefoxBinaryPath(String path); void setGeckcoDriverPath(String path); void setChromeDriverPath(String path); void setIEDriverPath(String path); void... | @Test public void testSetEdgeDriverPath() { String path = "./lib/edge"; ds.setEdgeDriverPath(path); assertEquals(ds.getEdgeDriverPath(), path); } |
FParser { public static List<String> getFuncList() { return FUNCTIONS; } static List<String> getFuncList(); static Object eval(String s); static String evaljs(String script); static List<String> FUNCTIONS; } | @Test public void testGetFuncList() { System.out.println("getFuncList"); String[] vals = {"Concat", "Random", "Round", "Pow", "Min", "Max", "Date"}; List<String> expResult = Arrays.asList(vals); Collections.sort(expResult); List<String> result = FParser.getFuncList(); Collections.sort(result); assertEquals(expResult.to... |
RedisAppender implements Appender { public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); } private RedisAppender(Builder builder); Configuration getConfig(); @Override String getName(); @Override Layout<? extends Serializable> getLayout(); @Override boolean ignoreExceptions(); @Override ErrorHand... | @Test public void test_messages_are_enqueued_to_redis() throws InterruptedException { LOGGER.debug("creating the logger"); Logger logger = LOGGER_CONTEXT_RESOURCE .getLoggerContext() .getLogger(RedisAppenderTest.class.getCanonicalName()); int expectedMessageCount = MIN_MESSAGE_COUNT + RANDOM.nextInt(MAX_MESSAGE_COUNT -... |
KeyLockManager { public static KeyLock getKeyLock(String type) { return keyLockMap.get(type); } static void init(String[] types, int keyLockExpireTime, int keyLockCycleSleepTime, ILog log); static KeyLock getKeyLock(String type); static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... ... | @Test public void testGetKeyLock() { KeyLock keylock = KeyLockManager.getKeyLock(TEST1); assertEquals(true, keylock != null); }
@Test public void testLockPartOneKey() { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(TEST1); String lockKey = "111"; boolean result = false; try { keyLock.l... |
MsgManager { public static boolean addMsgListener(IMsgListener msgListener) throws Exception { Map<String, String> msgs = msgListener.getMsgs(); if (msgs != null) { Object[] msgKeyArray = msgs.keySet().toArray(); for (int i = 0; i < msgKeyArray.length; i++) { String msg = String.valueOf(msgKeyArray[i]); Method method =... | @Test public void testAddMsgListener() throws Exception { TestMsgListener testMsgListener = new TestMsgListener(); boolean result = MsgManager.addMsgListener(testMsgListener); MsgManager.dispatchMsg("createuser", 111, 222); assertEquals(true, result); } |
RunMonitor { public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); } RunMonitor(String type, String opCode); void putMonitor(String content); String toString(String opCode); @Override String toString(); } | @Test public void testPutMonitor() { runMonitor.putMonitor("链接"); runMonitor.putMonitor("发送"); runMonitor.putMonitor("断开"); } |
ThreadMsgManager { public static boolean addMapping(String msgOpCode, int[] threadPriority) { if (msgOpcodeType.containsKey(msgOpCode)) { return false; } if (threadPriority != null) { msgOpcodeType.put(msgOpCode, threadPriority); } return true; } static boolean addMapping(String msgOpCode, int[] threadPriority); stati... | @Test public void testAddMapping() throws InterruptedException { ThreadMsgManager.dispatchThreadMsg("createuser", 111, 222); ThreadMsgManager.dispatchThreadMsg("updateuser", 111, 222); Thread.sleep(1000); } |
KeyLockManager { public static Object lockMethod(String lockKey, String keyType, KeylockFunction func, Object... params) { boolean isKeyLockException = false; KeyLock keyLock = KeyLockManager.getKeyLock(keyType); try { keyLock.lock(lockKey); return func.apply(params); } catch (KeyLockException e) { isKeyLockException =... | @Test public void testLockMethodOneKey() { String str = (String) KeyLockManager.lockMethod("111", TEST1, (params) -> lockFunction(params), new Object[] { "222", 111 }); assertEquals("222111", str); }
@Test public void testLockMethodTwoKey() { String str = (String) KeyLockManager.lockMethod("111", "222", TEST1, (params)... |
AsyncThreadManager { public static boolean addHandle(IHandle handle, int threadId, int priority) { if (handle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("handle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadMana... | @Test public void testAddHandle() throws NoSuchMethodException, SecurityException, InterruptedException { PacketTest packetTest = new PacketTest(); Method method = HandlerManagerTest.class.getMethod("handle", new Class[] { Object.class }); ThreadHandle threadHandle = new ThreadHandle(packetTest, method, null); boolean ... |
AsyncThreadManager { public static boolean addCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManager.... | @Test public void testAddCycle() { CycleTest cycleTest = new CycleTest(); cycleTest.name = "testAddCycle"; boolean result = AsyncThreadManager.addCycle(cycleTest, 1, 1); assertEquals(true, result); } |
AsyncThreadManager { public static boolean removeCycle(ICycle cycle, int threadId, int priority) { if (cycle == null) { if (AsyncThreadManager.log != null) { AsyncThreadManager.log.warn("ICycle为空"); } return false; } AsyncThread asyncThread = asyncThreadMap.get(threadId); if (asyncThread == null) { if (AsyncThreadManag... | @Test public void testRemoveCycle() { CycleTest cycleTest = new CycleTest(); cycleTest.name = "testRemoveCycle"; boolean result = AsyncThreadManager.addCycle(cycleTest, 1, 1); result = AsyncThreadManager.removeCycle(cycleTest, 1, 1); assertEquals(true, result); } |
AsyncThreadManager { public static int[] getRandomThreadPriority() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); int priority = (int) (Math.random() * asyncThreadPriorityNum + 1); return new int[] { thread, priority }; } static void init(int asyncThreadCycleInterval, int asyncThreadNum, ... | @Test public void testGetRandomThreadPriority() { int[] threadPriority = AsyncThreadManager.getRandomThreadPriority(); assertEquals(true, threadPriority != null); } |
AsyncThreadManager { public static int[] getRandomThread() { int thread = (int) (Math.random() * (asyncThreadNum - lockThreadNum) + 1); return new int[] { thread, 1 }; } static void init(int asyncThreadCycleInterval, int asyncThreadNum, int asyncThreadPriorityNum, int lockThreadNum, ILog log); static boolean addHandle... | @Test public void testGetRandomThread() { int[] threadPriority = AsyncThreadManager.getRandomThread(); assertEquals(true, threadPriority != null); } |
SpreadsheetDataSetProducer implements DataSetProducer { @Override public Schema getSchema() { return new Schema() { @Override public Table getTable(String name) { throw new UnsupportedOperationException("Cannot get the metadata of a table for a spreadsheet"); } @Override public boolean isEmptyDatabase() { return tables... | @Test public void testGetSchema() throws URISyntaxException { final SpreadsheetDataSetProducer producer = produceTestSpreadsheet(); Collection<String> tableNames = producer.getSchema().tableNames(); assertEquals("Number of tables found [" + tableNames + "]", 12, tableNames.size()); assertTrue("Tables correctly populate... |
RemoveIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) return false; Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesMa... | @Test public void testRemovingIndexFromNonExistentTable() { Schema testSchema = schema(appleTable); removeIndex = new RemoveIndex("Sweets", index("Sweets_1").unique().columns("pieces")); removeIndex.isApplied(testSchema, MockConnectionResources.build()); }
@Test public void testRemovingIndexFromExistingTable() { Schema... |
ExistingViewHashLoader { Optional<Map<String, String>> loadViewHashes(Schema schema) { if (!schema.tableExists(DEPLOYED_VIEWS_NAME)) { return Optional.empty(); } Map<String, String> result = Maps.newHashMap(); SelectStatement upgradeAuditSelect = select(field("name"), field("hash")).from(tableRef(DEPLOYED_VIEWS_NAME));... | @Test public void testNoDeployedViewsTable() { Schema schema = schema(table("SomeTable")); assertFalse(onTest.loadViewHashes(schema).isPresent()); }
@Test public void testFetch() throws SQLException { Schema schema = schema(table(DatabaseUpgradeTableContribution.DEPLOYED_VIEWS_NAME)); when(dataSource.getConnection()).t... |
UpgradePathFinder { public SchemaChangeSequence determinePath(Schema current, Schema target, Collection<String> exceptionRegexes) throws NoUpgradePathExistsException { SchemaChangeSequence schemaChangeSequence = getSchemaChangeSequence(); Schema trialUpgradedSchema = schemaChangeSequence.applyToSchema(current); if (!sc... | @Test public void testExactPath() { List<Class<? extends UpgradeStep>> upgradeSteps = new ArrayList<>(); upgradeSteps.add(AddJamType.class); upgradeSteps.add(AddCakeTable.class); upgradeSteps.add(AddDiameter.class); upgradeSteps.add(InsertAVictoriaSpongeRowUsingDSL.class); UpgradePathFinder pathFinder = makeFinder(upgr... |
RenameTable implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, oldTableName, newTableName); } RenameTable(String oldTableName, String newTableName); String getOldTableName(); String getNewTableName(); @Override Schema apply(Schema schema); @Override Schema reverse(Schema... | @Test(expected = IllegalArgumentException.class) public void testRenameTableNotExists() { Schema testSchema = schema(appleTable); RenameTable renameTable = new RenameTable("Pear", "Apple"); renameTable.apply(testSchema); }
@Test(expected = IllegalArgumentException.class) public void testRenameTableAlreadyExists() { Sch... |
AuditRecordHelper { public static void addAuditRecord(SchemaChangeVisitor visitor, Schema schema, UUID uuid, String description) { if (!schema.tableExists("UpgradeAudit")) return; InsertStatement auditRecord = createAuditInsertStatement(uuid, description); visitor.visit(new ExecuteStatement(auditRecord)); } static voi... | @Test public void testAddAuditRecord() throws ParseException { SchemaChangeVisitor visitor = mock(SchemaChangeVisitor.class); Schema schema = mock(Schema.class); UUID uuid = UUID.randomUUID(); String description = "Description"; given(schema.tableExists("UpgradeAudit")).willReturn(true); AuditRecordHelper.addAuditRecor... |
AuditRecordHelper { public static InsertStatement createAuditInsertStatement(UUID uuid, String description) { InsertStatement auditRecord = new InsertStatement().into( new TableReference("UpgradeAudit")).values( new FieldLiteral(uuid.toString()).as("upgradeUUID"), new FieldLiteral(description).as("description"), cast(d... | @Test public void createAuditInsertStatement() throws Exception { UUID uuid = UUID.randomUUID(); String description = "Description"; InsertStatement statement = AuditRecordHelper.createAuditInsertStatement(uuid, description); assertAuditInsertStatement(uuid, description, statement); } |
Deployment { public UpgradePath getPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps) { final UpgradePath path = upgradePathFactory.create(sqlDialect); writeStatements(targetSchema, path); writeUpgradeSteps(upgradeSteps, path); return path; } @Inject Deployment(SqlDialect sqlDialect, SqlS... | @Test public void testGetPath() { Table testTable = table("Foo").columns(column("name", DataType.STRING, 32)); View testView = view("FooView", select(field("name")).from(tableRef("Foo"))); View testView2 = view("BarView", select(field("name")).from(tableRef("MooView")), "MooView"); View testView3 = view("MooView", sele... |
ChangeColumn implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromColumn, toColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApp... | @Test public void testIncreaseColumnLength() { Schema testSchema = schema(appleTable); ChangeColumn changeColumn = new ChangeColumn("Apple", column("colour", DataType.STRING, 10).nullable(), column("colour", DataType.STRING, 35).nullable()); Schema updatedSchema = changeColumn.apply(testSchema); Table resultTable = upd... |
ChangeColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toColumn, fromColumn); } ChangeColumn(String tableName, Column fromColumn, Column toColumn); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isA... | @Test public void testReverseChangeLength() { appleTable = table("Apple").columns( idColumn(), versionColumn(), column("colour", DataType.STRING, 35).nullable(), column("variety", DataType.STRING, 15).nullable(), column("ispoisoned", DataType.BOOLEAN).nullable(), column("datecreated", DataType.DATE).nullable(), column(... |
UpgradeStatusTableServiceImpl implements UpgradeStatusTableService { @Override public UpgradeStatus getStatus(Optional<DataSource> dataSource) { SelectStatement select = SqlUtils.select(SqlUtils.field(STATUS_COLUMN)).from(tableRef(UpgradeStatusTableService.UPGRADE_STATUS)); Connection connection = null; try { if (dataS... | @SuppressWarnings("unchecked") @Test public void testGetStatusWhenTableNotPresent() { when(sqlScriptExecutor.executeQuery(anyString(), any(Connection.class), any(ResultSetProcessor.class))).thenThrow(RuntimeSqlException.class); assertEquals("Result", UpgradeStatus.NONE, upgradeStatusTableService.getStatus(Optional.of(d... |
ChangeIndex implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromIndex, toIndex); } ChangeIndex(String tableName, Index fromIndex, Index toIndex); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(Sch... | @Test public void testChangeIndexColumns() { Schema testSchema = schema(appleTable); ChangeIndex changeIndex = new ChangeIndex("Apple", index("Apple_1").columns("pips"), index("Apple_1").columns("totalValue")); Schema updatedSchema = changeIndex.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); as... |
ChangeIndex implements SchemaChange { @Override public Schema reverse(Schema schema) { return applyChange(schema, toIndex, fromIndex); } ChangeIndex(String tableName, Index fromIndex, Index toIndex); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boolean isApplied(S... | @Test public void testReverseChangeColumnType() { Schema testSchema = schema(appleTable); ChangeIndex changeIndex = new ChangeIndex("Apple", index("Apple_3").unique().columns("colour", "pips"), index("Apple_3").columns("pips")); Schema updatedSchema = changeIndex.reverse(testSchema); Table resultTable = updatedSchema.g... |
ChangeIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) { return false; } Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.index... | @Test public void testChangeIndexOnNonExistentTable() { Schema testSchema = schema(appleTable); ChangeIndex changeIndex = new ChangeIndex("Sweets", index("Sweets_1").unique().columns("pieces"), index("Sweets_1").unique().columns("pieces")); changeIndex.isApplied(testSchema, MockConnectionResources.build()); }
@Test pub... |
InlineTableUpgrader implements SchemaChangeVisitor { public void preUpgrade() { sqlStatementWriter.writeSql(sqlDialect.tableDeploymentStatements(idTable)); } InlineTableUpgrader(Schema startSchema, SqlDialect sqlDialect, SqlStatementWriter sqlStatementWriter, Table idTable); void preUpgrade(); void postUpgrade(); @Over... | @Test public void testPreUpgrade() { final ArgumentCaptor<Table> captor = ArgumentCaptor.forClass(Table.class); upgrader.preUpgrade(); verify(sqlDialect).tableDeploymentStatements(captor.capture()); assertTrue("Temporary table", captor.getValue().isTemporary()); } |
InlineTableUpgrader implements SchemaChangeVisitor { public void postUpgrade() { sqlStatementWriter.writeSql(sqlDialect.truncateTableStatements(idTable)); sqlStatementWriter.writeSql(sqlDialect.dropStatements(idTable)); } InlineTableUpgrader(Schema startSchema, SqlDialect sqlDialect, SqlStatementWriter sqlStatementWrit... | @Test public void testPostUpgrade() { final ArgumentCaptor<Table> truncateCaptor = ArgumentCaptor.forClass(Table.class); final ArgumentCaptor<Table> dropCaptor = ArgumentCaptor.forClass(Table.class); upgrader.postUpgrade(); verify(sqlDialect).truncateTableStatements(truncateCaptor.capture()); verify(sqlDialect).dropSta... |
InlineTableUpgrader implements SchemaChangeVisitor { @Override public void visit(AddTable addTable) { currentSchema = addTable.apply(currentSchema); writeStatements(sqlDialect.tableDeploymentStatements(addTable.getTable())); } InlineTableUpgrader(Schema startSchema, SqlDialect sqlDialect, SqlStatementWriter sqlStatemen... | @Test public void testVisitAddTable() { AddTable addTable = mock(AddTable.class); given(addTable.apply(schema)).willReturn(schema); upgrader.visit(addTable); verify(addTable).apply(schema); verify(sqlDialect, atLeastOnce()).tableDeploymentStatements(any(Table.class)); verify(sqlStatementWriter).writeSql(anyCollectionOf... |
UpgradeStatusTableServiceImpl implements UpgradeStatusTableService { @Override public int writeStatusFromStatus(UpgradeStatus fromStatus, UpgradeStatus toStatus) { List<String> script = updateTableScript(fromStatus, toStatus); try { return sqlScriptExecutorProvider.get().execute(script); } catch (RuntimeSqlException e)... | @Test public void testUpdateFromNoneToInProgress() { upgradeStatusTableService.writeStatusFromStatus(UpgradeStatus.NONE, UpgradeStatus.IN_PROGRESS); ArgumentCaptor<Table> tableCaptor = ArgumentCaptor.forClass(Table.class); verify(sqlDialect).tableDeploymentStatements(tableCaptor.capture()); assertEquals("Table name", t... |
InlineTableUpgrader implements SchemaChangeVisitor { private void visitStatement(Statement statement) { writeStatements(sqlDialect.convertStatementToSQL(statement, currentSchema, idTable)); } InlineTableUpgrader(Schema startSchema, SqlDialect sqlDialect, SqlStatementWriter sqlStatementWriter, Table idTable); void preUp... | @Test public void testVisitStatement() { ExecuteStatement executeStatement = mock(ExecuteStatement.class); Statement statement = mock(Statement.class); given(executeStatement.getStatement()).willReturn(statement); when(sqlDialect.convertStatementToSQL(eq(statement), any(Schema.class), any(Table.class))).thenCallRealMet... |
RenameIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) { return false; } Table table = schema.getTable(tableName); for (Index index : table.indexes()) { if (index.getName().equalsIgnoreCase(toIndexName)) { return true; ... | @Test public void testRenameIndexOnNonExistentTable() { Schema testSchema = schema(appleTable); RenameIndex renameIndex = new RenameIndex("Sweets", "Sweets_1", "Sweets_2"); assertFalse("Should not be applied", renameIndex.isApplied(testSchema, MockConnectionResources.build())); }
@Test public void testRenameIndexOnNonE... |
RenameIndex implements SchemaChange { @Override public Schema apply(Schema schema) { return applyChange(schema, fromIndexName, toIndexName); } RenameIndex(String tableName, String fromIndexName, String toIndexName); @Override void accept(SchemaChangeVisitor visitor); @Override Schema apply(Schema schema); @Override boo... | @Test(expected = IllegalArgumentException.class) public void testRenameIndexNoFromName() { Schema testSchema = schema(appleTable); RenameIndex renameIndex = new RenameIndex("Apple", " ", "Apple_3"); renameIndex.apply(testSchema); }
@Test(expected = IllegalArgumentException.class) public void testRenameIndexNoToName() {... |
AddIndex implements SchemaChange { @Override public Schema apply(Schema schema) { Table original = schema.getTable(tableName); if (original == null) { throw new IllegalArgumentException(String.format("Cannot add index [%s] to table [%s] as the table cannot be found", newIndex.getName(), tableName)); } List<String> inde... | @Test public void testAddingIndex() { Schema testSchema = schema(appleTable); Schema updatedSchema = addIndex.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade index count", 1, resultTable.indexes().size()); assertEquals("Post upgrade index na... |
AddIndex implements SchemaChange { @Override public Schema reverse(Schema schema) { Table original = schema.getTable(tableName); List<String> indexeNames = new ArrayList<>(); boolean foundAndRemovedIndex = false; for (Index index : original.indexes()) { if (index.getName().equalsIgnoreCase(newIndex.getName())) { foundA... | @Test public void testReverseAddingIndex() { appleTable = table("Apple").columns( column("pips", DataType.STRING, 10).nullable(), column("colour", DataType.STRING, 10).nullable() ).indexes( index("Apple_1").unique().columns("pips") ); Schema testSchema = schema(appleTable); Schema downGradedSchema = addIndex.reverse(te... |
AddIndex implements SchemaChange { @Override public boolean isApplied(Schema schema, ConnectionResources database) { if (!schema.tableExists(tableName)) { return false; } Table table = schema.getTable(tableName); SchemaHomology homology = new SchemaHomology(); for (Index index : table.indexes()) { if (homology.indexesM... | @Test public void testAddIndexToNonExistentTable() { Schema testSchema = schema(appleTable); addIndex = new AddIndex("Sweets", index("Sweets_1").unique().columns("pieces")); assertFalse("Index should not have been applied", addIndex.isApplied(testSchema, MockConnectionResources.build())); }
@Test public void testAddInd... |
TableSetSchema implements Schema { @Override public boolean tableExists(final String name) { return tables.stream().anyMatch(table -> table.getName().equalsIgnoreCase(name)); } TableSetSchema(Collection<Table> tables); @Override Collection<Table> tables(); @Override Table getTable(final String name); @Override boolean ... | @Test public void testTableExists() { assertTrue(schema.tableExists("Apple")); assertFalse(schema.tableExists("Peach")); }
@Test public void testTableExistsNotCaseSensitive() { assertTrue(schema.tableExists("APPLE")); assertTrue(schema.tableExists("apple")); } |
TableSetSchema implements Schema { @Override public Table getTable(final String name) { return tables.stream() .filter(table -> table.getName().equalsIgnoreCase(name)) .findFirst() .orElseThrow(() -> new IllegalArgumentException(String.format("Requested table [%s] does not exist.", name))); } TableSetSchema(Collection<... | @Test public void testGetTable() { final String tableName = "Apple"; Table appleTable = schema.getTable(tableName); assertNotNull(appleTable); assertEquals(tableName, appleTable.getName()); }
@Test public void testGetTableCaseInsensitive() { final String tableName = "Apple"; Table uppercaseTable = schema.getTable(table... |
Escaping { static String escapeCharacters(String recordValue) { int last = 0; StringBuilder escapedValue = new StringBuilder(recordValue.length()); for (int i=0; i<recordValue.length(); i++) { if (!isCharValidForXml(recordValue.charAt(i))) { escapedValue.append(recordValue.substring(last, i)); escapedValue.append(Strin... | @Test public void testEscapeCharacters() { for (TestCase testCase : testCases) { assertEquals(testCase.escaped, escapeCharacters(testCase.unescaped)); } } |
Escaping { static String unescapeCharacters(String attributeValue) { if (attributeValue == null) return null; char[] attributeChars = attributeValue.toCharArray(); StringBuilder result = new StringBuilder(attributeChars.length); int from = 0; int len = 0; int i = 0; while (i < attributeChars.length) { if (attributeChar... | @Test public void testUnescapeCharacters() { for (TestCase testCase : testCases) { assertEquals(testCase.unescaped, unescapeCharacters(testCase.escaped)); } assertEquals(string('a', 'b', 'c', (char) 0), unescapeCharacters("abc\0")); assertEquals(string('a', 'b', 'c', (char) 0), unescapeCharacters("abc\u0000")); } |
DataMaskingXmlDataSetConsumer extends XmlDataSetConsumer { @Override protected String getValue(Record record, Column column, String table) { if (tableColumnsToMask.containsKey(table) && tableColumnsToMask.get(table).contains(column.getName())) { return null; } return super.getValue(record, column, table); } DataMasking... | @Test public void getValue() { DummyXmlOutputStreamProvider dummyXmlOutputStreamProvider = new DummyXmlOutputStreamProvider(); DataSetConsumer testConsumer = new DataMaskingXmlDataSetConsumer(dummyXmlOutputStreamProvider, toMask); Table metaData = table("Test").columns( column("id", DataType.BIG_INTEGER).primaryKey().a... |
Version2to4TransformingReader extends Reader { static int readVersion(BufferedReader bufferedReader) { try { bufferedReader.mark(1024); try { char[] buffer = new char[1024]; int read = bufferedReader.read(buffer); if (read == -1) { return -1; } String content = new String(buffer, 0, read); Pattern pattern = Pattern.com... | @Test public void testReadVersion() throws IOException { try (BufferedReader reader = new BufferedReader(new StringReader( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<table version=\"1\">\n" + " <metadata name=\"Foo\">" ))) { Assert.assertEquals(1, Version2to4TransformingReader.readVersion(reader)); } try (Buffe... |
SchemaUtils { public static ColumnType type(DataType type) { return SchemaUtils.column(null, type); } private SchemaUtils(); static Column idColumn(); static Column versionColumn(); static Schema schema(); static Schema schema(Table... tables); static Schema schema(View... views); static Schema schema(Iterable<Table> ... | @Test public void testCreatingAColumnTypeNotNullable() { ColumnType columnType = SchemaUtils.type(DataType.DECIMAL, 10, 4, false); assertTrue("ColumnType type incorrect", columnType.getType().equals(DataType.DECIMAL)); assertTrue("ColumnType width incorrect", columnType.getWidth() == 10); assertTrue("ColumnType scale i... |
SchemaUtils { public static List<String> toUpperCase(List<String> listOfStrings) { return FluentIterable.from(listOfStrings).transform(new Function<String, String>() { @Override public String apply(String value) { return value.toUpperCase(); } }).toList(); } private SchemaUtils(); static Column idColumn(); static Colu... | @Test public void testToUpperCase() { assertEquals( Arrays.asList("ONE", "TWO", "THREE"), SchemaUtils.toUpperCase(Arrays.asList("One", "two", "thReE")) ); } |
CompositeSchema implements Schema { @Override public Table getTable(String name) { for (Schema schema : delegates) if (schema.tableExists(name)) return schema.getTable(name); throw new IllegalArgumentException("Unknown table [" + name + "]"); } CompositeSchema(Schema... schema); @Override boolean isEmptyDatabase(); @Ov... | @Test public void testOrdering() { assertSame("Bar table", schema1.getTable("Bar"), new CompositeSchema(schema1, schema2).getTable("Bar")); } |
TableHelper { public static Column columnWithName(Table table, String columnName) { for (Column currentColumn : table.columns()) { if (currentColumn.getName().equalsIgnoreCase(columnName)) { return currentColumn; } } return null; } static Column columnWithName(Table table, String columnName); static List<String> build... | @Test public void testColumnWithName() { String columnName = "columnName"; Table table = table("tableName").columns( idColumn(), versionColumn(), column(columnName, DataType.STRING, 10).nullable() ); assertEquals("Incorrect column", TableHelper.columnWithName(table, columnName).getName(), columnName); } |
TableHelper { public static Index indexWithName(Table table, String indexName) { for (Index currentIndex : table.indexes()) { if (currentIndex.getName().equalsIgnoreCase(indexName)) { return currentIndex; } } return null; } static Column columnWithName(Table table, String columnName); static List<String> buildColumnNa... | @Test public void testIndexWithName() { String indexName = "indexName"; Table table = table("tableName").indexes(index(indexName)); assertEquals("Incorrect index", TableHelper.indexWithName(table, indexName).getName(), indexName); } |
TableHelper { public static List<String> buildColumnNameList(Table table) { List<String> result = new ArrayList<String>(); for (Column currentColumn : table.columns()) { result.add(currentColumn.getName()); } return result; } static Column columnWithName(Table table, String columnName); static List<String> buildColumn... | @Test public void testBuildColumnNameList() { Table table = table("tableName").columns( idColumn(), versionColumn(), column("columnName1", DataType.STRING, 10).nullable(), column("columnName2", DataType.STRING, 10).nullable() ); assertEquals("Column list", Arrays.asList("id", "version", "columnName1", "columnName2"), T... |
SchemaValidator { public void validate(Schema schema) { for (Table table : schema.tables()) { validateTable(table); } for (View view : schema.views()) { validateView(view); } checkForValidationErrors(); } void validate(Schema schema); void validate(Table table); void validate(View view); } | @Test public void testValidSchema() { Schema validSchema = schema(simpleValidTable, edgeCaseValidTable); SchemaValidator validator = new SchemaValidator(); validator.validate(validSchema); }
@Test public void testInvalidTableName() { Schema invalidTableNameSchema = schema(simpleValidTable, invalidTableNameTable); try {... |
SpreadsheetDataSetProducer implements DataSetProducer { private List<Record> getRecords(Sheet sheet) { try { long id = 1; int row = findHeaderRow(sheet); final Map<String, Integer> columnHeadingsMap = new HashMap<>(); for (int i = 0; i < countHeadings(sheet, row); i++) { columnHeadingsMap.put(columnName(sheet.getCell(i... | @Test public void testGetRecords() throws URISyntaxException { final SpreadsheetDataSetProducer producer = produceTestSpreadsheet(); List<Record> records = Lists.newArrayList(producer.records("UsageMeterType")); assertEquals("Number of rows [" + records + "]", 2, records.size()); Record record = records.get(0); assertE... |
SchemaHomology { public boolean tablesMatch(Table table1, Table table2) { noDifferences = true; checkTable(table1, table2); return noDifferences; } SchemaHomology(); SchemaHomology(DifferenceWriter differenceWriter); SchemaHomology(DifferenceWriter differenceWriter, String schema1Name, String schema2Name); boolean sc... | @Test public void testDuplicate() { boolean match = schemaHomology.tablesMatch(appleTable, appleTableDuplicate); assertTrue(match); }
@Test public void testNameChange() { assertFalse(schemaHomology.tablesMatch(appleTable, appleNameChange)); }
@Test public void testAutonumbering() { assertFalse(schemaHomology.tablesMatc... |
SchemaHomology { public boolean schemasMatch(Schema schema1, Schema schema2, Collection<String> exclusionRegex) { noDifferences = true; HashMap<String, Table> schema2Tables = new HashMap<String, Table>(); for (Table table : schema2.tables()) { schema2Tables.put(table.getName().toUpperCase(), table); } Set<String> addit... | @Test public void testIdenticalSchemas() { Schema schema1 = schema(appleTable, pearTable, simpleTable); Schema schema2 = schema(appleTable, pearTable, simpleTable); boolean match = schemaHomology.schemasMatch(schema1, schema2, Sets.<String>newHashSet()); assertTrue(match); }
@Test public void testSchemasWithDifferentTa... |
SchemaHomology { public boolean columnsMatch(Column column1, Column column2) { noDifferences = true; checkColumn(null, column1, column2); return noDifferences; } SchemaHomology(); SchemaHomology(DifferenceWriter differenceWriter); SchemaHomology(DifferenceWriter differenceWriter, String schema1Name, String schema2Nam... | @Test public void testColumnsMatch() { assertTrue("columns should match", schemaHomology.columnsMatch(column("colour", DataType.STRING).nullable(), column("colour", DataType.STRING).nullable())); assertTrue("columns should match", schemaHomology.columnsMatch(column("colour", DataType.STRING).nullable(), column("COLOUR"... |
SchemaHomology { public boolean indexesMatch(Index index1, Index index2) { noDifferences = true; checkIndex("unspecified", index1, index2); return noDifferences; } SchemaHomology(); SchemaHomology(DifferenceWriter differenceWriter); SchemaHomology(DifferenceWriter differenceWriter, String schema1Name, String schema2N... | @Test public void testIndexesMatch() { assertTrue("indexes should match", schemaHomology.indexesMatch(index("ABC").unique().columns("a", "b", "c"), index("ABC").unique().columns("a", "b", "c"))); assertFalse("indexes should match", schemaHomology.indexesMatch(index("ABC").unique().columns("a", "b", "c"), index("ABC").u... |
SQLEntityNameValidationService { public boolean isNameConventional(String name) { return schemaValidator.isNameConventional(name); } @Inject SQLEntityNameValidationService(); boolean isReservedWord(String word); boolean isNameConventional(String name); boolean isEntityNameLengthValid(String name); } | @Test @Parameters(method="getNamePatternTestSubjects") public void testValidNamePattern(String name, boolean expectedResult) { boolean result = sqlEntityNameValidationService.isNameConventional(name); assertEquals(format("%s should have been valid=%s but was valid=%s", name, expectedResult, result), expectedResult, res... |
SQLEntityNameValidationService { public boolean isReservedWord(String word) { return schemaValidator.isSQLReservedWord(word); } @Inject SQLEntityNameValidationService(); boolean isReservedWord(String word); boolean isNameConventional(String name); boolean isEntityNameLengthValid(String name); } | @Test @Parameters(method="getReservedWordTestSubjects") public void testReservedWord(String name, boolean expectedResult) { boolean result = sqlEntityNameValidationService.isReservedWord(name); assertEquals(format("%s should have been reserved=%s but was reserved=%s", name, expectedResult, result), expectedResult, resu... |
SQLEntityNameValidationService { public boolean isEntityNameLengthValid(String name) { return schemaValidator.isEntityNameLengthValid(name); } @Inject SQLEntityNameValidationService(); boolean isReservedWord(String word); boolean isNameConventional(String name); boolean isEntityNameLengthValid(String name); } | @Test @Parameters(method="getNameLengthTestSubjects") public void testValidNameLength(String name, boolean expectedResult) { boolean result = sqlEntityNameValidationService.isEntityNameLengthValid(name); assertEquals(format("%s should have been valid=%s but was valid=%s", name, expectedResult, result), expectedResult, ... |
DataSetUtils { public static RecordBuilder record() { return new RecordBuilderImpl(); } static RecordBuilder record(); static StatementParametersBuilder statementParameters(); static DataSetProducerBuilder dataSetProducer(Schema schema); } | @Test public void testIntegerGetters() { assertEquals(-1, record().setInteger(INTEGER_COLUMN, -1).getInteger(INTEGER_COLUMN).intValue()); assertEquals(0, record().setInteger(INTEGER_COLUMN, 0).getInteger(INTEGER_COLUMN).intValue()); assertEquals(1, record().setInteger(INTEGER_COLUMN, 1).getInteger(INTEGER_COLUMN).intVa... |
UpgradeStatusTableServiceImpl implements UpgradeStatusTableService { @Override public void tidyUp(DataSource dataSource) { try { new SqlScriptExecutorProvider(dataSource, sqlDialect).get().execute(sqlDialect.dropStatements(table(UpgradeStatusTableService.UPGRADE_STATUS))); } catch (RuntimeSqlException e) { if (getStatu... | @Test public void testTidyUp() throws SQLException { upgradeStatusTableService.tidyUp(dataSource); ArgumentCaptor<Table> tableCaptor = ArgumentCaptor.forClass(Table.class); verify(sqlDialect).dropStatements(tableCaptor.capture()); assertEquals("Table", tableCaptor.getValue().getName(), UPGRADE_STATUS); } |
UnionSetOperator implements SetOperator { @Override public Builder<SetOperator> deepCopy(DeepCopyTransformation transformer) { return TempTransitionalBuilderWrapper.<SetOperator>wrapper(new UnionSetOperator(getUnionStrategy(),transformer.deepCopy(getSelectStatement()))); } UnionSetOperator(UnionStrategy unionStrategy, ... | @Test public void testDeepCopy() { SelectStatement parentSelect = new SelectStatement(); SelectStatement childSelect = new SelectStatement(); UnionSetOperator original = new UnionSetOperator(ALL, parentSelect, childSelect); UnionSetOperator copy = (UnionSetOperator) original.deepCopy(noTransformation()).build(); assert... |
BracketedExpression extends AliasedField implements Driver { public MathsField getInnerExpression() { return innerExpression; } BracketedExpression(MathsField innerExpression); private BracketedExpression(final String alias, MathsField innerExpression); @Override BracketedExpression as(String aliasName); MathsField ge... | @Test public void testInnerExpression() { assertEquals(plus(literal(1), literal(2)), onTest.getInnerExpression()); } |
BracketedExpression extends AliasedField implements Driver { @Override public void drive(ObjectTreeTraverser traverser) { traverser.dispatch(getInnerExpression()); } BracketedExpression(MathsField innerExpression); private BracketedExpression(final String alias, MathsField innerExpression); @Override BracketedExpressi... | @Test public void testDrive() { ObjectTreeTraverser.Callback callback = mock(ObjectTreeTraverser.Callback.class); onTest.drive(ObjectTreeTraverser.forCallback(callback)); verify(callback).visit(onTest.getInnerExpression()); } |
FieldFromSelect extends AliasedField implements Driver { public SelectStatement getSelectStatement() { return selectStatement; } private FieldFromSelect(String alias, SelectStatement selectStatement); FieldFromSelect(SelectStatement selectStatement); SelectStatement getSelectStatement(); @Override void drive(ObjectTr... | @Test public void testDeepCopyDetail() { SelectStatement statementWithTwoFields = new SelectStatement(new FieldReference("agreementNumber")).from(new TableReference("Schedule")) .where(Criterion.eq(new FieldReference(new TableReference("Schedule"), "agreementNumber"), "A001003657")); FieldFromSelect ffs = new FieldFrom... |
TableReference implements DeepCopyableWithTransformation<TableReference,
Builder<TableReference>> { @Override public int hashCode() { return new HashCodeBuilder(1559, 887) .append(schemaName) .append(name) .append(alias) .append(temporary) .toHashCode(); } private TableReference(... | @Test public void testHashCode() { assertEquals(isEqual.hashCode(), onTest.hashCode()); assertEquals(isEqualAliased.hashCode(), onTestAliased.hashCode()); } |
TableReference implements DeepCopyableWithTransformation<TableReference,
Builder<TableReference>> { @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (!(obj instanceof TableReference)) return false; TableReference rhs = (... | @Test public void testEquals() { assertEquals(isEqual, onTest); assertFalse(onTest.equals(null)); assertNotEquals(notEqualDueToSchema, onTest); assertNotEquals(notEqualDueToName, onTest); assertNotEquals(notEqualDueToAlias, onTest); assertEquals(isEqualAliased, onTestAliased); assertNotEquals(differentSchema, onTestAli... |
TableReference implements DeepCopyableWithTransformation<TableReference,
Builder<TableReference>> { public TableReference as(String aliasName) { if (AliasedField.immutableDslEnabled()) { return new TableReference(this, aliasName); } else { this.alias = aliasName; return this; } } ... | @Test public void testAliasImmutability() { AliasedField.withImmutableBuildersEnabled(() -> { assertEquals(isEqual.as("A"), onTest.as("A")); assertEquals(isEqual.as("B").as("A"), onTest.as("A")); assertNotEquals(isEqual.as("A"), onTest.as("B")); assertNotSame(onTest, onTest.as("A")); }); }
@Test public void testAliasMu... |
TableReference implements DeepCopyableWithTransformation<TableReference,
Builder<TableReference>> { @Override public Builder<TableReference> deepCopy(DeepCopyTransformation transformer) { return TempTransitionalBuilderWrapper.wrapper(deepCopy()); } private TableReference(TableRef... | @Test public void testDeepCopy() { TableReference deepCopy = onTest.deepCopy(); assertEquals(deepCopy, onTest); assertNotSame(deepCopy, onTest); }
@Test public void testDeepCopyAliased() { TableReference deepCopy = onTestAliased.deepCopy(); assertEquals(deepCopy, onTestAliased); assertNotSame(deepCopy, onTestAliased); ... |
ExistingViewStateLoader { public Result viewChanges(Schema sourceSchema, Schema targetSchema) { Map<String, View> viewsToDrop = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (View view : sourceSchema.views()) { viewsToDrop.put(view.getName().toUpperCase(), view); } Set<View> viewsToDeploy = new HashSet<>(targetSche... | @Test public void testNoChanges() { Schema sourceSchema = schema( view("View1", select(literal("x")).from(tableRef("a"))), view("VIEW2", select(literal("y")).from(tableRef("b"))), view("view3", select(literal("z")).from(tableRef("c"))) ); Schema targetSchema = schema( view("VIEW1", select(literal("x")).from(tableRef("a... |
DatabaseMetaDataProviderUtils { public static int getAutoIncrementStartValue(String columnComment) { if (StringUtils.isNotEmpty(columnComment)) { Matcher matcher = AUTONUM_START_REGEX.matcher(columnComment); if (matcher.find()) { return Integer.parseInt(matcher.group(1)); } } return -1; } static int getAutoIncrementSt... | @Test public void testGetAutoIncrementStartValue() { assertEquals("Failed to fetch correct value", 1234, DatabaseMetaDataProviderUtils.getAutoIncrementStartValue("AUTONUMSTART:[1234]")); assertEquals("Failed to fetch correct value from large string", 1234, DatabaseMetaDataProviderUtils.getAutoIncrementStartValue(" dfdf... |
DatabaseMetaDataProviderUtils { public static boolean shouldIgnoreIndex(String indexName) { return indexName.toUpperCase().matches(".*_PRF\\d+$"); } static int getAutoIncrementStartValue(String columnComment); static Optional<String> getDataTypeFromColumnComment(String columnComment); static boolean shouldIgnoreIndex(... | @Test public void shouldIgnoreIndex() { assertFalse(DatabaseMetaDataProviderUtils.shouldIgnoreIndex("Schedule_1")); assertFalse(DatabaseMetaDataProviderUtils.shouldIgnoreIndex("Fred")); assertFalse(DatabaseMetaDataProviderUtils.shouldIgnoreIndex("Schedule_PRF")); assertFalse(DatabaseMetaDataProviderUtils.shouldIgnoreIn... |
SqlQueryDataSetProducer implements DataSetProducer { @Override public void open() { try { this.connection = dataSource.getConnection(); this.wasAutoCommit = connection.getAutoCommit(); wasAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); } catch (SQLException e) { throw new RuntimeSqlException("... | @Test public void testOpen() throws SQLException { Table table = buildTable(); String query = "select column from table"; given(dataSource.getConnection()) .willReturn(connection); SqlQueryDataSetProducer producer = new SqlQueryDataSetProducer(table, query, dataSource, sqlDialect); producer.open(); verify(connection).s... |
SqlQueryDataSetProducer implements DataSetProducer { @Override public void close() { if (connection == null) { return; } try { for (ResultSetIterator resultSetIterator : openResultSets) { resultSetIterator.close(); } openResultSets.clear(); connection.setAutoCommit(wasAutoCommit); connection.close(); connection = null;... | @Test public void testClose() throws SQLException { Table table = buildTable(); String query = "select column from table"; given(dataSource.getConnection()) .willReturn(connection); given(connection.getAutoCommit()).willReturn(true); SqlQueryDataSetProducer producer = new SqlQueryDataSetProducer(table, query, dataSourc... |
SqlQueryDataSetProducer implements DataSetProducer { @Override public Iterable<Record> records(String tableName) { Table table = getSchema().getTable(tableName); return new Iterable<Record>() { @Override public Iterator<Record> iterator() { ResultSetIterator resultSetIterator = new ResultSetIterator(table, query, conne... | @Test public void testRecords() throws SQLException { Table table = buildTable(); String query = "select column from table"; given(dataSource.getConnection()) .willReturn(connection); ResultSet resultSet = mock(ResultSet.class); given(statement.executeQuery(query)).willReturn(resultSet); given(resultSet.findColumn("Col... |
DatabaseExceptionHelper { public boolean isCausedByTimeoutException(Throwable throwable) { if (ExceptionUtils.indexOfType(throwable, SQLTimeoutException.class) != -1) { return true; } for (Throwable causeThrowable : ExceptionUtils.getThrowables(throwable)) { if (MYSQL_TIMEOUT_EXCEPTION_NAME.equals(causeThrowable.getCla... | @Test public void testIsCausedByTimeoutForSQLTimeoutException() { assertEquals(true, databaseExceptionHelper.isCausedByTimeoutException(new ExtendsSQLTimeoutException())); }
@Test public void testIsCausedByTimeoutForMySQLTimeoutException() { assertEquals(true, databaseExceptionHelper.isCausedByTimeoutException(new MySQ... |
NamedParameterPreparedStatement implements AutoCloseable { public static ParseResult parse(String sql) { return new ParseResult(sql); } NamedParameterPreparedStatement(Connection connection, String query, Map<String, List<Integer>> indexMap, boolean queryOnly, ParseResult sql); static ParseResult parse(String sql); boo... | @Test public void testParse() { ParseResult parseResult = NamedParameterPreparedStatement.parse( "SELECT :fee,:fi, :fo(:fum), ':eek' FROM :fum WHERE :fum AND :fo" ); assertThat("Parsed SQL", parseResult.getParsedSql(), equalTo("SELECT ?,?, ?(?), ':eek' FROM ? WHERE ? AND ?")); assertThat("fee", parseResult.getIndexesFo... |
SqlScriptExecutor { public int execute(final Iterable<String> sqlScript) { final Holder<Integer> holder = new Holder<>(-1); doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { holder.set(SqlScriptExecutor.this.executeAndCommit(sqlScript, connection)); } }); return holder.get()... | @Test public void testExecute() throws SQLException { when(statement.getUpdateCount()).thenReturn(5).thenReturn(2); int result = sqlScriptExecutor.execute(sqlScripts); assertEquals("Return value", 7, result); }
@Test public void testExecuteFailure() throws Exception { when(statement.execute(sqlScriptOne)).thenThrow(new... |
SqlScriptExecutor { public int executeAndCommit(Iterable<String> sqlScript, Connection connection) { int result = 0; try { visitor.executionStart(); for (String sql : sqlScript) { result += executeInternal(sql, connection); connection.commit(); } visitor.executionEnd(); } catch (SQLException e) { throw reclassifiedRunt... | @Test public void testExecuteAndCommit() throws SQLException { when(statement.getUpdateCount()).thenReturn(5).thenReturn(2); int result = sqlScriptExecutor.executeAndCommit(sqlScripts, connection); assertEquals("Return value", 7, result); verify(connection, times(sqlScripts.size())).commit(); } |
InsertStatementDefaulter { public InsertStatement defaultMissingFields(InsertStatement statement) { if (statement.isParameterisedInsert()) { return statement; } Set<String> columnsWithValues = getColumnsWithValues(statement); return addColumnDefaults(statement, columnsWithValues); } protected InsertStatementDefaulter(... | @Test public void testInsertDefaultedDecimalValue() { InsertStatementDefaulter defaulter = new InsertStatementDefaulter(schema); InsertStatement statement = insert().into(new TableReference("Car")).values(new FieldLiteral("bob").as("name")).build(); statement = defaulter.defaultMissingFields(statement); assertEquals("F... |
ResultSetMismatch { @Override public String toString(){ StringBuilder mismatchDetails = new StringBuilder(); if (key.length > 0) { mismatchDetails.append("Row key:").append(Arrays.toString(key)).append(" "); } mismatchDetails.append("Type:[").append(mismatchType) .append("] Column:[").append(mismatchColumnIndex); misma... | @Test public void testToString(){ String[] keys = {"one", "two", "three"}; ResultSetMismatch unitUnderTest = new ResultSetMismatch(MismatchType.MISSING_LEFT, 3, "left", "rightValue", keys); String expectedString = "Row key:[one, two, three] Type:[MISSING_LEFT] Column:[3] Values:[left <> rightValue]"; assertEquals(expec... |
RemoveColumn implements SchemaChange { @Override public Schema apply(Schema schema) { Table original = schema.getTable(tableName); boolean foundColumn = false; List<String> columns = new ArrayList<>(); for (Column column : original.columns()) { if (column.getName().equalsIgnoreCase(columnDefinition.getName())) { foundC... | @Test public void testRemovingColumn() { Schema testSchema = schema(appleTable); Schema updatedSchema = removeColumn.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 3, resultTable.columns().size()); assertEquals("Post upgrade ... |
RemoveColumn implements SchemaChange { @Override public Schema reverse(Schema schema) { Table original = schema.getTable(tableName); List<String> columns = new ArrayList<>(); for (Column column : original.columns()) { columns.add(column.getName()); } columns.add(columnDefinition.getName()); return new TableOverrideSche... | @Test public void testReverseAddingColumn() { appleTable.columns().remove(3); Schema testSchema = schema(appleTable); Schema downGradedSchema = removeColumn.reverse(testSchema); Table resultTable = downGradedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 4, resultTable.c... |
RemoveTable implements SchemaChange { @Override public Schema reverse(Schema schema) { if(schema.tableExists(tableToBeRemoved.getName().toUpperCase())){ throw new IllegalArgumentException("Cannot perform reversal for for [" + tableToBeRemoved.getName() + "] table removal as it already exist."); } return new AugmentedSc... | @Test public void testReverseRemovingTable() { Schema testSchema = schema(appleTable, mangoTable); testSchema.tables().remove(appleTable); Schema updatedSchema = removeTable.reverse(testSchema); assertEquals("Post upgrade table count", 2, updatedSchema.tables().size()); assertTrue(updatedSchema.tableExists("Apple")); a... |
RemoveTable implements SchemaChange { @Override public Schema apply(Schema schema) { if(!schema.tableExists(tableToBeRemoved.getName().toUpperCase())){ throw new IllegalArgumentException("Cannot remove table [" + tableToBeRemoved.getName() + "] as it does not exist."); } return new FilteredSchema(schema, tableToBeRemov... | @Test public void testRemovingNonExistantIndex() { Schema testSchema = schema(appleTable); try { Table table = table("Orange").columns( column("colour", DataType.STRING, 10).nullable(), column("totalValue", DataType.STRING, 10).nullable() ); removeTable = new RemoveTable(table); removeTable.apply(testSchema); fail("Sho... |
AnalyseTable implements SchemaChange { @Override public Schema apply(Schema schema) { if (!schema.tableExists(tableName.toUpperCase())) { throw new IllegalArgumentException("Cannot analyse table [" + tableName + "] as it does not exist."); } return schema; } AnalyseTable(String tableName); @Override void accept(SchemaC... | @Test public void testApplyDoesNotChangeSchema() { Schema testSchema = schema(appleTable); AnalyseTable analyseTable = new AnalyseTable("Apple"); Schema updatedSchema = analyseTable.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column coun... |
SpreadsheetDataSetConsumer implements DataSetConsumer { @Override public void table(Table table, Iterable<Record> records) { Integer maxSampleRows = DEFAULT_SAMPLE_ROWS; if (rowsPerTable.isPresent()) { maxSampleRows = rowsPerTable.get().get(table.getName().toUpperCase()); } if (maxSampleRows == null) { log.info("File [... | @Test public void testIgnoreTable() { final MockTableOutputter outputter = new MockTableOutputter(); final SpreadsheetDataSetConsumer consumer = new SpreadsheetDataSetConsumer( mock(OutputStream.class), Optional.<Map<String, Integer>>of(ImmutableMap.of("COMPANY", 5)), outputter ); consumer.table(table("NotCompany"), NO... |
UpgradePath implements SqlStatementWriter { public List<String> getSql() { List<String> results = Lists.newLinkedList(); if (!sql.isEmpty() || !upgradeScriptAdditions.isEmpty()) results.addAll(initialisationSql); results.addAll(sql); for (UpgradeScriptAddition addition : upgradeScriptAdditions) { Iterables.addAll(resul... | @Test public void testSqlOrderingWhenEmpty() { Set<UpgradeScriptAddition> upgradeScriptAdditions = Collections.emptySet(); UpgradePath path = new UpgradePath(upgradeScriptAdditions, sqlDialect, ImmutableList.of("INIT1", "INIT2"), ImmutableList.of("FIN1", "FIN2")); List<String> sql = path.getSql(); assertEquals("Result"... |
UpgradePath implements SqlStatementWriter { private void addCommentsToDropUpgradeStatusTable(final StringBuilder sqlOutput) { String separator = System.getProperty("line.separator"); sqlOutput.append("-- WARNING - This upgrade step creates a temporary table " + UpgradeStatusTableService.UPGRADE_STATUS + "." + separator... | @Test public void testAddCommentsToDropUpgradeStatusTable() { UpgradePath path = factory.create(ImmutableList.of(mock(UpgradeStep.class)), sqlDialect); path.writeSql(ImmutableList.of("ABC", "DEF")); when(sqlDialect.dropStatements(any(Table.class))).thenReturn(Arrays.asList("FLUSH UPGRADE TABLE","DROP UPGRADE TABLE")); ... |
Upgrade { @Inject Upgrade(ConnectionResources connectionResources, DataSource dataSource, UpgradePathFactory factory, UpgradeStatusTableService upgradeStatusTableService) { super(); this.connectionResources = connectionResources; this.dataSource = dataSource; this.factory = factory; this.upgradeStatusTableService = upg... | @Test public void testUpgrade() throws SQLException { Table upgradeAudit = upgradeAudit(); Table car = originalCar(); Table driver = table("Driver") .columns( idColumn(), versionColumn(), column("name", DataType.STRING, 10).nullable(), column("address", DataType.STRING, 10).nullable() ); Table carUpgraded = upgradedCar... |
Upgrade { public UpgradePath findPath(Schema targetSchema, Collection<Class<? extends UpgradeStep>> upgradeSteps, Collection<String> exceptionRegexes) { final List<String> upgradeStatements = new ArrayList<>(); UpgradeStatus status = upgradeStatusTableService.getStatus(Optional.of(dataSource)); if (status != UpgradeSta... | @Test public void testUpgradeWithTriggerMessage() throws SQLException { ResultSet viewResultSet = mock(ResultSet.class); when(viewResultSet.next()).thenReturn(true, true, false); when(viewResultSet.getString(1)).thenReturn("FooView", "OldView"); when(viewResultSet.getString(2)).thenReturn("XXX"); ResultSet upgradeResul... |
AddColumn implements SchemaChange { @Override public Schema apply(Schema schema) { Table original = schema.getTable(tableName); List<String> columns = new ArrayList<>(); for (Column column : original.columns()) { if (column.getName().equalsIgnoreCase(newColumnDefinition.getName())) { throw new IllegalStateException("Co... | @Test public void testAddingColumn() { Schema testSchema = schema(appleTable); Schema updatedSchema = addColumn.apply(testSchema); Table resultTable = updatedSchema.getTable("Apple"); assertNotNull(resultTable); assertEquals("Post upgrade column count", 4, resultTable.columns().size()); assertEquals("Post upgrade exist... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.