How to use match_BackgroundLine method in Cucumber-gherkin

Best JavaScript code snippet using cucumber-gherkin

Run Cucumber-gherkin automation tests on LambdaTest cloud grid

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

token_matcher.js

Source: token_matcher.js Github

copy
1var DIALECTS = require('./dialects');
2var Errors = require('./errors');
3var LANGUAGE_PATTERN = /^\s*#\s*language\s*:\s*([a-zA-Z\-_]+)\s*$/;
4
5module.exports = function TokenMatcher(defaultDialectName) {
6  defaultDialectName = defaultDialectName || 'en';
7
8  var dialect;
9  var dialectName;
10  var activeDocStringSeparator;
11  var indentToRemove;
12
13  function changeDialect(newDialectName, location) {
14    var newDialect = DIALECTS[newDialectName];
15    if(!newDialect) {
16      throw Errors.NoSuchLanguageException.create(newDialectName, location);
17    }
18
19    dialectName = newDialectName;
20    dialect = newDialect;
21  }
22
23  this.reset = function () {
24    if(dialectName != defaultDialectName) changeDialect(defaultDialectName);
25    activeDocStringSeparator = null;
26    indentToRemove = 0;
27  };
28
29  this.reset();
30
31  this.match_TagLine = function match_TagLine(token) {
32    if(token.line.startsWith('@')) {
33      setTokenMatched(token, 'TagLine', null, null, null, token.line.getTags());
34      return true;
35    }
36    return false;
37  };
38
39  this.match_FeatureLine = function match_FeatureLine(token) {
40    return matchTitleLine(token, 'FeatureLine', dialect.feature);
41  };
42
43  this.match_ScenarioLine = function match_ScenarioLine(token) {
44    return matchTitleLine(token, 'ScenarioLine', dialect.scenario);
45  };
46
47  this.match_ScenarioOutlineLine = function match_ScenarioOutlineLine(token) {
48    return matchTitleLine(token, 'ScenarioOutlineLine', dialect.scenarioOutline);
49  };
50
51  this.match_BackgroundLine = function match_BackgroundLine(token) {
52    return matchTitleLine(token, 'BackgroundLine', dialect.background);
53  };
54
55  this.match_ExamplesLine = function match_ExamplesLine(token) {
56    return matchTitleLine(token, 'ExamplesLine', dialect.examples);
57  };
58
59  this.match_TableRow = function match_TableRow(token) {
60    if (token.line.startsWith('|')) {
61      // TODO: indent
62      setTokenMatched(token, 'TableRow', null, null, null, token.line.getTableCells());
63      return true;
64    }
65    return false;
66  };
67
68  this.match_Empty = function match_Empty(token) {
69    if (token.line.isEmpty) {
70      setTokenMatched(token, 'Empty', null, null, 0);
71      return true;
72    }
73    return false;
74  };
75
76  this.match_Comment = function match_Comment(token) {
77    if(token.line.startsWith('#')) {
78      var text = token.line.getLineText(0); //take the entire line, including leading space
79      setTokenMatched(token, 'Comment', text, null, 0);
80      return true;
81    }
82    return false;
83  };
84
85  this.match_Language = function match_Language(token) {
86    var match;
87    if(match = token.line.trimmedLineText.match(LANGUAGE_PATTERN)) {
88      var newDialectName = match[1];
89      setTokenMatched(token, 'Language', newDialectName);
90
91      changeDialect(newDialectName, token.location);
92      return true;
93    }
94    return false;
95  };
96
97  this.match_DocStringSeparator = function match_DocStringSeparator(token) {
98    return activeDocStringSeparator == null
99      ?
100      // open
101      _match_DocStringSeparator(token, '"""', true) ||
102      _match_DocStringSeparator(token, '```', true)
103      :
104      // close
105      _match_DocStringSeparator(token, activeDocStringSeparator, false);
106  };
107
108  function _match_DocStringSeparator(token, separator, isOpen) {
109    if (token.line.startsWith(separator)) {
110      var contentType = null;
111      if (isOpen) {
112        contentType = token.line.getRestTrimmed(separator.length);
113        activeDocStringSeparator = separator;
114        indentToRemove = token.line.indent;
115      } else {
116        activeDocStringSeparator = null;
117        indentToRemove = 0;
118      }
119
120      // TODO: Use the separator as keyword. That's needed for pretty printing.
121      setTokenMatched(token, 'DocStringSeparator', contentType);
122      return true;
123    }
124    return false;
125  }
126
127  this.match_EOF = function match_EOF(token) {
128    if(token.isEof) {
129      setTokenMatched(token, 'EOF');
130      return true;
131    }
132    return false;
133  };
134
135  this.match_StepLine = function match_StepLine(token) {
136    var keywords = []
137      .concat(dialect.given)
138      .concat(dialect.when)
139      .concat(dialect.then)
140      .concat(dialect.and)
141      .concat(dialect.but);
142    var length = keywords.length;
143    for(var i = 0, keyword; i < length; i++) {
144      var keyword = keywords[i];
145
146      if (token.line.startsWith(keyword)) {
147        var title = token.line.getRestTrimmed(keyword.length);
148        setTokenMatched(token, 'StepLine', title, keyword);
149        return true;
150      }
151    }
152    return false;
153  };
154
155  this.match_Other = function match_Other(token) {
156    var text = token.line.getLineText(indentToRemove); //take the entire line, except removing DocString indents
157    setTokenMatched(token, 'Other', unescapeDocString(text), null, 0);
158    return true;
159  };
160
161  function matchTitleLine(token, tokenType, keywords) {
162    var length = keywords.length;
163    for(var i = 0, keyword; i < length; i++) {
164      var keyword = keywords[i];
165
166      if (token.line.startsWithTitleKeyword(keyword)) {
167        var title = token.line.getRestTrimmed(keyword.length + ':'.length);
168        setTokenMatched(token, tokenType, title, keyword);
169        return true;
170      }
171    }
172    return false;
173  }
174
175  function setTokenMatched(token, matchedType, text, keyword, indent, items) {
176    token.matchedType = matchedType;
177    token.matchedText = text;
178    token.matchedKeyword = keyword;
179    token.matchedIndent = (typeof indent === 'number') ? indent : (token.line == null ? 0 : token.line.indent);
180    token.matchedItems = items || [];
181
182    token.location.column = token.matchedIndent + 1;
183    token.matchedGherkinDialect = dialectName;
184  }
185
186  function unescapeDocString(text) {
187    return activeDocStringSeparator != null ? text.replace("\\\"\\\"\\\"", "\"\"\"") : text;
188  }
189};
190
Full Screen

