How to use given_keywords method in Gherkin-python

Best Python code snippet using gherkin-python

gherkin_template_processor.py

Source:gherkin_template_processor.py Github

copy

Full Screen

1import json2print("Make sure script is run using python3")3def generate_keyword_body(keywords):4 first_keyword = keywords[0].replace("'", "\\'")5 body = "\n\t("6 body += "'" + keywords[0].replace("'", "\\'") + "'"7 8 if len(body) > 1:9 for keyword in range(1,len(keywords)): 10 body += "\n\t\t| '{k}'".format(k=keywords[keyword].replace("'", "\\'"))11 body += "\n\t) "12 return body13 14language_data = json.load(open('languages/gherkin-languages.json'))15template = """lexer grammar GherkinLexer;16fragment LANGUAGE_KEYWORD : WS* '#' WS* 'language' WS* ':' WS*;17LANGUAGE_HEADER : LANGUAGE_KEYWORD 'en' LINE_END -> mode(DEFAULT_MODE) ;18"""19for language in language_data.keys():20 l = language_data[language]21 ul = language.upper().replace("-", "_")22 template += "\n" + ul + "_LANGUAGE_HEADER : LANGUAGE_KEYWORD '" + language + "' LINE_END -> mode(" + ul + "), type(LANGUAGE_HEADER) ;"23template += "\n//////////////////////////////////////////////////////////////////////////"24template += '''25FEATURE_KEYWORD : ('Feature'26 | 'Business Need'27 | 'Ability') ':' -> channel(HIDDEN) ;28SCENARIO_KEYWORD : ('Scenario' | 'Example') ':' -> channel(HIDDEN) ;29SCENARIO_OUTLINE_KEYWORD : 'Scenario Outline:' -> channel(HIDDEN);30BACKGROUND_KEYWORD : 'Background:' ;31EXAMPLES_KEYWORD : 'Examples:' | 'Scenarios:';32RULE_KEYWORD : 'Rule:' ;33STARTING_STEP_KEYWORD : GIVEN_KEYWORD34 | WHEN_KEYWORD35 | THEN_KEYWORD36 | WILD_KEYWORD37 ;38ALTERNATIVE_STEP_KEYWORD : AND_KEYWORD39 | BUT_KEYWORD40 | GIVEN_KEYWORD41 ;42GIVEN_KEYWORD : 'Given ' ;43WHEN_KEYWORD : 'When ' ;44THEN_KEYWORD : 'Then ' ;45WILD_KEYWORD : '* ' ;46AND_KEYWORD : 'And ';47BUT_KEYWORD : 'But ';48fragment CAPTURE_DATA : '<' ~[>\\t\\r\\n ]'>' ;49fragment DOCSTRING_DOUBLE_QUOTES : WS* '"""' (CAPTURE_DATA | ~'"' | '"' ~'"')*? '"""' LINE_END ;50fragment DOCSTRING_BACKTICKS : WS* '```' (~'`' | CAPTURE_DATA | '`' ~'`').*? '```' LINE_END;51fragment TAG : '@'~[ \\r\\n\\t@]+ ;52fragment ESCAPE_SEQUENCE : '\\\\' [\\\\|\\n]* ;53fragment CELL_CHARACTER54 : CAPTURE_DATA55 | ~[\\r\\n|\\\\]56 | ESCAPE_SEQUENCE57 ;58fragment CELL_DATA : WS* CELL_CHARACTER* '|';59DOCSTRING : DOCSTRING_DOUBLE_QUOTES | DOCSTRING_BACKTICKS ;60TAGS : WS* TAG (WS* TAG)* (COMMENT? | LINE_END);61FEATURE_TITLE : WS* FEATURE_KEYWORD ~[\\r\\n]* LINE_END ;62BACKGROUND_TITLE : WS* BACKGROUND_KEYWORD ~[\\r\\n]* COMMENT? LINE_END ;63EXAMPLES_TITLE : WS* EXAMPLES_KEYWORD ~[\\r\\n]* COMMENT? LINE_END ;64SCENARIO_TITLE : WS* SCENARIO_KEYWORD ~[\\r\\n]* LINE_END ;65SCENARIO_OUTLINE_TITLE : WS* SCENARIO_OUTLINE_KEYWORD (CAPTURE_DATA | ~[\\r\\n])* LINE_END ;66RULE_TITLE : WS* RULE_KEYWORD ~[\\r\\n]* LINE_END ;67GIVEN_STEP : WS* GIVEN_KEYWORD ~[ @\\r\\n|] ~[\\r\\n]* LINE_END;68WHEN_STEP : WS* WHEN_KEYWORD ~[ @\\r\\n|] ~[\\r\\n]* LINE_END;69THEN_STEP : WS* THEN_KEYWORD ~[ @\\r\\n|] ~[\\r\\n]* LINE_END;70AND_STEP : WS* AND_KEYWORD ~[ @\\r\\n|] ~[\\r\\n]* LINE_END;71BUT_STEP : WS* BUT_KEYWORD ~[ @\\r\\n|] ~[\\r\\n]* LINE_END;72WILD_STEP : WS* WILD_KEYWORD ~[ @\\r\\n|] ~[\\r\\n]* LINE_END;73DATA_ROW : WS* '|' CELL_DATA+ LINE_END ;74INVALID_LANGUAGE_HEADER : LANGUAGE_KEYWORD ~[\\r\\n]* LINE_END ;75COMMENT : WS* '#' ~[\\r\\n]* LINE_END -> channel(HIDDEN) ;76LINE_END : WS* (NEWLINE+ | EOF) -> skip;77NEWLINE : [\\r\\n] -> skip ;78WS : [ \\t] -> skip;79LONG_DESCRIPTION : WS* ~[ @\\r\\n|] ~[\\r\\n]* LINE_END ;80///////////////////////////////////////////////////81'''82for language in language_data.keys():83 print(language)84 ul = language.upper().replace('-', '_')85 ld = language_data[language]86 template += "\n//" + ld["name"]87 template += "\n//" + ld["native"]88 template += "\nmode " + ul + ";"89 # Feature90 template += "\n\t" + ul + "_FEATURE : ( "91 template += generate_keyword_body(ld["feature"]) + "':'"92 template += "\n\t\t) -> type(FEATURE_KEYWORD) ;"93 # Background94 template += """95 {lc}_BACKGROUND : (96 """.format(lc=ul)97 template += generate_keyword_body(ld["background"]) + "':'"98 template += "\n\t\t) -> type(BACKGROUND_KEYWORD);"99 # Scenario100 template += "\n\t" + ul + "_SCENARIO : (\n"101 template += generate_keyword_body(ld["scenario"]) + "':'"102 template += "\n\t) -> type(SCENARIO_KEYWORD);\n"103 # Scenario Outline104 template += "\n\t" + ul + "_SCENARIO_OUTLINE : (\n"105 template += generate_keyword_body(ld["scenarioOutline"])106 template += "\n\t) -> type(SCENARIO_OUTLINE_KEYWORD);\n"107 # Examples108 template += "\n\t" + ul + "_EXAMPLES : (\n"109 template += generate_keyword_body(ld["examples"]) + "':'"110 template += " ) -> type(EXAMPLES_KEYWORD) ;\n"111 # Rule112 template += "\n\t" + ul + "_RULE : (\n"113 template += generate_keyword_body(ld["rule"]) + "':'"114 template += " ) -> type(RULE_KEYWORD) ;\n"115 # Given116 template += "\n\t" + ul + "_GIVEN : (\n"117 given_keywords = ld["given"]118 if "* " in given_keywords: given_keywords.remove("* ")119 template += generate_keyword_body(given_keywords)120 template += " ) -> type(GIVEN_KEYWORD) ;\n"121 # When122 template += "\n\t" + ul + "_WHEN : (\n"123 when_keywords = ld["when"]124 if "* " in when_keywords: when_keywords.remove("* ")125 template += generate_keyword_body(when_keywords)126 template += " ) -> type(WHEN_KEYWORD) ;\n"127 # Then128 template += "\n\t" + ul + "_THEN : (\n"129 then_keywords = ld["then"]130 if "* " in then_keywords: then_keywords.remove("* ")131 template += generate_keyword_body(then_keywords)132 template += " ) -> type(THEN_KEYWORD) ;\n"133 # And134 template += "\n\t" + ul + "_AND : (\n"135 and_keywords = ld["and"]136 if "* " in and_keywords: and_keywords.remove("* ")137 template += generate_keyword_body(and_keywords)138 template += " ) -> type(AND_KEYWORD) ;\n"139 # But140 template += "\n\t" + ul + "_BUT : (\n"141 but_keywords = ld["but"]142 if "* " in but_keywords: but_keywords.remove("* ")143 template += generate_keyword_body(but_keywords)144 template += " ) -> type(BUT_KEYWORD) ;\n"145 # Starting step146 template += "\n\t" + ul + """_STARTING_STEP_KEYWORD : (\n147 {lc}_GIVEN148 | {lc}_WHEN149 | {lc}_THEN150 | WILD_KEYWORD151 ) -> type(STARTING_STEP_KEYWORD);152 """.format(lc=ul)153 template += "\n\t" + ul + """_ALTERNATIVE_STEP_KEYWORD : (\n154 {lc}_AND155 | {lc}_BUT156 ) -> type(ALTERNATIVE_STEP_KEYWORD);157 """.format(lc=ul)158 template += """159 {language_code}_FEATURE_TITLE : WS* {language_code}_FEATURE ~[\\r\\n]* WS* LINE_END -> type(FEATURE_TITLE) ;160 {language_code}_BACKGROUND_TITLE : WS* {language_code}_BACKGROUND ~[\\r\\n]* COMMENT? LINE_END -> type(BACKGROUND_TITLE) ;161 {language_code}_EXAMPLES_TITLE : WS* {language_code}_EXAMPLES ~[\\r\\n]* COMMENT? LINE_END -> type(EXAMPLES_TITLE);162 {language_code}_SCENARIO_TITLE : WS* {language_code}_SCENARIO ~[\\r\\n]* LINE_END -> type(SCENARIO_TITLE);163 {language_code}_SCENARIO_OUTLINE_TITLE : WS* {language_code}_SCENARIO_OUTLINE ~[\\r\\n]* LINE_END -> type(SCENARIO_OUTLINE_TITLE) ;164 {language_code}_RULE_TITLE : WS* {language_code}_RULE ~[\\r\\n]* LINE_END -> type(RULE_TITLE);165 {language_code}_GIVEN_STEP : WS* {language_code}_GIVEN ~[ @\\r\\n|] ~[\\r\\n]* LINE_END -> type(GIVEN_STEP);166 {language_code}_WHEN_STEP : WS* {language_code}_WHEN ~[ @\\r\\n|] ~[\\r\\n]* LINE_END -> type(WHEN_STEP);167 {language_code}_THEN_STEP : WS* {language_code}_THEN ~[ @\\r\\n|] ~[\\r\\n]* LINE_END -> type(THEN_STEP);168 {language_code}_AND_STEP : WS* {language_code}_AND ~[ @\\r\\n|] ~[\\r\\n]* LINE_END -> type(AND_STEP);169 {language_code}_BUT_STEP : WS* {language_code}_BUT ~[ @\\r\\n|] ~[\\r\\n]* LINE_END -> type(BUT_STEP);170""".format(language_code = ul)171 f = open("GherkinLexer.g4", "w")172 f.write(template)173 f.close()174print("GherkinLexer.g4 regenerated")...

