Best JGiven code snippet using com.tngtech.jgiven.report.model.StepFormatter.formatTable
Source:StepFormatter.java
...71 @Override72 public String format( Object o ) {73 return null;74 }75 public DataTable formatTable( Object o ) {76 return formatter.format( o, tableAnnotation, parameterName, annotations );77 }78 }79 public static class ChainedFormatting<T> extends Formatting<ObjectFormatter<T>, T> {80 private final List<Formatting<?, String>> formattings = Lists.newArrayList();81 public ChainedFormatting( ObjectFormatter<T> innerFormatting ) {82 super( innerFormatting );83 }84 @Override85 public String format( T o ) {86 String result = getFormatter().format( o );87 for( Formatting<?, String> formatting : formattings ) {88 try {89 result = formatting.format( result );90 } catch( ClassCastException e ) {91 throw new JGivenWrongUsageException( "Could not apply the formatter. " +92 "When using multiple formatters on an argument, all but the last need to apply to strings.", e );93 }94 }95 return result;96 }97 public ChainedFormatting<T> addFormatting( Formatting<?, String> formatting ) {98 formattings.add( formatting );99 return this;100 }101 }102 public StepFormatter( String stepDescription, List<NamedArgument> arguments, List<ObjectFormatter<?>> formatters ) {103 this.stepDescription = stepDescription;104 this.arguments = arguments;105 this.formatters = formatters;106 }107 public List<Word> buildFormattedWords() {108 try {109 return buildFormattedWordsInternal();110 } catch( JGivenWrongUsageException e ) {111 throw new JGivenWrongUsageException( e.getMessage() + ". Step definition: " + stepDescription );112 }113 }114 private List<Word> buildFormattedWordsInternal() {115 List<Word> formattedWords = Lists.newArrayList();116 Set<String> usedArguments = Sets.newHashSet();117 int singlePlaceholderCounter = 0;118 boolean dropNextWhitespace = false;119 StringBuilder currentWords = new StringBuilder();120 for( int i = 0; i < stepDescription.length(); i++ ) {121 boolean dollarMatch = stepDescription.charAt( i ) == '$';122 boolean nextCharExists = ( i + 1 ) < stepDescription.length();123 boolean escapedDollarMatch = nextCharExists && stepDescription.charAt( i + 1 ) == '$';124 String argumentName = nextCharExists ? nextName( stepDescription.substring( i + 1 ) ) : "";125 boolean namedArgumentExists = argumentName.length() > 0;126 boolean namedArgumentMatch = namedArgumentExists && isArgument( argumentName );127 boolean enumArgumentMatch =128 nextCharExists && arguments.size() > nextIndex( stepDescription.substring( i + 1 ), arguments.size() );129 boolean singleDollarCountIndexExists = singlePlaceholderCounter < arguments.size();130 if( dollarMatch ) {131 // e.g $$132 if( escapedDollarMatch ) {133 formattedWords.add( new Word( "$" ) );134 i += 1;135 // e.g $argument136 } else if( namedArgumentMatch ) {137 int argumentIndex = getArgumentIndexByName( argumentName, 0 );138 addArgumentByIndex( argumentIndex, currentWords, formattedWords, usedArguments );139 i += argumentName.length();140 // e.g $1141 } else if( enumArgumentMatch ) {142 int argumentIndex = nextIndex( stepDescription.substring( i + 1 ), arguments.size() );143 addArgumentByIndex( argumentIndex, currentWords, formattedWords, usedArguments );144 i += Integer.toString( argumentIndex ).length();145 // e.g $argumentNotKnown - gets replaced with running counter146 } else if( singleDollarCountIndexExists && namedArgumentExists ) {147 int argumentIndex = singlePlaceholderCounter;148 addArgumentByIndex( argumentIndex, currentWords, formattedWords, usedArguments );149 singlePlaceholderCounter += 1;150 i += argumentName.length();151 // e.g $152 } else if( singleDollarCountIndexExists ) {153 int argumentIndex = singlePlaceholderCounter;154 addArgumentByIndex( argumentIndex, currentWords, formattedWords, usedArguments );155 singlePlaceholderCounter += 1;156 // e.g ($notKnown || $) && counter > argument.size157 } else {158 formattedWords.add( new Word( '$' + argumentName ) );159 i += argumentName.length();160 }161 // unfortunately we need this after every argument so the Joiner can use .join(' ') on the formattedWords162 dropNextWhitespace = true;163 // if no placeholder was detected, check dropNextWhitespace rule and append the next character164 } else {165 if (dropNextWhitespace && stepDescription.charAt( i ) == ' ') {166 dropNextWhitespace = false;167 } else {168 currentWords.append( stepDescription.charAt( i ) );169 }170 }171 }172 flushCurrentWord( currentWords, formattedWords, false );173 formattedWords.addAll( getRemainingArguments( usedArguments ) );174 return formattedWords;175 }176 /**177 * Greedy search for the next String from the start in the {@param description}178 * until a non JavaIdentifierPart or $ is found179 *180 * @param description the searchable {@link String}181 * @return a {@link String} consisting only of JavaIdentifiableParts182 */183 private static String nextName( String description ) {184 StringBuilder result = new StringBuilder();185 for( int i = 0; i < description.length(); i++ ) {186 char c = description.charAt( i );187 if( Character.isJavaIdentifierPart( c ) && c != '$' ) {188 result.append( c );189 } else {190 break;191 }192 }193 return result.toString();194 }195 private int getArgumentIndexByName( String argumentName, int defaultIndex ) {196 for( int i = 0; i < arguments.size(); i++ ) {197 if( arguments.get( i ).name.equals( argumentName ) ) {198 return i;199 }200 }201 return defaultIndex;202 }203 private boolean isArgument( String argumentName ) {204 for( NamedArgument arg : arguments ) {205 if( arg.name.equals( argumentName ) ) {206 return true;207 }208 }209 return false;210 }211 /**212 * Looks up the argument by index via {@link #argumentIndexToWord(int)}, adds it to formattedWords and usedArguments213 * and flushes the previously accumulated text via {@link #flushCurrentWord(StringBuilder, List, boolean)}.214 *215 * @param index is searchable index216 * @param currentWords this {@link StringBuilder} holds the previously accumulated words217 * @param formattedWords this is the resulting List of Words218 * @param usedArguments this is the set which tracks which arguments were already used219 */220 private void addArgumentByIndex( int index, StringBuilder currentWords, List<Word> formattedWords, Set<String> usedArguments ) {221 flushCurrentWord( currentWords, formattedWords, true );222 Word argument = argumentIndexToWord( index );223 formattedWords.add( argument );224 usedArguments.add( argument.getArgumentInfo().getArgumentName() );225 }226 /**227 * Gets the argument based on the index, uses {@link #toDefaultStringFormat(Object)} and {@link #formatters} to format228 * the value and name of the Word accordingly229 *230 * @param index is the searchable index in {@link #arguments}231 * @return the {@link Word}232 */233 private Word argumentIndexToWord( int index ) {234 Object value = arguments.get( index ).value;235 String defaultFormattedValue = toDefaultStringFormat( value );236 ObjectFormatter<?> formatter = formatters.get( index );237 String formattedValue = formatUsingFormatterOrNull( formatter, value );238 String argumentName = WordUtil.fromSnakeCase( arguments.get( index ).name );239 return Word.argWord( argumentName, defaultFormattedValue, formattedValue );240 }241 /**242 * Appends the accumulated words to the resulting words. Trailing whitespace is removed because of the243 * postprocessing that inserts custom whitespace244 *245 * @param currentWords is the {@link StringBuilder} of the accumulated words246 * @param formattedWords is the list that is being appended to247 */248 private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {249 if( currentWords.length() > 0 ) {250 if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {251 currentWords.setLength( currentWords.length() - 1 );252 }253 formattedWords.add( new Word( currentWords.toString() ) );254 currentWords.setLength( 0 );255 }256 }257 /**258 * Returns the next index of the argument by decrementing 1 from the possibly parsed number259 *260 * @param description this String will be searched from the start for a number261 * @param defaultIndex this will be returned if the match does not succeed262 * @return the parsed index or the defaultIndex263 */264 private static int nextIndex( String description, int defaultIndex ) {265 Pattern startsWithNumber = Pattern.compile( "(\\d+).*" );266 Matcher matcher = startsWithNumber.matcher( description );267 if( matcher.matches() ) {268 return Integer.parseInt( matcher.group( 1 ) ) - 1;269 }270 return defaultIndex;271 }272 private List<Word> getRemainingArguments( Set<String> usedArguments ) {273 List<Word> remainingArguments = Lists.newArrayList();274 for( int i = 0; i < arguments.size(); i++ ) {275 Object value = arguments.get( i ).value;276 String formattedValue = formatUsingFormatterOrNull( formatters.get( i ), value );277 if( !usedArguments.contains( arguments.get( i ).name ) ) {278 if( formattedValue == null279 && formatters.get( i ) != null280 && ( formatters.get( i ) instanceof TableFormatting ) ) {281 DataTable dataTable = ( (TableFormatting) formatters.get( i ) ).formatTable( value );282 remainingArguments.add( Word.argWord( arguments.get( i ).name, toDefaultStringFormat( value ),283 dataTable ) );284 } else {285 remainingArguments.add( Word.argWord( arguments.get( i ).name, toDefaultStringFormat( value ), formattedValue ) );286 }287 }288 }289 return remainingArguments;290 }291 @SuppressWarnings( "unchecked" )292 private <T> String formatUsingFormatterOrNull( ObjectFormatter<T> argumentFormatter, Object value ) {293 if( argumentFormatter == null ) {294 return null;295 }...
formatTable
Using AI Code Generation
1import com.tngtech.jgiven.report.model.StepFormatter2import com.tngtech.jgiven.report.model.StepModel3def stepFormatter = new StepFormatter()4def stepModel = new StepModel()5stepModel.setRawDescription("Given I have a table:\n" +6stepFormatter.formatTable(stepModel)7println stepModel.getFormattedDescription()8import com.tngtech.jgiven.impl.util.TableFormatter9import com.tngtech.jgiven.report.model.StepModel10import com.tngtech.jgiven.format.TableFormatter11def stepModel = new StepModel()12stepModel.setRawDescription("Given I have a table:\n" +13TableFormatter.formatTable(stepModel)14println stepModel.getFormattedDescription()15import com.tngtech.jgiven.format.TableFormatter16import com.tngtech.jgiven.report.model.StepModel17def stepModel = new StepModel()18stepModel.setRawDescription("Given I have a table:\n" +19TableFormatter.formatTable(stepModel)20println stepModel.getFormattedDescription()
formatTable
Using AI Code Generation
1import com.tngtech.jgiven.report.model.StepFormatter2StepFormatter formatter = new StepFormatter()3def table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4"]])4StepFormatter formatter = new StepFormatter()5def table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4"]])6StepFormatter formatter = new StepFormatter()7String table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4"]])8StepFormatter formatter = new StepFormatter()9String table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4"]])10StepFormatter formatter = new StepFormatter()11String table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4"]])12StepFormatter formatter = new StepFormatter()13String table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4"]])14StepFormatter formatter = new StepFormatter()15String table = formatter.formatTable("table", ["column1", "column2"], [["row1", "row2"], ["row3", "row4
formatTable
Using AI Code Generation
1public static String formatTable( Table table ) {2 if( table == null ) {3 return "";4 }5 StringBuilder sb = new StringBuilder();6 List<TableRow> rows = table.getRows();7 int[] columnWidths = new int[ table.getColumnCount() ];8 for( TableRow row : rows ) {9 List<String> cells = row.getCells();10 for( int i = 0; i < cells.size(); i++ ) {11 columnWidths[ i ] = Math.max( columnWidths[ i ], cells.get( i ).length() );12 }13 }14 for( TableRow row : rows ) {15 List<String> cells = row.getCells();16 for( int i = 0; i < cells.size(); i++ ) {17 String cell = cells.get( i );18 sb.append( cell );19 int padding = columnWidths[ i ] - cell.length();20 for( int j = 0; j < padding; j++ ) {21 sb.append( ' ' );22 }23 sb.append( " | " );24 }25 sb.append( "26" );27 }28 return sb.toString();29 }30public void #StepName( Table table ) {31 String formattedTable = StepFormatter.formatTable( table );32 }33public void #StepName( Table table ) {34 }35public void #StepName( Table table ) {36 }37public void #StepName( Table table ) {38 }
formatTable
Using AI Code Generation
1import java.util.List;2import java.util.ArrayList;3import java.util.Arrays;4import com.tngtech.jgiven.annotation.Format;5import com.tngtech.jgiven.annotation.ProvidedScenarioState;6import com.tngtech.jgiven.annotation.ScenarioState;7import com.tngtech.jgiven.report.model.StepFormatter;8public class MyTest extends ScenarioTest<MyTest.TestSteps> {9 public static class TestSteps extends Stage<TestSteps> {10 String table;11 String formattedTable;12 public TestSteps a_table_with_$_rows_$_and_$_columns(int rows, int columns) {13 List<List<String>> table = new ArrayList<List<String>>();14 for (int i = 0; i < rows; i++) {15 List<String> row = new ArrayList<String>();16 for (int j = 0; j < columns; j++) {17 row.add("" + i + "_" + j);18 }19 table.add(row);20 }21 this.table = StepFormatter.formatTable(table);22 return self();23 }24 public TestSteps the_table_is_formatted() {25 formattedTable = StepFormatter.formatTable(table);26 return self();27 }28 public TestSteps the_table_is_formatted_with_$_as_header_separator(String separator) {29 formattedTable = StepFormatter.formatTable(table, separator);30 return self();31 }32 public TestSteps the_table_is_formatted_with_$_as_header_separator_$_and_$_as_row_separator(String headerSeparator, String rowSeparator) {33 formattedTable = StepFormatter.formatTable(table, headerSeparator, rowSeparator);34 return self();35 }36 public TestSteps the_table_is_formatted_with_$_as_header_separator_$_and_$_as_row_separator_$_and_$_as_column_separator(String headerSeparator, String rowSeparator, String columnSeparator) {37 formattedTable = StepFormatter.formatTable(table, headerSeparator, rowSeparator, columnSeparator);38 return self();39 }40 public TestSteps the_table_is_formatted_with_$_as_header_separator_$_and_$_as_row_separator_$_and_$_as_column_separator_$_and_$_as_escape_character(String headerSeparator, String rowSeparator, String columnSeparator, String escapeCharacter) {41 formattedTable = StepFormatter.formatTable(table, headerSeparator, rowSeparator, columnSeparator, escapeCharacter);
formatTable
Using AI Code Generation
1def "A scenario with a step that has a table"() {2 given().a_step_with_a_table()3 when().a_step_with_a_table()4 then().a_step_with_a_table()5}6def a_step_with_a_table() {7 [formatValue("column1"), formatValue("column2")],8 [formatValue("value1"), formatValue("value2")]9 step(formatTable(table))10}11def "A scenario with a step that has a table"() {12 given().a_step_with_a_table()13 when().a_step_with_a_table()14 then().a_step_with_a_table()15}16def a_step_with_a_table() {17 [formatValue("column1"), formatValue("column2")],18 [formatValue("value1"), formatValue("value2")]19 step(formatTable(table))20}21def "A scenario with a step that has a table"() {22 given().a_step_with_a_table()23 when().a_step_with_a_table()24 then().a_step_with_a_table()25}26def a_step_with_a_table() {27 [formatValue("column1"), formatValue("column2")],28 [formatValue("value1"), formatValue("value2")]29 step(formatTable(table))30}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!