How to use isDollarPrefixedJsonPath method of com.intuit.karate.core.ScenarioEngine class

Best Karate code snippet using com.intuit.karate.core.ScenarioEngine.isDollarPrefixedJsonPath

Source:ScenarioEngine.java Github

copy

Full Screen

...1697 return StringUtils.pair(name, path);1698 }1699 public Match.Result match(Match.Type matchType, String expression, String path, String rhs) {1700 String name = StringUtils.trimToEmpty(expression);1701 if (isDollarPrefixedJsonPath(name) || isXmlPath(name)) { //1702 path = name;1703 name = RESPONSE;1704 }1705 if (name.startsWith("$")) { // in case someone used the dollar prefix by mistake on the LHS1706 name = name.substring(1);1707 }1708 path = StringUtils.trimToNull(path);1709 if (path == null) {1710 StringUtils.Pair pair = parseVariableAndPath(name);1711 name = pair.left;1712 path = pair.right;1713 }1714 if ("header".equals(name)) { // convenience shortcut for asserting against response header1715 return matchHeader(matchType, path, rhs);1716 }1717 Variable actual;1718 // karate started out by "defaulting" to JsonPath on the LHS of a match so we have this kludge1719 // but we now handle JS expressions of almost any shape on the LHS, if in doubt, wrap in parentheses1720 // actually it is not too bad - the XPath function check is the only odd one out1721 // rules:1722 // if not XPath function, wrapped in parentheses, involves function call1723 // [then] JS eval1724 // else if XPath, JsonPath, JsonPath wildcard ".." or "*" or "[?"1725 // [then] eval name, and do a JsonPath or XPath using the parsed path1726 if (isXmlPathFunction(path)1727 || (!name.startsWith("(") && !path.endsWith(")") && !path.contains(")."))1728 && (isDollarPrefixed(path) || isJsonPath(path) || isXmlPath(path))) {1729 actual = evalKarateExpression(name);1730 // edge case: java property getter, e.g. "driver.cookies"1731 if (!actual.isMap() && !actual.isList() && !isXmlPath(path) && !isXmlPathFunction(path)) {1732 actual = evalKarateExpression(expression); // fall back to JS eval of entire LHS1733 path = "$";1734 }1735 } else {1736 actual = evalKarateExpression(expression); // JS eval of entire LHS1737 path = "$";1738 }1739 if ("$".equals(path) || "/".equals(path)) {1740 // we have eval-ed the entire LHS, so proceed to match RHS to "$"1741 } else {1742 if (isDollarPrefixed(path)) { // json-path1743 actual = evalJsonPath(actual, path);1744 } else { // xpath1745 actual = evalXmlPath(actual, path);1746 }1747 }1748 Variable expected = evalKarateExpression(rhs);1749 return match(matchType, actual.getValue(), expected.getValue());1750 }1751 // TODO document that match header is case-insensitive at last1752 private Match.Result matchHeader(Match.Type matchType, String name, String exp) {1753 Variable expected = evalKarateExpression(exp);1754 String actual = response.getHeader(name);1755 return match(matchType, actual, expected.getValue());1756 }1757 public Match.Result match(Match.Type matchType, Object actual, Object expected) {1758 return Match.execute(JS, matchType, actual, expected);1759 }1760 private static final Pattern VAR_AND_PATH_PATTERN = Pattern.compile("\\w+");1761 private static final String VARIABLE_PATTERN_STRING = "[a-zA-Z][\\w]*";1762 private static final Pattern VARIABLE_PATTERN = Pattern.compile(VARIABLE_PATTERN_STRING);1763 private static final Pattern FUNCTION_PATTERN = Pattern.compile("^function[^(]*\\(");1764 private static final Pattern JS_PLACEHODER = Pattern.compile("\\$\\{.*?\\}");1765 public static boolean isJavaScriptFunction(String text) {1766 return FUNCTION_PATTERN.matcher(text).find();1767 }1768 public static boolean isValidVariableName(String name) {1769 return VARIABLE_PATTERN.matcher(name).matches();1770 }1771 public static boolean hasJavaScriptPlacehoder(String exp) {1772 return JS_PLACEHODER.matcher(exp).find();1773 }1774 public static final boolean isVariableAndSpaceAndPath(String text) {1775 return text.matches("^" + VARIABLE_PATTERN_STRING + "\\s+.+");1776 }1777 public static final boolean isVariable(String text) {1778 return VARIABLE_PATTERN.matcher(text).matches();1779 }1780 public static final boolean isWithinParentheses(String text) {1781 return text != null && text.startsWith("(") && text.endsWith(")");1782 }1783 public static final boolean isCallSyntax(String text) {1784 return text.startsWith("call ");1785 }1786 public static final boolean isCallOnceSyntax(String text) {1787 return text.startsWith("callonce ");1788 }1789 public static final boolean isGetSyntax(String text) {1790 return text.startsWith("get ") || text.startsWith("get[");1791 }1792 public static final boolean isJson(String text) {1793 return text.startsWith("{") || text.startsWith("[");1794 }1795 public static final boolean isXml(String text) {1796 return text.startsWith("<");1797 }1798 public static boolean isXmlPath(String text) {1799 return text.startsWith("/");1800 }1801 public static boolean isXmlPathFunction(String text) {1802 return text.matches("^[a-z-]+\\(.+");1803 }1804 public static final boolean isJsonPath(String text) {1805 return text.indexOf('*') != -1 || text.contains("..") || text.contains("[?");1806 }1807 public static final boolean isDollarPrefixed(String text) {1808 return text.startsWith("$");1809 }1810 public static final boolean isDollarPrefixedJsonPath(String text) {1811 return text.startsWith("$.") || text.startsWith("$[") || text.equals("$");1812 }1813 public static StringUtils.Pair parseCallArgs(String line) {1814 int pos = line.indexOf("read(");1815 if (pos != -1) {1816 pos = line.indexOf(')');1817 if (pos == -1) {1818 throw new RuntimeException("failed to parse call arguments: " + line);1819 }1820 return new StringUtils.Pair(line.substring(0, pos + 1), StringUtils.trimToNull(line.substring(pos + 1)));1821 }1822 pos = line.indexOf(' ');1823 if (pos == -1) {1824 return new StringUtils.Pair(line, null);1825 }1826 return new StringUtils.Pair(line.substring(0, pos), StringUtils.trimToNull(line.substring(pos)));1827 }1828 public Variable call(Variable called, Variable arg, boolean sharedScope) {1829 switch (called.type) {1830 case JS_FUNCTION:1831 case JAVA_FUNCTION:1832 return arg == null ? executeFunction(called) : executeFunction(called, new Object[] {arg.getValue()});1833 case FEATURE:1834 Variable res = callFeature(called.getValue(), arg, -1, sharedScope);1835 recurseAndAttach(res.getValue()); // will always be a map, we update entries within1836 return res;1837 default:1838 throw new RuntimeException("not a callable feature or js function: " + called);1839 }1840 }1841 public Variable call(boolean callOnce, String exp, boolean sharedScope) {1842 StringUtils.Pair pair = parseCallArgs(exp);1843 Variable called = evalKarateExpression(pair.left);1844 Variable arg = pair.right == null ? null : evalKarateExpression(pair.right);1845 Variable result;1846 if (callOnce) {1847 result = callOnce(exp, called, arg, sharedScope);1848 } else {1849 result = call(called, arg, sharedScope);1850 }1851 if (sharedScope && result.isMap()) {1852 setVariables(result.getValue());1853 }1854 return result;1855 }1856 private Variable result(ScenarioCall.Result result, boolean sharedScope) {1857 if (sharedScope) { // if shared scope1858 vars.clear(); // clean slate1859 vars.putAll(copy(result.vars, false)); // clone for safety1860 init(); // this will also insert magic variables1861 setConfig(new Config(result.config)); // re-apply config from time of snapshot1862 return Variable.NULL; // since we already reset the vars above we return null1863 // else the call() routine would try to do it again1864 // note that shared scope means a return value is meaningless1865 } else {1866 return result.value.copy(false); // clone result for safety1867 }1868 }1869 private Variable callOnce(String cacheKey, Variable called, Variable arg, boolean sharedScope) {1870 // IMPORTANT: the call result is always shallow-cloned before returning1871 // so that call result (especially if a java Map) is not mutated by other scenarios1872 final Map<String, ScenarioCall.Result> CACHE = runtime.featureRuntime.FEATURE_CACHE;1873 ScenarioCall.Result result = CACHE.get(cacheKey);1874 if (result != null) {1875 logger.trace("callonce cache hit for: {}", cacheKey);1876 return result(result, sharedScope);1877 }1878 long startTime = System.currentTimeMillis();1879 logger.trace("callonce waiting for lock: {}", cacheKey);1880 synchronized (CACHE) {1881 result = CACHE.get(cacheKey); // retry1882 if (result != null) {1883 long endTime = System.currentTimeMillis() - startTime;1884 logger.warn("this thread waited {} milliseconds for callonce lock: {}", endTime, cacheKey);1885 return result(result, sharedScope);1886 }1887 // this thread is the 'winner'1888 logger.info(">> lock acquired, begin callonce: {}", cacheKey);1889 Variable resultValue = call(called, arg, sharedScope);1890 // we clone result (and config) here, to snapshot state at the point the callonce was invoked1891 // this prevents the state from being clobbered by the subsequent steps of this1892 // first scenario that is about to use the result1893 Map<String, Variable> clonedVars = called.isFeature() && sharedScope ? detachVariables() : null;1894 Config clonedConfig = new Config(config);1895 clonedConfig.detach();1896 result = new ScenarioCall.Result(resultValue.copy(false), clonedConfig, clonedVars);1897 CACHE.put(cacheKey, result);1898 logger.info("<< lock released, cached callonce: {}", cacheKey);1899 return resultValue; // another routine will apply globally if needed1900 }1901 }1902 public Variable callFeature(Feature feature, Variable arg, int index, boolean sharedScope) {1903 if (arg == null || arg.isMap()) {1904 ScenarioCall call = new ScenarioCall(runtime, feature, arg);1905 call.setLoopIndex(index);1906 call.setSharedScope(sharedScope);1907 FeatureRuntime fr = new FeatureRuntime(call);1908 fr.run();1909 // VERY IMPORTANT ! switch back from called feature js context1910 THREAD_LOCAL.set(this);1911 FeatureResult result = fr.result;1912 runtime.addCallResult(result);1913 if (result.isFailed()) {1914 KarateException ke = result.getErrorMessagesCombined();1915 throw ke;1916 } else {1917 return new Variable(result.getVariables());1918 }1919 } else if (arg.isList() || arg.isJsOrJavaFunction()) {1920 List result = new ArrayList();1921 List<String> errors = new ArrayList();1922 int loopIndex = 0;1923 boolean isList = arg.isList();1924 Iterator iterator = isList ? arg.<List> getValue().iterator() : null;1925 while (true) {1926 Variable loopArg;1927 if (isList) {1928 loopArg = iterator.hasNext() ? new Variable(iterator.next()) : Variable.NULL;1929 } else { // function1930 loopArg = executeFunction(arg, new Object[] {loopIndex});1931 }1932 if (!loopArg.isMap()) {1933 if (!isList) {1934 logger.info("feature call loop function ended at index {}, returned: {}", loopIndex, loopArg);1935 }1936 break;1937 }1938 try {1939 Variable loopResult = callFeature(feature, loopArg, loopIndex, sharedScope);1940 result.add(loopResult.getValue());1941 } catch (Exception e) {1942 String message = "feature call loop failed at index: " + loopIndex + ", " + e.getMessage();1943 errors.add(message);1944 runtime.logError(message);1945 if (!isList) { // this is a generator function, abort infinite loop !1946 break;1947 }1948 }1949 loopIndex++;1950 }1951 if (errors.isEmpty()) {1952 return new Variable(result);1953 } else {1954 String errorMessage = StringUtils.join(errors, '\n');1955 throw new KarateException(errorMessage);1956 }1957 } else {1958 throw new RuntimeException("feature call argument is not a json object or array: " + arg);1959 }1960 }1961 public Variable evalJsonPath(Variable v, String path) {1962 Json json = Json.of(v.getValueAndForceParsingAsJson());1963 try {1964 return new Variable(json.get(path));1965 } catch (PathNotFoundException e) {1966 return Variable.NOT_PRESENT;1967 }1968 }1969 public static Variable evalXmlPath(Variable xml, String path) {1970 NodeList nodeList;1971 Node doc = xml.getAsXml();1972 try {1973 nodeList = XmlUtils.getNodeListByPath(doc, path);1974 } catch (Exception e) {1975 // hack, this happens for xpath functions that don't return nodes (e.g. count)1976 String strValue = XmlUtils.getTextValueByPath(doc, path);1977 Variable v = new Variable(strValue);1978 if (path.startsWith("count")) { // special case1979 return new Variable(v.getAsInt());1980 } else {1981 return v;1982 }1983 }1984 int count = nodeList.getLength();1985 if (count == 0) { // xpath / node does not exist !1986 return Variable.NOT_PRESENT;1987 }1988 if (count == 1) {1989 return nodeToValue(nodeList.item(0));1990 }1991 List list = new ArrayList();1992 for (int i = 0; i < count; i++) {1993 Variable v = nodeToValue(nodeList.item(i));1994 list.add(v.getValue());1995 }1996 return new Variable(list);1997 }1998 private static Variable nodeToValue(Node node) {1999 int childElementCount = XmlUtils.getChildElementCount(node);2000 if (childElementCount == 0) {2001 // hack assuming this is the most common "intent"2002 return new Variable(node.getTextContent());2003 }2004 if (node.getNodeType() == Node.DOCUMENT_NODE) {2005 return new Variable(node);2006 } else { // make sure we create a fresh doc else future xpath would run against original root2007 return new Variable(XmlUtils.toNewDocument(node));2008 }2009 }2010 public Variable evalJsonPathOnVariableByName(String name, String path) {2011 return evalJsonPath(vars.get(name), path);2012 }2013 public Variable evalXmlPathOnVariableByName(String name, String path) {2014 return evalXmlPath(vars.get(name), path);2015 }2016 public Variable evalKarateExpression(String text) {2017 text = StringUtils.trimToNull(text);2018 if (text == null) {2019 return Variable.NULL;2020 }2021 // don't re-evaluate if this is clearly a direct reference to a variable2022 // this avoids un-necessary conversion of xml into a map in some cases2023 // e.g. 'Given request foo' - where foo is a Variable of type XML2024 if (vars.containsKey(text)) {2025 return vars.get(text);2026 }2027 boolean callOnce = isCallOnceSyntax(text);2028 if (callOnce || isCallSyntax(text)) { // special case in form "callBegin foo arg"2029 if (callOnce) {2030 text = text.substring(9);2031 } else {2032 text = text.substring(5);2033 }2034 return call(callOnce, text, false);2035 } else if (isDollarPrefixedJsonPath(text)) {2036 return evalJsonPathOnVariableByName(RESPONSE, text);2037 } else if (isGetSyntax(text) || isDollarPrefixed(text)) { // special case in form2038 // get json[*].path2039 // $json[*].path2040 // get /xml/path2041 // get xpath-function(expression)2042 int index = -1;2043 if (text.startsWith("$")) {2044 text = text.substring(1);2045 } else if (text.startsWith("get[")) {2046 int pos = text.indexOf(']');2047 index = Integer.valueOf(text.substring(4, pos));2048 text = text.substring(pos + 2);2049 } else {2050 text = text.substring(4);2051 }2052 String left;2053 String right;2054 if (isDollarPrefixedJsonPath(text)) { // edge case get[0] $..foo2055 left = RESPONSE;2056 right = text;2057 } else if (isVariableAndSpaceAndPath(text)) {2058 int pos = text.indexOf(' ');2059 right = text.substring(pos + 1);2060 left = text.substring(0, pos);2061 } else {2062 StringUtils.Pair pair = parseVariableAndPath(text);2063 left = pair.left;2064 right = pair.right;2065 }2066 Variable sv;2067 if (isXmlPath(right) || isXmlPathFunction(right)) {2068 sv = evalXmlPathOnVariableByName(left, right);...

Full Screen

Full Screen

isDollarPrefixedJsonPath

Using AI Code Generation

copy

Full Screen

1* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)2* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)3* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)4* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)5* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)6* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)7* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)8* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)9* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)10* def isDollarPrefixed = engine.isDollarPrefixedJsonPath(jsonPath)

Full Screen

Full Screen

isDollarPrefixedJsonPath

Using AI Code Generation

copy

Full Screen

1import com.intuit.karate.core.ScenarioEngine2* def json = read('some.json')3import com.intuit.karate.core.ScenarioEngine4* def json = read('some.json')5import com.intuit.karate.core.ScenarioEngine6* def json = read('some.json')7import com.intuit.karate.core.ScenarioEngine8* def json = read('some.json')9import com.intuit.karate.core.ScenarioEngine10* def json = read('some.json')11import com.intuit.karate.core.ScenarioEngine12* def json = read('some

Full Screen

Full Screen

isDollarPrefixedJsonPath

Using AI Code Generation

copy

Full Screen

1* def result = engine.isDollarPrefixedJsonPath('$[1]')2* def result = engine.isDollarPrefixedJsonPath('$[1]')3* def result = engine.isDollarPrefixedJsonPath('$[1]')4* def result = engine.isDollarPrefixedJsonPath('$[1]')5* def result = engine.isDollarPrefixedJsonPath('$[1]')6* def result = engine.isDollarPrefixedJsonPath('$[1]')7* def result = engine.isDollarPrefixedJsonPath('$[1]')

Full Screen

Full Screen

isDollarPrefixedJsonPath

Using AI Code Generation

copy

Full Screen

1* assert isDollarPrefixedJsonPath('$..name') == '$..name'2* assert isDollarPrefixedJsonPath('$.name') == '$.name'3* assert isDollarPrefixedJsonPath('..name') == '$..name'4* assert isDollarPrefixedJsonPath('.name') == '$.name'5* assert isDollarPrefixedJsonPath('$..name') == '$..name'6* assert isDollarPrefixedJsonPath('$.name') == '$.name'7* assert isDollarPrefixedJsonPath('..name') == '$..name'8* assert isDollarPrefixedJsonPath('.name') == '$.name'9* assert isDollarPrefixedJsonPath('$..name') == '$..name'10* assert isDollarPrefixedJsonPath('$.name') == '$.name'11* assert isDollarPrefixedJsonPath('..name') == '$..name'12* assert isDollarPrefixedJsonPath('.name') == '$.name'13* assert isDollarPrefixedJsonPath('$..name') == '$..name'14* assert isDollarPrefixedJsonPath('$.name') == '$.name'15* assert isDollarPrefixedJsonPath('..name') == '$..name'16* assert isDollarPrefixedJsonPath('.name') == '$.name'17* assert isDollarPrefixedJsonPath('$..name') == '$..name'18* assert isDollarPrefixedJsonPath('$.name') == '$.name'19* assert isDollarPrefixedJsonPath('..name') == '$..name'20* assert isDollarPrefixedJsonPath('.name') == '$.name'21* assert isDollarPrefixedJsonPath('$..name') == '$..name'22* assert isDollarPrefixedJsonPath('$.name') == '$.name'23* assert isDollarPrefixedJsonPath('..name') == '$..name'24* assert isDollarPrefixedJsonPath('.name') == '$.name'

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Karate automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in ScenarioEngine

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful