Best Karate code snippet using com.intuit.karate.core.Table.toString
Source:ScenarioContext.java  
...346        return sv.getAsString();347    }348    private static String asString(Map<String, Object> map, String key) {349        Object o = map.get(key);350        return o == null ? null : o.toString();351    }352    public void updateResponseVars() {353        vars.put(ScriptValueMap.VAR_RESPONSE_STATUS, prevResponse.getStatus());354        vars.put(ScriptValueMap.VAR_REQUEST_TIME_STAMP, prevResponse.getStartTime());355        vars.put(ScriptValueMap.VAR_RESPONSE_TIME, prevResponse.getResponseTime());356        vars.put(ScriptValueMap.VAR_RESPONSE_COOKIES, prevResponse.getCookies());357        if (config.isLowerCaseResponseHeaders()) {358            Object temp = new ScriptValue(prevResponse.getHeaders()).toLowerCase();359            vars.put(ScriptValueMap.VAR_RESPONSE_HEADERS, temp);360        } else {361            vars.put(ScriptValueMap.VAR_RESPONSE_HEADERS, prevResponse.getHeaders());362        }363        byte[] responseBytes = prevResponse.getBody();364        bindings.putAdditionalVariable(ScriptValueMap.VAR_RESPONSE_BYTES, responseBytes);365        String responseString = FileUtils.toString(responseBytes);366        Object responseBody = responseString;367        responseString = StringUtils.trimToEmpty(responseString);368        if (Script.isJson(responseString)) {369            try {370                responseBody = JsonUtils.toJsonDoc(responseString);371            } catch (Exception e) {372                logger.warn("json parsing failed, response data type set to string: {}", e.getMessage());373            }374        } else if (Script.isXml(responseString)) {375            try {376                responseBody = XmlUtils.toXmlDoc(responseString);377            } catch (Exception e) {378                logger.warn("xml parsing failed, response data type set to string: {}", e.getMessage());379            }380        }381        vars.put(ScriptValueMap.VAR_RESPONSE, responseBody);382    }383    public void invokeAfterHookIfConfigured(boolean afterFeature) {384        if (callDepth > 0) {385            return;386        }387        ScriptValue sv = afterFeature ? config.getAfterFeature() : config.getAfterScenario();388        if (sv.isFunction()) {389            try {390                sv.invokeFunction(this, null);391            } catch (Exception e) {392                String prefix = afterFeature ? "afterFeature" : "afterScenario";393                logger.warn("{} hook failed: {}", prefix, e.getMessage());394            }395        }396    }397    //==========================================================================398    //399    public void configure(String key, String exp) {400        configure(key, Script.evalKarateExpression(exp, this));401    }402    public void url(String expression) {403        String temp = Script.evalKarateExpression(expression, this).getAsString();404        request.setUrl(temp);405    }406    public void path(List<String> paths) {407        for (String path : paths) {408            ScriptValue temp = Script.evalKarateExpression(path, this);409            if (temp.isListLike()) {410                List list = temp.getAsList();411                for (Object o : list) {412                    if (o == null) {413                        continue;414                    }415                    request.addPath(o.toString());416                }417            } else {418                request.addPath(temp.getAsString());419            }420        }421    }422    public void param(String name, List<String> values) {423        request.setParam(name, evalList(values));424    }425    public void params(String expr) {426        Map<String, Object> map = evalMapExpr(expr);427        for (Map.Entry<String, Object> entry : map.entrySet()) {428            String key = entry.getKey();429            Object temp = entry.getValue();430            if (temp == null) {431                request.removeParam(key);432            } else {433                if (temp instanceof List) {434                    request.setParam(key, (List) temp);435                } else {436                    request.setParam(key, temp.toString());437                }438            }439        }440    }441    public void cookie(String name, String value) {442        ScriptValue sv = Script.evalKarateExpression(value, this);443        Cookie cookie;444        if (sv.isMapLike()) {445            cookie = new Cookie((Map) sv.getAsMap());446            cookie.put(Cookie.NAME, name);447        } else {448            cookie = new Cookie(name, sv.getAsString());449        }450        request.setCookie(cookie);451    }452    public void cookies(String expr) {453        Map<String, Object> map = evalMapExpr(expr);454        for (Map.Entry<String, Object> entry : map.entrySet()) {455            String key = entry.getKey();456            Object temp = entry.getValue();457            if (temp == null) {458                request.removeCookie(key);459            } else {460                request.setCookie(new Cookie(key, temp.toString()));461            }462        }463    }464    public void header(String name, List<String> values) {465        request.setHeader(name, evalList(values));466    }467    public void headers(String expr) {468        Map<String, Object> map = evalMapExpr(expr);469        for (Map.Entry<String, Object> entry : map.entrySet()) {470            String key = entry.getKey();471            Object temp = entry.getValue();472            if (temp == null) {473                request.removeHeader(key);474            } else {475                if (temp instanceof List) {476                    request.setHeader(key, (List) temp);477                } else {478                    request.setHeader(key, temp.toString());479                }480            }481        }482    }483    public void formField(String name, List<String> values) {484        request.setFormField(name, evalList(values));485    }486    public void formFields(String expr) {487        Map<String, Object> map = evalMapExpr(expr);488        for (Map.Entry<String, Object> entry : map.entrySet()) {489            String key = entry.getKey();490            Object temp = entry.getValue();491            if (temp == null) {492                request.removeFormField(key);493            } else {494                if (temp instanceof List) {495                    request.setFormField(key, (List) temp);496                } else {497                    request.setFormField(key, temp.toString());498                }499            }500        }501    }502    public void request(ScriptValue body) {503        request.setBody(body);504    }505    public void request(String requestBody) {506        ScriptValue temp = Script.evalKarateExpression(requestBody, this);507        request(temp);508    }509    public void table(String name, List<Map<String, String>> table) {510        int pos = name.indexOf('='); // backward compatibility, we used to require this till v0.5.0511        if (pos != -1) {...Source:ScenarioRuntimeTest.java  
...224    @Test225    void testToString() {226        run(227                "def foo = { hello: 'world' }",228                "def fooStr = karate.toString(foo)",229                "def fooPretty = karate.pretty(foo)",230                "def fooXml = karate.prettyXml(foo)"231        );232        assertEquals(get("fooStr"), "{\"hello\":\"world\"}");233        assertEquals(get("fooPretty"), "{\n  \"hello\": \"world\"\n}\n");234        // fixed for windows235        assertEquals(((String) get("fooXml")).trim(), "<hello>world</hello>");236    }237    @Test238    void testGetSetAndRemove() {239        run(240                "karate.set('foo', 1)",241                "karate.set('bar', { hello: 'world' })",242                "karate.set({ a: 2, b: 'hey' })",243                "karate.setXml('fooXml', '<foo>bar</foo>')",244                "copy baz = bar",245                "karate.set('baz', '$.a', 1)",246                "karate.remove('baz', 'hello')",247                "copy bax = fooXml",248                "karate.setXml('bax', '/foo', '<a>1</a>')",249                "def getFoo = karate.get('foo')",250                "def getNull = karate.get('blah')",251                "def getDefault = karate.get('blah', 'foo')",252                "def getPath = karate.get('bar.hello')"253        );254        assertEquals(get("foo"), 1);255        assertEquals(get("a"), 2);256        assertEquals(get("b"), "hey");257        matchVar("bar", "{ hello: 'world' }");258        Object fooXml = get("fooXml");259        assertTrue(Match.that(fooXml).isXml());260        matchVar("fooXml", "<foo>bar</foo>");261        matchVar("baz", "{ a: 1 }");262        Match.that(get("bax")).isEqualTo("<foo><a>1</a></foo>");263        assertEquals(get("getFoo"), 1);264        assertEquals(get("getNull"), null);265        assertEquals(get("getDefault"), "foo");266        assertEquals(get("getPath"), "world");267    }268    @Test269    void testCollections() {270        run(271                "def foo = { a: 1, b: 2, c: 3 }",272                "def fooSize = karate.sizeOf(foo)",273                "def bar = [1, 2, 3]",274                "def barSize = karate.sizeOf(bar)",275                "def fooKeys = karate.keysOf(foo)",276                "def fooVals = karate.valuesOf(foo)"277        );278        assertEquals(get("fooSize"), 3);279        assertEquals(get("barSize"), 3);280        matchVar("fooKeys", "['a', 'b', 'c']");281        matchVar("fooVals", "[1, 2, 3]");282    }283    @Test284    void testMatch() {285        run(286                "def foo = { a: 1 }",287                "def mat1 = karate.match(foo, {a: 2})",288                "def mat2 = karate.match('foo == { a: 1 }')"289        );290        matchVar("mat1", "{ pass: false, message: '#notnull' }");291        matchVar("mat2", "{ pass: true, message: '#null' }");292    }293    @Test294    void testForEach() {295        run(296                "def foo = { a: 1, b: 2, c: 3 }",297                "def res1 = { value: '' }",298                "def fun = function(k, v, i){ res1.value += k + v + i }",299                "karate.forEach(foo, fun)",300                "def foo = ['a', 'b', 'c']",301                "def res2 = { value: '' }",302                "def fun = function(v, i){ res2.value += v + i }",303                "karate.forEach(foo, fun)"304        );305        matchVar("res1", "{ value: 'a10b21c32' }");306        matchVar("res2", "{ value: 'a0b1c2' }");307    }308    @Test309    void testMap() {310        run(311                "def foo = [{ a: 1 }, { a: 2 }, { a: 3 }]",312                "def fun = function(x){ return x.a }",313                "def res = karate.map(foo, fun)"314        );315        matchVar("res", "[1, 2, 3]");316        run(317                "def foo = [{ a: 1 }, { a: 2 }, { a: 3 }]",318                "def res = karate.map(foo, x => x.a)"319        );320        matchVar("res", "[1, 2, 3]");321        run(322                "def foo = [{ a: 1 }, { a: 2 }, { a: 3 }]",323                "def fun = (x, i) => `${x.a}${i}`",324                "def res1 = karate.map(foo, fun)",325                "def res2 = foo.map(x => x.a)"326        );327        matchVar("res1", "['10', '21', '32']");328        matchVar("res2", "[1, 2, 3]");329    }330    @Test331    void testFilter() {332        run(333                "def foo = [{ a: 0 }, { a: 1 }, { a: 2 }]",334                "def res = karate.filter(foo, x => x.a > 0)"335        );336        matchVar("res", "[{ a: 1 }, { a: 2 }]");337    }338    @Test339    void testFilterKeys() {340        run(341                "def foo = { a: 1, b: 2, c: 3 }",342                "def res1 = karate.filterKeys(foo, 'a')",343                "def res2 = karate.filterKeys(foo, 'a', 'c')",344                "def res3 = karate.filterKeys(foo, ['b', 'c'])",345                "def res4 = karate.filterKeys(foo, { a: 2, c: 5})"346        );347        matchVar("res1", "{ a: 1 }");348        matchVar("res2", "{ a: 1, c: 3 }");349        matchVar("res3", "{ b: 2, c: 3 }");350        matchVar("res4", "{ a: 1, c: 3 }");351    }352    @Test353    void testRepeat() {354        run(355                "def res1 = karate.repeat(3, i => i + 1 )",356                "def res2 = karate.repeat(3, i => ({ a: 1 }))",357                "def res3 = karate.repeat(3, i => ({ a: i + 1 }))"358        );359        matchVar("res1", "[1, 2, 3]");360        matchVar("res2", "[{ a: 1 }, { a: 1 }, { a: 1 }]");361        matchVar("res3", "[{ a: 1 }, { a: 2 }, { a: 3 }]");362    }363    @Test364    void testMapWithKey() {365        run(366                "def foo = [1, 2, 3]",367                "def res = karate.mapWithKey(foo, 'val')"368        );369        matchVar("res", "[{ val: 1 }, { val: 2 }, { val: 3 }]");370    }371    @Test372    void testMergeAndAppend() {373        run(374                "def foo = { a: 1 }",375                "def res1 = karate.merge(foo, { b: 2 })",376                "def bar = [1, 2]",377                "def res2 = karate.append(bar, [3, 4])",378                "def res3 = [1, 2]",379                "karate.appendTo('res3', [3, 4])",380                "def res4 = [1, 2]",381                "karate.appendTo(res4, [3, 4])" // append to variable reference !382        );383        matchVar("res1", "{ a: 1, b: 2 }");384        matchVar("res2", "[1, 2, 3, 4]");385        matchVar("res3", "[1, 2, 3, 4]");386        matchVar("res4", "[1, 2, 3, 4]");387    }388    @Test389    void testJsonPath() {390        run(391                "def foo = { a: 1, b: { a: 2 } }",392                "def res1 = karate.jsonPath(foo, '$..a')"393        );394        matchVar("res1", "[1, 2]");395    }396    @Test397    void testLowerCase() {398        run(399                "def foo = { HELLO: 'WORLD' }",400                "def res1 = karate.lowerCase(foo)"401        );402        matchVar("res1", "{ hello: 'world' }");403    }404    @Test405    void testXmlPath() {406        run(407                "def foo = <bar><a><b>c</b></a></bar>",408                "def res1 = karate.xmlPath(foo, '/bar/a')"409        );410        matchVar("res1", "<a><b>c</b></a>");411    }412    @Test413    void testJsonToString() {414        run(415                "def original = '{\"echo\":\"echo@gmail.com\",\"lambda\":\"Lambda\",\"bravo\":\"1980-01-01\"}'",416                "json asJson = original",417                "string asString = asJson",418                "match original == asString"419        );420    }421    @Test422    void testToBean() {423        run(424                "def foo = { foo: 'hello', bar: 5 }",425                "def res1 = karate.toBean(foo, 'com.intuit.karate.core.SimplePojo')"426        );427        SimplePojo sp = (SimplePojo) get("res1");428        assertEquals(sp.getFoo(), "hello");429        assertEquals(sp.getBar(), 5);430    }431    @Test432    void testToJson() {433        run(434                "def SP = Java.type('com.intuit.karate.core.SimplePojo')",435                "def pojo = new SP()",436                "def res1 = karate.toJson(pojo)",437                "def res2 = karate.toJson(pojo, true)"438        );439        matchVar("res1", "{ bar: 0, foo: null }");440        matchVar("res2", "{ bar: 0 }");441    }442    @Test443    void testToBeanAdvanced() {444        run(445                "def pojoType = 'com.intuit.karate.core.SimplePojo'",446                "def Pojo = Java.type(pojoType)",447                "def toPojo = function(x){ return karate.toBean(x, pojoType) }",448                "def toJson = function(x){ return karate.toJson(x, true) }",449                "def bean = new Pojo()",450                "bean.foo = 'hello'",451                "def pojo = toPojo({ bar: 5 })",452                "def json = toJson(pojo)"453        );454        matchVar("json", "{ bar: 5 }");455        SimplePojo bean = (SimplePojo) get("bean");456        assertEquals(0, bean.getBar());457        assertEquals("hello", bean.getFoo());458        SimplePojo pojo = (SimplePojo) get("pojo");459        assertEquals(5, pojo.getBar());460        assertNull(pojo.getFoo());461    }462    @Test463    void testToCsv() {464        run(465                "def foo = [{a: 1, b: 2}, { a: 3, b: 4 }]",466                "def res = karate.toCsv(foo)"467        );468        // fixed for windows469        match(((String) get("res")).replaceAll("[\r\n]+", "@"), "a,b@1,2@3,4@");470    }471    @Test472    void testTrim() {473        run(474                "def text = ' \\tblah\\n'",475                "def foo = karate.trim(text)",476                "match foo == 'blah'"477        );478        matchVar("foo", "blah");479    }480    @Test481    void testEval() {482        run(483                "def foo = karate.eval('() => 1 + 2')",484                "def bar = foo()"485        );486        assertTrue(sr.engine.vars.get("foo").isJsFunction());487        matchVar("bar", 3);488    }489    @Test490    void testFromString() {491        run(492                "def foo = karate.fromString('{ hello: \"world\" }')",493                "def bar = karate.typeOf(foo)"494        );495        assertTrue(sr.engine.vars.get("foo").isMap());496        matchVar("bar", "map");497    }498    @Test499    void testEmbed() {500        run(501                "karate.embed('<h1>hello world</h1>', 'text/html')"502        );503        List<StepResult> results = sr.result.getStepResults();504        assertEquals(1, results.size());505        List<Embed> embeds = results.get(0).getEmbeds();506        assertEquals(1, embeds.size());507        assertEquals(embeds.get(0).getAsString(), "<h1>hello world</h1>");508        assertEquals(embeds.get(0).getResourceType(), ResourceType.HTML);509    }510    @Test511    void testStepLog() {512        run(513                "print 'hello world'"514        );515        List<StepResult> results = sr.result.getStepResults();516        assertEquals(1, results.size());517        String log = results.get(0).getStepLog();518        assertTrue(log.contains("[print] hello world"));519    }520    @Test521    void testWrite() {522        run(523                "def file = karate.write('hello world', 'runtime-test.txt')"524        );525        File file = (File) get("file");526        assertEquals(file.getParentFile().getName(), "target");527        assertEquals(file.getName(), "runtime-test.txt");528        assertEquals(FileUtils.toString(file), "hello world");529    }530    @Test531    void testJavaClassAsVariable() {532        run(533                "def Utils = Java.type('com.intuit.karate.core.MockUtils')",534                "def res = Utils.testBytes"535        );536        assertEquals(get("res"), MockUtils.testBytes);537    }538    @Test539    void testCallJsFunctionShared() {540        run(541                "def myFn = function(x){ return { myVar: x } }",542                "call myFn 'foo'"543        );544        assertEquals(get("myVar"), "foo");545    }546    @Test547    void testCallJsFunctionSharedJson() {548        run(549                "def myFn = function(x){ return { myVar: x.foo } }",550                "call myFn { foo: 'bar' }"551        );552        assertEquals(get("myVar"), "bar");553    }554    @Test555    void testSelfValidationWithVariables() {556        run(557                "def date = { month: 3 }",558                "def min = 1",559                "def max = 12",560                "match date == { month: '#? _ >= min && _ <= max' }"561        );562    }563    @Test564    void testReadAndMatchBytes() {565        run(566                "bytes data = read('karate-logo.png')",567                "match data == read('karate-logo.png')"568        );569    }570    @Test571    void testJsonEmbeddedExpressionFailuresAreNotBlockers() {572        run(573                "def expected = { a: '#number', b: '#(_$.a * 2)' }",574                "def actual = [{a: 1, b: 2}, {a: 2, b: 4}]",575                "match each actual == expected"576        );577    }578    @Test579    void testXmlEmbeddedExpressionFailuresAreNotBlockers() {580        run(581                "def expected = <foo att='#(bar)'>#(bar)</foo>",582                "def actual = <foo att=\"test\">test</foo>",583                "def bar = 'test'",584                "match actual == expected"585        );586    }587    @Test588    void testMatchEachMagicVariablesDontLeak() {589        run(590                "def actual = [{a: 1, b: 2}, {a: 2, b: 4}]",591                "match each actual == { a: '#number', b: '#(_$.a * 2)' }",592                "def res = { b: '#(_$.a * 2)' }"593        );594        matchVar("res", "{ b: '#string' }");595    }596    @Test597    void testMatchMagicVariables() {598        run(599                "def temperature = { celsius: 100, fahrenheit: 212 }",600                "match temperature contains { fahrenheit: '#($.celsius * 1.8 + 32)' }"601        );602    }603    @Test604    void testMatchContainsArrayOnLhs() {605        run(606                "match ['foo', 'bar'] contains 'foo'"607        );608    }609    610    @Test611    void testMatchEmbeddedOptionalObject() {612        run(613                "def foo = { a: 1 }",614                "def bar = { foo: '##(foo)' }",615                "match bar == { foo: { a: 1 } }"616        );617    }618    @Test619    void testMatchSchema() {620        run(621                "def dogSchema = { id: '#string', color: '#string' }",622                "def schema = ({ id: '#string', name: '#string', dog: '##(dogSchema)' })",623                "def response1 = { id: '123', name: 'foo' }",624                "match response1 == schema",625                "def response2 = { id: '123', name: 'foo', dog: { id: '456', color: 'brown' } }",626                "match response2 == schema"627        );628    }629    @Test630    void testMatchSchemaMagicVariables() {631        run(632                "def response = { odds: [1, 2], count: 2 }",633                "match response == { odds: '#[$.count]', count: '#number' }"634        );635    }636    @Test637    void testJavaInteropStatic() {638        run(639                "def Utils = Java.type('com.intuit.karate.core.StaticUtils')",640                "def array = ['a', 'b', 'c']",641                "def res = Utils.concat(array)"642        );643        matchVar("res", "abc");644    }645    @Test646    void testJavaInteropBase64() {647        run(648                "def Base64 = Java.type('java.util.Base64')",649                "def res = Base64.encoder.encodeToString('hello'.getBytes())"650        );651        matchVar("res", java.util.Base64.getEncoder().encodeToString("hello".getBytes()));652    }653    @Test654    void testTypeConversionCsvEmpty() {655        run(656                "csv temp = ''"657        );658        matchVar("temp", "[]");659    }660    @Test661    void testJavaInteropParameters() {662        run(663                "def Utils = Java.type('com.intuit.karate.core.StaticUtils')",664                "def res1 = Utils.fromInt(2)",665                "def res2 = Utils.fromDouble(2)",666                "def res3 = Utils.fromDouble(2.0)",667                "def res4 = Utils.fromNumber(2.0)"668        );669        matchVar("res1", "value is 2");670        matchVar("res2", "value is 2.0");671        matchVar("res3", "value is 2.0");672        matchVar("res4", "value is 2.0");673    }674    @Test675    void testTableWithInvalidVariableName() {676        fail = true;677        run(678                "table table1 =",679                "| col |",680                "| foo |"681        );682    }683    @Test684    void testReplace() {685        run(686                "def text = 'words that need to be {replaced}'",687                "replace text.{replaced} = 'correct'",688                "match text == 'words that need to be correct'",689                "match text.toString() == 'words that need to be correct'"690        );691        matchVar("text", "words that need to be correct");692    }693    @Test694    void testDistinct() {695        run(696                "def list1 = ['abc', 'def', 'abc', 'def', 'ghi']",697                "def res1 = karate.distinct(list1)",698                "match res1 == ['abc', 'def', 'ghi']",699                "def list2 = [1, 2, 1, 2, 3]",700                "def res2 = karate.distinct(list2)",701                "match res2 == [1, 2, 3]"702        );703    }704    @Test705    void testSort() {706        run(707                "def list1 = [{ num: 3 }, { num: 1 }, { num: 2 }]",708                "def fun1 = x => x.num",709                "def res1 = karate.sort(list1, fun1)",710                "match res1 == [{ num: 1 }, { num: 2 }, { num: 3 }]",711                "def list2 = [{ val: 'C' }, { val: 'A' }, { val: 'B' }]",712                "def res2 = karate.sort(list2, x => x.val)",713                "match res2 == [{ val: 'A' }, { val: 'B' }, { val: 'C' }]",714                "def list3 = ['c', 'b', 'a']",715                "def res3 = karate.sort(list3)",716                "match res3 == ['a', 'b', 'c']",717                "match res3.reverse() == ['c', 'b', 'a']"718        );719    }720    @Test721    void testRange() {722        run(723                "def list1 = karate.range(5, 10)",724                "match list1 == [5, 6, 7, 8, 9, 10]",725                "def list2 = karate.range(5, 10, 2)",726                "match list2 == [5, 7, 9]",727                "def list3 = karate.range(10, 5, 2)",728                "match list3 == [10, 8, 6]"729        );730        fail = true;731        run(732                "def list = karate.range(10, 5, 0)"733        );734        run(735                "def list = karate.range(10, 5, -1)"736        );737    }738    @Test739    void testUrlEncodeAndDecode() {740        run(741                "def raw = 'encoding%2Ffoo%2Bbar'",742                "def decoded = karate.urlDecode(raw)",743                "match decoded == 'encoding/foo+bar'",744                "def encoded = karate.urlEncode(decoded)",745                "match encoded == raw"746        );747    }748    @Test749    void testMatchXmlXpath() {750        fail = true;751        run(752                "xml myXml = <root><foo>bar</foo><hello><text>hello \"world\"</text></hello><hello><text>hello \"moon\"</text></hello></root>",753                "match myXml //myXml2/root/text == '#notnull'"754        );755    }756    @Test757    void testcontinueOnStepFailure() {758        fail = true;759        run(760                "def var = 'foo'",761                "configure continueOnStepFailure = true",762                "match var == 'bar'",763                "match var == 'pub'",764                "match var == 'crawl'",765                "match var == 'foo'",766                "configure continueOnStepFailure = false",767                "match var == 'foo'",768                "match var == 'bar2'",769                "match var == 'foo'"770        );771        // the last failed step will be show as the result failed step772        // TODO: verify how this will look in the reports773        assertEquals("match var == 'crawl'", sr.result.getFailedStep().getStep().getText());774    }775    @Test776    void testcontinueOnStepFailure2() {777        fail = true;778        run(779                "def var = 'foo'",780                "configure continueOnStepFailure = { enabled: true, continueAfter: true }",781                "match var == 'bar'",782                "match var == 'pub'",783                "match var == 'crawl'",784                "match var == 'foo'",785                "configure continueOnStepFailure = false",786                "match var == 'foo'",787                "match var == 'bar2'",788                "match var == 'foo'"789        );790        assertEquals("match var == 'bar2'", sr.result.getFailedStep().getStep().getText());791    }792    @Test793    void testcontinueOnStepFailure3() {794        fail = true;795        // bad idea to continue/ignore anything else other than match but ...796        run(797                "def var = 'foo'",798                "configure continueOnStepFailure = { enabled: true, continueAfter: true, keywords: ['match', 'def'] }",799                "match var == 'bar'",800                "def var2 = function() { syntax error in here };",801                "match var == 'pub'",802                "match var == 'crawl'",803                "match var == 'foo'",804                "configure continueOnStepFailure = { enabled: false }",805                "match var == 'foo'",806                "match var == 'bar2'",807                "match var == 'foo'"808        );809        assertEquals("match var == 'bar2'", sr.result.getFailedStep().getStep().getText());810    }811    @Test812    void testcontinueOnStepFailure4() {813        fail = true;814        run(815                "def var = 'foo'",816                "configure continueOnStepFailure = true",817                "match var == 'bar'",818                "match var == 'pub'",819                "match var == 'crawl'",820                "match var == 'foo'",821                "configure continueOnStepFailure = false",822                "match var == 'foo'"823        );824        assertEquals("match var == 'crawl'", sr.result.getFailedStep().getStep().getText());825    }826    @Test827    void testcontinueOnStepFailure5() {828        fail = true;829        run(830                "def var = 'foo'",831                "configure continueOnStepFailure = { enabled: true, continueAfter: true }",832                "match var == 'bar'",833                "match var == 'pub'",834                "match var == 'crawl'",835                "match var == 'foo'",836                "configure continueOnStepFailure = false",837                "match var == 'foo'",838                "match var == 'foo'",839                "match var == 'bar'",840                "match var == 'skipped'"841        );842        // scenario will still be marked as failed (reduces non-deterministic tests and using keyword as if condition)843        // the first failed step will be the one reported as failure844        // but next steps after configure 'continueOnStepFailure = false' will continue to execute845        assertEquals("match var == 'bar'", sr.result.getFailedStep().getStep().getText());846        assertEquals("[passed] * configure continueOnStepFailure = false", sr.result.getStepResults().get(6).toString());847        assertEquals("[passed] * match var == 'foo'", sr.result.getStepResults().get(7).toString());848        assertEquals("[passed] * match var == 'foo'", sr.result.getStepResults().get(8).toString());849        assertEquals("[failed] * match var == 'bar'", sr.result.getStepResults().get(9).toString());850        assertEquals("[skipped] * match var == 'skipped'", sr.result.getStepResults().get(10).toString());851    }852    @Test853    void testcontinueOnStepFailure6() {854        fail = true;855        // "continuing" on javascript line errors is not supported856        // note the if without space after evalutes line as JS857        run(858                "def var = 'foo'",859                "configure continueOnStepFailure = { enabled: true, continueAfter: true, keywords: ['match', 'eval', 'if'] }",860                "match var == 'bar'",861                "if(true == true) { syntax error within JS line }",862                "match var == 'crawl'",863                "match var == 'foo'",864                "configure continueOnStepFailure = false",...Source:Step.java  
...189    public void setComments(List<String> comments) {190        this.comments = comments;191    }192    @Override193    public String toString() {194        String temp = prefix + " " + text;195        if (docString != null) {196            temp = temp + "\n\"\"\"\n" + docString + "\n\"\"\"";197        }198        if (table != null) {199            temp = temp + " " + table.toString();200        }201        return temp;202    }203}...toString
Using AI Code Generation
1import com.intuit.karate.core.Table;2import java.util.List;3import java.util.Map;4import java.util.ArrayList;5import java.util.HashMap;6public class 4 {7    public static void main(String[] args) {8        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();9        Map<String, Object> map = new HashMap<String, Object>();10        map.put("name", "John");11        map.put("age", 30);12        list.add(map);13        map = new HashMap<String, Object>();14        map.put("name", "Mary");15        map.put("age", 28);16        list.add(map);17        Table table = new Table(list);18        System.out.println(table);19    }20}21Related posts: Java String indexOf() and lastIndexOf() Methods Java String concat() Method Java String substring() Method Java String replace() Method Java String replaceFirst() Method Java String replaceAll() Method Java String toLowerCase() and toUpperCase() Methods Java String trim() Method Java String split() Method Java String matches() Method Java String join() Method Java String format() Method Java String strip() Method Java String stripLeading() Method Java String stripTrailing() Method Java String isBlank() Method Java String isEmpty() Method Java String codePoints() Method Java String chars() Method Java String lines() Method Java String hashCode() Method Java String equals() Method Java String compareTo() Method Java String compareToIgnoreCase() Method Java String equalsIgnoreCase() Method Java String regionMatches() Method Java String startsWith() and endsWith() Methods Java String contains() Method Java String contentEquals() Method Java String intern() Method Java String getBytes() Method Java String getChars() Method Java String toCharArray() Method Java String valueOf() Method Java String charAt() Method Java String length() Method Java String toString() Method Java String toUpperCase() Method Java String toLowerCase() Method Java String toUpperCase(Locale) Method Java String toLowerCase(Locale) Method Java String trim() Method Java String strip() Method Java String stripLeading() Method Java String stripTrailing() Method Java String format() Method Java String join() Method Java String replace() Method Java String replaceFirst() Method Java String replaceAll() Method Java String split() Method Java String matches() Method Java String lines() Method Java String chars() Method Java String codePoints() Method Java String isBlank() Method Java String isEmpty() Method Java String isBlanktoString
Using AI Code Generation
1import com.intuit.karate.core.Table;2public class 4 {3    public static void main(String[] args) {4        Table table = new Table("id", "name", "age");5        table.add(1, "John", 30);6        table.add(2, "Jack", 40);7        System.out.println(table.toString());8    }9}toString
Using AI Code Generation
1import com.intuit.karate.FileUtils;2import com.intuit.karate.core.Table;3import com.intuit.karate.core.Table.TableRow;4import java.util.List;5public class 4 {6    public static void main(String[] args) {7        String text = FileUtils.toString("src/test/resources/test2.feature");8        Table table = Table.read(text);9        List<TableRow> rows = table.getRows();10        for (TableRow row : rows) {11            System.out.println("row: " + row);12        }13    }14}15import com.intuit.karate.core.Table;16import com.intuit.karate.core.Table.TableRow;17import java.util.Arrays;18import java.util.List;19public class 5 {20    public static void main(String[] args) {21        Table table = new Table();22        table.addHeaders(Arrays.asList("a", "b", "c"));23        table.addRow(Arrays.asList("1", "2", "3"));24        table.addRow(Arrays.asList("4", "5", "6"));25        table.addRow(Arrays.asList("7", "8", "9"));26        System.out.println(table.toString());27    }28}toString
Using AI Code Generation
1import com.intuit.karate.core.Table;2import java.util.List;3import java.util.Map;4import java.util.ArrayList;5import java.util.HashMap;6import java.util.Arrays;7import java.util.Iterator;8public class 4 {9    public static void main(String[] args) {10        List<Map<String, Object>> list = new ArrayList();11        Map<String, Object> map = new HashMap();12        map.put("name", "John");13        map.put("age", 30);14        list.add(map);15        map = new HashMap();16        map.put("name", "Mary");17        map.put("age", 25);18        list.add(map);19        Table table = new Table(list);20        System.out.println(table);21    }22}23import com.intuit.karate.core.Table;24import java.util.List;25import java.util.Map;26import java.util.ArrayList;27import java.util.HashMap;28import java.util.Arrays;29import java.util.Iterator;30public class 5 {31    public static void main(String[] args) {32        List<Map<String, Object>> list = new ArrayList();33        Map<String, Object> map = new HashMap();34        map.put("name", "John");35        map.put("age", 30);36        map.put("salary", 1000.0);37        list.add(map);38        map = new HashMap();39        map.put("name", "Mary");40        map.put("age", 25);41        map.put("salary", 2000.0);42        list.add(map);43        Table table = new Table(list);44        System.out.println(table);45    }46}47import com.intuit.karate.core.Table;48import java.util.List;49import java.util.Map;50import java.util.ArrayList;51import java.util.HashMap;52import java.util.Arrays;53import java.util.Iterator;54public class 6 {55    public static void main(String[] args) {56        List<Map<String, Object>> list = new ArrayList();57        Map<String, Object> map = new HashMap();58        map.put("name", "John");toString
Using AI Code Generation
1import com.intuit.karate.core.Table;2import com.intuit.karate.core.Table.Column;3import com.intuit.karate.core.Table.Row;4import java.util.ArrayList;5import java.util.List;6public class 4 {7    public static void main(String[] args) {8        Table table = new Table();9        List<Column> columns = new ArrayList<Column>();10        columns.add(new Column("Name"));11        columns.add(new Column("Age"));12        table.setColumns(columns);13        List<Row> rows = new ArrayList<Row>();14        rows.add(new Row(new Object[] { "John", 20 }));15        rows.add(new Row(new Object[] { "Mary", 25 }));16        table.setRows(rows);17        System.out.println(table);18    }19}20import com.intuit.karate.core.Table;21import com.intuit.karate.core.Table.Column;22import com.intuit.karate.core.Table.Row;23import java.util.ArrayList;24import java.util.List;25public class 5 {26    public static void main(String[] args) {27        Table table = new Table();28        List<Column> columns = new ArrayList<Column>();29        Column column1 = new Column("Name");30        column1.setAlign("right");31        columns.add(column1);32        Column column2 = new Column("Age");33        column2.setAlign("right");34        columns.add(column2);35        table.setColumns(columns);36        List<Row> rows = new ArrayList<Row>();37        rows.add(new Row(new Object[] { "John", 20 }));38        rows.add(new Row(new Object[] { "Mary", 25 }));39        table.setRows(rows);40        System.out.println(table);41    }42}toString
Using AI Code Generation
1import com.intuit.karate.core.Table;2import java.util.List;3import java.util.Map;4public class TableToString {5    public static void main(String[] args) {6        Table table = new Table();7        table.addCell("a");8        table.addCell("b");9        table.addCell("c");10        table.addCell("d");11        table.addCell("e");12        table.addCell("f");13        table.addCell("g");14        table.addCell("h");15        table.addCell("i");16        table.addCell("j");17        table.addCell("k");18        table.addCell("l");19        table.addCell("m");20        table.addCell("n");21        table.addCell("o");22        table.addCell("p");23        table.addCell("q");24        table.addCell("r");25        table.addCell("s");26        table.addCell("t");27        table.addCell("u");28        table.addCell("v");29        table.addCell("w");30        table.addCell("x");31        table.addCell("y");32        table.addCell("z");33        System.out.println(table.toString());34    }35}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!!
