How to use GherkinLine method of Gherkin.GherkinLine class

Best Gherkin-dotnet code snippet using Gherkin.GherkinLine.GherkinLine

Run Gherkin-dotnet automation tests on LambdaTest cloud grid

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

Lexer.cs

Source: Lexer.cs Github

copy
1using System;
2using System.Text.RegularExpressions;
3
4namespace GherkinSharp
5{
6    public class Lexer
7    {
8        private readonly ITokenReceiver _tokenReceiver;
9
10        public interface ITokenReceiver
11        {
12            void EndOfFile();
13            void Given(string text);
14            void When(string text);
15            void Then(string text);
16        }
17
18        public Lexer(ITokenReceiver tokenReceiver)
19        {
20            _tokenReceiver = tokenReceiver;
21        }
22
23        public void Lex(string gherkin)
24        {
25            foreach (var gherkinLine in GetGherkinLines(gherkin))
26            {
27                MatchAndCallback("^Given (.*)", _tokenReceiver.Given, gherkinLine);
28                MatchAndCallback("^When (.*)", _tokenReceiver.When, gherkinLine);
29                MatchAndCallback("^Then (.*)", _tokenReceiver.Then, gherkinLine);
30            }
31
32            _tokenReceiver.EndOfFile();
33        }
34
35        private static void MatchAndCallback(string pattern, Action<string> callback, string gherkinLine)
36        {
37            var m = Regex.Match(gherkinLine, pattern);
38            
39            while (m.Success)
40            {
41                var theText = m.Groups[1].Value;
42                callback(theText);
43                
44                m = m.NextMatch();
45            }
46        }
47
48        private static string[] GetGherkinLines(string gherkin)
49        {
50            return gherkin.Split(new[] { "\n", "\r\n" }, StringSplitOptions.None);
51        }
52    }
53}
Full Screen

GherkinParser.cs

Source: GherkinParser.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using System.Text.RegularExpressions;
6using Gherkin;
7using Gherkin.Ast;
8
9namespace SevenFt10.SpecFlow.Gherkin.Ast
10{
11    public class GherkinParser : Parser
12    {
13        public GherkinParser() : base() { }
14
15        public new GherkinDocument Parse(TextReader reader)
16        {
17            return ReparseDocument(base.Parse(reader));
18        }
19
20        public new GherkinDocument Parse(string sourceFile)
21        {
22            using (var fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
23            using (var textReader = new StreamReader(fileStream))
24            {
25                return ReparseDocument(base.Parse(textReader));
26            }
27        }
28
29        private GherkinDialect GetDialect(GherkinDocument doc)
30        {
31            var provider = new GherkinDialectProvider(doc.Feature.Language);
32            return provider.GetDialect(doc.Feature.Language, doc.Feature.Location);
33        }
34
35        private Step[] UpdateStepsX(IHasSteps parent, global::Gherkin.GherkinDialect dialect)
36        {
37            var steps = new List<Step>();
38            StepX previous = new StepX(dialect.GivenStepKeywords.Where(g => g.Trim() != "*").First());
39            foreach (var step in parent.Steps)
40            {
41                var name = previous.Name ?? dialect.GivenStepKeywords.Where(g => g.Trim() != "*").First();
42                if (dialect.WhenStepKeywords.Contains(step.Keyword) || dialect.ThenStepKeywords.Contains(step.Keyword))
43                {
44                    name = step.Keyword;
45                }
46                steps.Add(previous = new StepX(step, name));
47            }
48            return steps.ToArray();
49        }
50
51        private IHasChildren UpdateSteps(IHasChildren parent, GherkinDialect dialect)
52        {
53            var newChilds = new List<IHasLocation>();
54            foreach (var top in parent.Children)
55            {
56                if (top is IHasChildren)
57                {
58                    newChilds.Add(UpdateSteps((IHasChildren)top, dialect) as IHasLocation);
59                }
60                else if (top is IHasSteps)
61                {
62                    var newSteps = UpdateStepsX((IHasSteps)top, dialect);
63                    newChilds.Add(top.ReplaceSteps(newSteps));
64                }
65            }
66
67            if (parent is Rule)
68            {
69                newChilds = RuleElements(dialect, (Rule)parent).Union(newChilds).ToList();
70            }
71
72            return parent.ReplaceChildren(newChilds);
73        }
74
75        private GherkinDocument ReparseDocument(GherkinDocument doc)
76        {
77            return new GherkinDocument(UpdateSteps(doc.Feature, GetDialect(doc)) as Feature, doc.Comments.ToArray());
78        }
79
80        private static string CleanDescription(string desc)
81        {
82            while (desc.IndexOf("  ") > -1) desc = desc.Replace("  ", " ").Trim();
83            return desc.Replace("\r\n ", "\r\n").Trim();
84        }
85
86        private static IEnumerable<IHasLocation> RuleElements(GherkinDialect dialect, Rule rule)
87        {
88            var desc = CleanDescription(rule.Description);
89            var lineNumber = rule.Location.Line;
90
91            var hasOneRule = false;
92            foreach (var meta in dialect.MetaKeywords)
93            {
94                if (desc.StartsWith(meta.Trim()))
95                {
96                    lineNumber++;
97                    foreach (Match match in Regex.Matches(desc, @"\*{2}(.*?)\*{2}", RegexOptions.Singleline))
98                    {
99                        var comment = match.Groups[0].Value.Trim().TrimStart(new char[] { '*' }).TrimEnd(new char[] { '*' }).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
100                        foreach (var line in comment)
101                        {
102                            if (line.IndexOf(":") > -1)
103                            {
104                                yield return new RuleMeta(
105                                    new Location(++lineNumber, 0),
106                                    line.Substring(0, line.IndexOf(":")).Trim(),
107                                    line.Substring(line.IndexOf(":") + 1).Trim());
108                                hasOneRule = true;
109                            }
110                        }
111                        desc = CleanDescription(desc.Replace(match.Groups[0].Value, string.Empty));
112                    }
113                }
114            }
115            if (hasOneRule) lineNumber = lineNumber + 2;
116
117            var lines = desc.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
118            var current = 0;
119
120            var hasTopLevel = false;
121
122            IEnumerable<NarrativeMap> mapping;
123
124            mapping = dialect.WhyKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeWhy) });
125            foreach (var map in mapping)
126            {
127                if (current >= lines.Length) yield break;
128                var gherkinLine = new GherkinLine(lines[current], current);
129                if (gherkinLine.StartsWith(map.Key))
130                {
131                    yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length).Trim(), lineNumber + current);
132                    current++;
133                    hasTopLevel = true;
134                    break;
135                }
136            }
137
138            if (hasTopLevel)
139            {
140                hasTopLevel = false;
141                // process And , But
142                mapping = dialect.AndStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeAndWhy) })
143                    .Union(dialect.ButStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeButWhy) }));
144
145                var gotOne = false;
146                while (true)
147                {
148                    foreach (var map in mapping)
149                    {
150                        if (current >= lines.Length) yield break;
151                        var gherkinLine = new GherkinLine(lines[current], current);
152                        if (gherkinLine.StartsWith(map.Key))
153                        {
154                            yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
155                            current++;
156                            gotOne = true;
157                            break;
158                        }
159                    }
160                    if (!gotOne) break;
161                    gotOne = false;
162                }
163            }
164
165            mapping = dialect.WhoKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeWho) });
166            foreach (var map in mapping)
167            {
168                if (current >= lines.Length) yield break;
169                var gherkinLine = new GherkinLine(lines[current], current);
170                if (gherkinLine.StartsWith(map.Key))
171                {
172                    yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
173                    current++;
174                    hasTopLevel = true;
175                    break;
176                }
177            }
178
179            if (hasTopLevel)
180            {
181                hasTopLevel = false;
182
183                // process And , But
184                mapping = dialect.AndStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeAndWho) })
185                    .Union(dialect.ButStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeButWho) }));
186
187                var gotOne = false;
188                while (true)
189                {
190                    foreach (var map in mapping)
191                    {
192                        if (current >= lines.Length) yield break;
193                        var gherkinLine = new GherkinLine(lines[current], current);
194                        if (gherkinLine.StartsWith(map.Key))
195                        {
196                            yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
197                            current++;
198                            gotOne = true;
199                            break;
200                        }
201                    }
202                    if (!gotOne) break;
203                    gotOne = false;
204                }
205            }
206
207            mapping = dialect.WhereKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeWhere) });
208            foreach (var map in mapping)
209            {
210                if (current >= lines.Length) yield break;
211                var gherkinLine = new GherkinLine(lines[current], current);
212                if (gherkinLine.StartsWith(map.Key))
213                {
214                    yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
215                    current++;
216                    hasTopLevel = true;
217                    break;
218                }
219            }
220
221            if (hasTopLevel)
222            {
223                hasTopLevel = false;
224
225                // process And , But
226                mapping = dialect.AndStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeAndWhere) })
227                    .Union(dialect.ButStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeButWhere) }));
228
229                var gotOne = false;
230                while (true)
231                {
232                    foreach (var map in mapping)
233                    {
234                        if (current >= lines.Length) yield break;
235                        var gherkinLine = new GherkinLine(lines[current], current);
236                        if (gherkinLine.StartsWith(map.Key))
237                        {
238                            yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
239                            current++;
240                            gotOne = true;
241                            break;
242                        }
243                    }
244                    if (!gotOne) break;
245                    gotOne = false;
246                }
247            }
248
249            mapping = dialect.WhatKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeWhat) });
250            foreach (var map in mapping)
251            {
252                if (current >= lines.Length) yield break;
253                var gherkinLine = new GherkinLine(lines[current], current);
254                if (gherkinLine.StartsWith(map.Key))
255                {
256                    yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
257                    current++;
258                    hasTopLevel = true;
259                    break;
260                }
261            }
262
263            if (hasTopLevel)
264            {
265                hasTopLevel = false;
266
267                // process And , But
268                mapping = dialect.AndStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeAndWhat) })
269                    .Union(dialect.ButStepKeywords.Select(w => new NarrativeMap { Key = w, Type = typeof(NarrativeButWhat) }));
270
271                foreach (var map in mapping)
272                {
273                    if (current >= lines.Length) yield break;
274                    var gherkinLine = new GherkinLine(lines[current], current);
275                    if (gherkinLine.StartsWith(map.Key))
276                    {
277                        yield return CreateNarrative(map, gherkinLine.GetRestTrimmed(map.Key.Length), lineNumber + current);
278                        current++;
279                        break;
280                    }
281                }
282            }
283        }
284
285        private struct NarrativeMap
286        {
287            public string Key;
288            public Type Type;
289        }
290
291        private static INarrative CreateNarrative(NarrativeMap map, string description, int lineNumber)
292        {
293            var narrative = (INarrative)Activator.CreateInstance(map.Type, new object[] { });
294            narrative.Name = map.Key.TrimEnd();
295            narrative.Description = description;
296            narrative.Location = new Location(lineNumber, 0);
297            return narrative;
298        }
299    }
300}
Full Screen

GherkinLine.cs

Source: GherkinLine.cs Github

copy
1using System;
2using System.Text.RegularExpressions;
3using System.Collections.Generic;
4using System.Linq;
5using Gherkin.Ast;
6
7namespace Gherkin
8{
9    public class GherkinLine : IGherkinLine
10    {
11        private static char[] inlineWhitespaceChars = new char[] { ' ', '\t', '\u00A0'};
12
13        private readonly string lineText;
14        private readonly string trimmedLineText;
15        public int LineNumber { get; private set; }
16
17        public GherkinLine(string line, int lineNumber)
18        {
19            this.LineNumber = lineNumber;
20
21            this.lineText = line;
22            this.trimmedLineText = this.lineText.TrimStart();
23        }
24
25        public void Detach()
26        {
27            //nop
28        }
29
30        public int Indent
31        {
32            get { return lineText.Length - trimmedLineText.Length; }
33        }
34
35        public bool IsEmpty()
36        {
37            return trimmedLineText.Length == 0;
38        }
39
40        public bool StartsWith(string text)
41        {
42            return trimmedLineText.StartsWith(text);
43        }
44
45        public bool StartsWithTitleKeyword(string text)
46        {
47            return StringUtils.StartsWith(trimmedLineText, text) &&
48                StartsWithFrom(trimmedLineText, text.Length, GherkinLanguageConstants.TITLE_KEYWORD_SEPARATOR);
49        }
50
51        private static bool StartsWithFrom(string text, int textIndex, string value)
52        {
53            return string.CompareOrdinal(text, textIndex, value, 0, value.Length) == 0;
54        }
55
56        public string GetLineText(int indentToRemove)
57        {
58            if (indentToRemove < 0 || indentToRemove > Indent)
59                return trimmedLineText;
60
61            return lineText.Substring(indentToRemove);
62        }
63
64        public string GetRestTrimmed(int length)
65        {
66            return trimmedLineText.Substring(length).Trim();
67        }
68
69        public IEnumerable<GherkinLineSpan> GetTags()
70        {
71            var uncommentedLine = Regex.Split(trimmedLineText, @"\s" + GherkinLanguageConstants.COMMENT_PREFIX)[0];
72            int position = Indent;
73            foreach (string item in uncommentedLine.Split(GherkinLanguageConstants.TAG_PREFIX[0]))
74            {
75                if (item.Length > 0)
76                {
77                    var tagName = GherkinLanguageConstants.TAG_PREFIX + item.TrimEnd(inlineWhitespaceChars);
78                    if (tagName.Length == 1)
79                        continue;
80
81                    if (tagName.IndexOfAny(inlineWhitespaceChars) >= 0)
82                        throw new InvalidTagException("A tag may not contain whitespace", new Location(LineNumber, position));
83
84                    yield return new GherkinLineSpan(position, tagName);
85                    position += item.Length;
86                }
87                position++; // separator
88            }
89        }
90        
91        public IEnumerable<GherkinLineSpan> GetTableCells()
92        {
93            var items = SplitCells(trimmedLineText).ToList();
94            bool isBeforeFirst = true;
95            foreach (var item in items.Take(items.Count - 1)) // skipping the one after last
96            {
97                if (!isBeforeFirst)
98                {
99                    int trimmedStart;
100                    var cellText = Trim(item.Item1, out trimmedStart);
101                    var cellPosition = item.Item2 + trimmedStart;
102
103                    if (cellText.Length == 0)
104                        cellPosition = item.Item2;
105
106                    yield return new GherkinLineSpan(Indent + cellPosition + 1, cellText);
107                }
108
109                isBeforeFirst = false;
110            }
111        }
112
113        private IEnumerable<Tuple<string, int>> SplitCells(string row)
114        {
115            var rowEnum = row.GetEnumerator();            
116
117            string cell = "";
118            int pos = 0;
119            int startPos = 0;
120            while (rowEnum.MoveNext()) {
121                pos++;
122                char c = rowEnum.Current;
123                if (c.ToString() == GherkinLanguageConstants.TABLE_CELL_SEPARATOR) {
124                    yield return Tuple.Create(cell, startPos);
125                    cell = "";
126                    startPos = pos;
127                } else if (c == GherkinLanguageConstants.TABLE_CELL_ESCAPE_CHAR) {
128                    rowEnum.MoveNext();
129                    pos++;
130                    c = rowEnum.Current;
131                    if (c == GherkinLanguageConstants.TABLE_CELL_NEWLINE_ESCAPE) {
132                        cell += "\n";
133                    } else {
134                        if (c.ToString() != GherkinLanguageConstants.TABLE_CELL_SEPARATOR && c != GherkinLanguageConstants.TABLE_CELL_ESCAPE_CHAR) {
135                            cell += GherkinLanguageConstants.TABLE_CELL_ESCAPE_CHAR;
136                        }
137                        cell += c;
138                    }
139                } else {
140                    cell += c;
141                }
142            }
143            yield return Tuple.Create(cell, startPos);
144        }
145
146        private string Trim(string s, out int trimmedStart)
147        {
148            trimmedStart = 0;
149            while (trimmedStart < s.Length && inlineWhitespaceChars.Contains(s[trimmedStart]))
150                trimmedStart++;
151
152            return s.Trim(inlineWhitespaceChars);
153        }
154    }
155}
156
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

Trigger GherkinLine code on LambdaTest Cloud Grid

Execute automation tests with GherkinLine 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)