token_matcher.py

Source: token_matcher.py Github

copy
1import re
2from .dialect import Dialect
3from .errors import NoSuchLanguageException
4
5
6class TokenMatcher(object):
7    LANGUAGE_RE = re.compile(r"^\s*#\s*language\s*:\s*([a-zA-Z\-_]+)\s*$")
8
9    def __init__(self, dialect_name='en'):
10        self._default_dialect_name = dialect_name
11        self._change_dialect(dialect_name)
12        self.reset()
13
14    def reset(self):
15        if self.dialect_name != self._default_dialect_name:
16            self._change_dialect(self._default_dialect_name)
17        self._indent_to_remove = 0
18        self._active_doc_string_separator = None
19
20    def match_FeatureLine(self, token):
21        return self._match_title_line(token, 'FeatureLine', self.dialect.feature_keywords)
22
23    def match_ScenarioLine(self, token):
24        return self._match_title_line(token, 'ScenarioLine', self.dialect.scenario_keywords)
25
26    def match_ScenarioOutlineLine(self, token):
27        return self._match_title_line(token, 'ScenarioOutlineLine',
28                                      self.dialect.scenario_outline_keywords)
29
30    def match_BackgroundLine(self, token):
31        return self._match_title_line(token, 'BackgroundLine', self.dialect.background_keywords)
32
33    def match_ExamplesLine(self, token):
34        return self._match_title_line(token, 'ExamplesLine', self.dialect.examples_keywords)
35
36    def match_TableRow(self, token):
37        if not token.line.startswith('|'):
38            return False
39        # TODO: indent
40        self._set_token_matched(token, 'TableRow', items=token.line.table_cells)
41        return True
42
43    def match_StepLine(self, token):
44        keywords = (self.dialect.given_keywords +
45                    self.dialect.when_keywords +
46                    self.dialect.then_keywords +
47                    self.dialect.and_keywords +
48                    self.dialect.but_keywords)
49        for keyword in (k for k in keywords if token.line.startswith(k)):
50            title = token.line.get_rest_trimmed(len(keyword))
51            self._set_token_matched(token, 'StepLine', title, keyword)
52            return True
53
54        return False
55
56    def match_Comment(self, token):
57        if not token.line.startswith('#'):
58            return False
59
60        text = token.line._line_text  # take the entire line, including leading space
61        self._set_token_matched(token, 'Comment', text, indent=0)
62        return True
63
64    def match_Empty(self, token):
65        if not token.line.is_empty():
66            return False
67
68        self._set_token_matched(token, 'Empty', indent=0)
69        return True
70
71    def match_Language(self, token):
72        match = self.LANGUAGE_RE.match(token.line.get_line_text())
73        if not match:
74            return False
75
76        dialect_name = match.group(1)
77        self._set_token_matched(token, 'Language', dialect_name)
78        self._change_dialect(dialect_name, token.location)
79        return True
80
81    def match_TagLine(self, token):
82        if not token.line.startswith('@'):
83            return False
84
85        self._set_token_matched(token, 'TagLine', items=token.line.tags)
86        return True
87
88    def match_DocStringSeparator(self, token):
89        if not self._active_doc_string_separator:
90            # open
91            return (self._match_DocStringSeparator(token, '"""', True) or
92                    self._match_DocStringSeparator(token, '```', True))
93        else:
94            # close
95            return self._match_DocStringSeparator(token, self._active_doc_string_separator, False)
96
97    def _match_DocStringSeparator(self, token, separator, is_open):
98        if not token.line.startswith(separator):
99            return False
100
101        content_type = None
102        if is_open:
103            content_type = token.line.get_rest_trimmed(len(separator))
104            self._active_doc_string_separator = separator
105            self._indent_to_remove = token.line.indent
106        else:
107            self._active_doc_string_separator = None
108            self._indent_to_remove = 0
109
110        # TODO: Use the separator as keyword. That's needed for pretty printing.
111        self._set_token_matched(token, 'DocStringSeparator', content_type)
112        return True
113
114    def match_Other(self, token):
115        # take the entire line, except removing DocString indents
116        text = token.line.get_line_text(self._indent_to_remove)
117        self._set_token_matched(token, 'Other', self._unescaped_docstring(text), indent=0)
118        return True
119
120    def match_EOF(self, token):
121        if not token.eof():
122            return False
123
124        self._set_token_matched(token, 'EOF')
125        return True
126
127    def _match_title_line(self, token, token_type, keywords):
128        for keyword in (k for k in keywords if token.line.startswith_title_keyword(k)):
129            title = token.line.get_rest_trimmed(len(keyword) + len(':'))
130            self._set_token_matched(token, token_type, title, keyword)
131            return True
132
133        return False
134
135    def _set_token_matched(self, token, matched_type, text=None,
136                           keyword=None, indent=None, items=None):
137        if items is None:
138            items = []
139        token.matched_type = matched_type
140        # text == '' should not result in None
141        token.matched_text = text.rstrip('\r\n') if text is not None else None
142        token.matched_keyword = keyword
143        if indent is not None:
144            token.matched_indent = indent
145        else:
146            token.matched_indent = token.line.indent if token.line else 0
147        token.matched_items = items
148        token.location['column'] = token.matched_indent + 1
149        token.matched_gherkin_dialect = self.dialect_name
150
151    def _change_dialect(self, dialect_name, location=None):
152        dialect = Dialect.for_name(dialect_name)
153        if not dialect:
154            raise NoSuchLanguageException(dialect_name, location)
155
156        self.dialect_name = dialect_name
157        self.dialect = dialect
158
159    def _unescaped_docstring(self, text):
160        return text.replace('\\"\\"\\"', '"""') if self._active_doc_string_separator else text
161
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cucumber-gherkin on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)