Full Screen

Full Screen

day4.py

Source:day4.py Github

copy

Full Screen

1# advent of code2# day43import re4keywords = ['byr', 'ecl', 'eyr', 'hcl', 'hgt', 'iyr', 'pid']5keywords.sort()6valid_passport_count_a = 0 7valid_passport_count_b = 08with open("../input/day4.txt","r") as file:9 entries = file.readlines()10 # first puzzle11 given_keywords = []12 for i in range(0, len(entries)):13 e = entries[i]14 if e == '\n' or i == len(entries) - 1:15 given_keywords.sort() # for debugging16 if len(given_keywords) == len(keywords):17 valid_passport_count_a += 118 # reset19 given_keywords = []20 21 else:22 items = e.split(' ')23 for i in items:24 key, value = i.split(':')25 if key != 'cid':26 given_keywords.append(key)27 # second puzzle28 given_keywords = []29 debug_given_items=[]30 for i in range(0, len(entries)):31 e = entries[i]32 if e != '\n':33 items = e.split(' ')34 for item in items:35 key, value = item.split(':')36 37 # whether the key's value is valid or not38 valid_value = False 39 40 value = value.rstrip('\r\n') # remove windows end of line41 42 if key == 'byr' :43 valid_value = 1920 <= int(value) <= 200244 elif (key == 'ecl'):45 valid_value = value in ['amb', 'blu', 'brn', 'gry', 'grn' ,'hzl' ,'oth']46 elif key == 'iyr':47 valid_value = 2010 <= int(value) <= 202048 elif key == 'eyr':49 valid_value = 2020 <= int(value) <= 203050 elif key == 'hgt':51 if 'cm' in value:52 valid_value = 150 <= int(value.split('cm')[0]) <= 19353 elif 'in' in value:54 valid_value = 59 <= int(value.split('in')[0]) <= 7655 elif key == 'hcl' :56 valid_value = re.search("^#[0-9a-f]{6}", value)57 elif key == 'pid' :58 valid_value = re.search("^[0-9]{9}$", value) 59 60 if valid_value:61 given_keywords.append(key)62 debug_given_items.append(key+":"+value) # for debugging63 64 65 if (i < len(entries) - 1 and entries[i+1] == '\n') or i ==len(entries) -1:66 given_keywords.sort() # for debugging67 if len(given_keywords) == len(keywords):68 valid_passport_count_b += 169 # for debugging70 debug_given_items.sort()71 #print("b) " + str(valid_passport_count_b)+":"+str(debug_given_items))72 73 # reset74 given_keywords = []75 debug_given_items=[]76 77 78print("a) valid passports ", valid_passport_count_a+1)79print("b) valid passports ",valid_passport_count_b) 80 ...

Full Screen

Full Screen

db_reader.py

Source:db_reader.py Github

copy

Full Screen

1import os2import json3import django4os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'xmemo.settings')5django.setup()6from random import randrange7from cs.models import Question8from xmemo_bot_lib.match_funcs import *9class QuestionJson:10 def __init__(self, model_obj):11 self.model_obj = model_obj12 self.heading = self.model_obj.question13 self.child_list = json.loads(model_obj.answer)14 self.child_html = self.get_child_html()15 def get_child_html(self):16 html = ""17 for each_child in self.child_list:18 html += AnswerJson(each_child).get_html()19 return html20 def get_html(self):21 html = f"""\22<span class="question_group">23 <div class="question">24 <p>{self.heading}</p>25 <div></div>26 </div>27 {self.child_html}28 <div class="major-line-break"></div>29</span>"""30 return html31class AnswerJson:32 def __init__(self, struct):33 self.struct = struct34 def get_html(self):35 html = f"""\36<p class="main-text">37 By ~ <bold>{self.struct["author"]}</bold><br>38 Published on ~ <bold>{self.struct["publish_date"]}</bold><br><br>39 <bold>Answer:</bold><br><br><br><br>40</p>41<pre class="code-block"><code class="lang-python">{self.struct["answer"]}</code></pre>42<p class="main-text">Is this answer correct?</p>43<div id="{self.struct["unique_id"]}" class="validity-check">44 <span class="right inline-btn" onclick="update_correct_val(this)">Correct</span>45 <span class="wrong inline-btn" onclick="update_incorrect_val(this)">Incorrect</span>46</div>47<p id="{self.struct["unique_id"]}correct_indicator" class="main-text" style="color: green;">48 {self.struct["correct_val"]} found this answer to be correct.49</p>50<p id="{self.struct["unique_id"]}wrong_indicator" class="main-text" style="color: red;">51 {self.struct["wrong_val"]} found this answer to be incorrect.52</p>53<div class="minor-line-break"></div>"""54 return html55def get_html_by_date(given_date):56 date = given_date.lower()57 html = ""58 question_list = Question.objects.filter(date=date)59 if len(question_list) > 0:60 for each_question in Question.objects.filter(date=date):61 html += QuestionJson(each_question).get_html()62 else:63 return f'<p class="main-text" style="margin-bottom: 85vh;"><bold>{date}</bold>' \64 ' no record for given date exists.Please try again. </p>'65 return html66def get_html_by_key(given_keywords):67 keywords = given_keywords.lower()68 html = ""69 similar_questions = [model for model in Question.objects.all() if are_similar(keywords, model.question)]70 if len(similar_questions) > 0:71 for each_question in similar_questions:72 html += QuestionJson(each_question).get_html()73 return html74 else:75 return f'\76<p class="main-text" style="margin-bottom: 85vh;"><bold>"{given_keywords}"</bold> ' \...

Full Screen

Full Screen

compute_constraint_metrics.py

Source:compute_constraint_metrics.py Github

copy

Full Screen

1import os2import pandas as pd3import ast4import spacy5from collections import Counter6from sklearn.metrics import f1_score7from sklearn.preprocessing import MultiLabelBinarizer8nlp = spacy.load("en_core_web_lg")9# csv로 저장해서 string이 된 list 되돌리기10def to_list(x):11 return ast.literal_eval(x)12def pos(slogan):13 pos = []14 doc = nlp(slogan)15 for token in doc:16 if str(token) in ['<', '>']:17 continue18 if str(token) in ['name', 'loc']:19 pos.append("PROPN")20 elif str(token) == 'year':21 pos.append("NUM")22 else:23 tag = token.pos_24 if str(tag) == 'SPACE':25 continue26 pos.append(tag)27 return pos28filenames = ['/home/yeoun/BART/PREDS/SynSemBart_lowered_preds.csv', '/home/yeoun/BART/PREDS/originalBart_preds.csv']29# df = pd.DataFrame()30for i, filename in enumerate(filenames):31 if i == 0:32 df = pd.read_csv(filename)33 df = df[['slogan', 'given_keywords', 'predicted_slogan']]34 df = df.rename(columns={'predicted_slogan':filename})35 else:36 temp = pd.read_csv(filename)37 temp = temp.rename(columns={'predicted_slogan':filename})38 df = pd.concat([df, temp[filename]], axis=1)39df.to_csv('multi_merged_preds.csv', index=False, encoding='utf-8')40N = df.shape[0]41df.given_keywords = df.given_keywords.apply(lambda x: to_list(x))42keywords = df.given_keywords.tolist()43slogans = df.slogan.tolist()44pos_tags = [["ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X"]]45multi = MultiLabelBinarizer()46multi.fit(pos_tags)47for column in filenames:48 preds = df[column].tolist()49 keyword_rates = []50 pos_f1 = []51 # keyword order score 추가52 # keyword53 for keyword, pred, slogan in zip(keywords, preds, slogans):54 doc = nlp(pred.lower())55 tokens = []56 for token in doc:57 tokens.append(str(token))58 total = len(keyword)59 count = 060 for k in keyword:61 if k in tokens:62 count += 163 if count / total > 1:64 print(keyword, slogan)65 keyword_rates.append(count / total)66 slogan_pos = [pos(slogan)]67 pred_pos = [pos(pred)]68 A_new = multi.transform(slogan_pos)69 B_new = multi.transform(pred_pos)70 pos_f1.append(f1_score(A_new,B_new,average='samples'))71 print(column, ' 키워드 포함 비율: ', sum(keyword_rates) / N)...

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 Gherkin-python automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful