How to use DEFAULT_OPTIONS method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

crud_sqlite.py

Source:crud_sqlite.py Github

copy

Full Screen

1import sqlite32from packages.dialogs.auxiliar_dialogs import selfCloseInterface3from packages.extras.error_utils import type_checker, condition_checker, ConditionFailedException4from packages.modules.db_templates_manager import close_cursor, initialize_cursor5sqlite_query_operators = [6 '=', '>', '<', '<=', '>=', '<>', '!=', 'ALL', 'AND', 'ANY',7 'BETWEEN', 'EXISTS', 'IN', 'LIKE', 'NOT', 'OR', 'REGEXP'8]9sqlite_logic_joiners = ['AND', 'OR']10sqlite_update_keys = ['SET']11def _insert_on_db(self, table, options):12 # options: dict13 # | { multi: boolean,14 # | fields: list<str>15 # | value: tuple16 # | value_list: list< tuple >17 # | ...18 default_options = {19 'value': None,20 'multi': False,21 'fields': [],22 'value_list': [],23 }24 default_options.update(options)25 value = default_options.get('value')26 multi = default_options.get('multi')27 fields = default_options.get('fields')28 value_list = default_options.get('value_list')29 type_checker(self, multi, bool)30 condition_checker(self, all((type_checker(self, field, str) for field in fields)), True)31 if multi:32 type_checker(self, value_list, type(None), TypeError, False)33 condition_checker(self,34 all((len(fields) == len(x) for x in value_list)),35 True,36 'not enough fields for values or vice versa'37 )38 if not multi:39 condition_checker(self,40 all([41 type_checker(self, value, tuple),42 len(value) == len(fields)43 ]), True,44 'not enough fields for values or vice versa'45 )46 fields_str = str.join(', ', fields)47 q_mark = str.join(', ', ('? ' for i in range(len(fields))))48 command = 'INSERT INTO ' + table + ' (' + fields_str + ') VALUES (' + q_mark + ')'49 # execution phase50 # print(command)51 if multi:52 self.cursor.executemany(command, value_list)53 self.connection.commit()54 return55 if not multi:56 self.cursor.execute(command, value)57 self.connection.commit()58 return59def _select_on_db(self, table, options):60 # print('crud_driver: selecting table %s' % table)61 # print('with options %s' % str(options))62 # options: dict {63 # | pick_all: bool64 # | multi: bool (if True uses many conditions when querying results)65 # | pick_cols: list (cols showed on result)66 # | field: str (field to build the comparison upon)67 # | field_list: list<str> (list of fields for perform comparison multifield)68 # | join_with: str in ['AND', 'OR']69 # | operator: str70 # | operator_list: list<str> (list of operators for perform comparison multifield)71 # | order_by: ['id', 'date'],72 # | order_: ['ASC', 'ASC']73 # | sort: True.74 # | value: tuple()...75 default_options = {76 'pick_all': True,77 'multi': False,78 'join_with': None,79 'pick_cols': ['*'],80 'field': None,81 'field_list': None,82 'operator': None,83 'operator_list': None,84 'value': None,85 'order_by': ['date'],86 'order_': ['ASC'],87 'sort': False88 }89 default_options.update(options)90 pick_all = default_options.get('pick_all')91 multi = default_options.get('multi')92 pick_cols = default_options.get('pick_cols')93 value = default_options.get('value')94 cols = '*'95 order = '' if not default_options.get('sort') else ' ORDER BY ' + ', '.join(list(('{} {}'.format(96 default_options.get('order_by')[i],97 default_options.get('order_')[i]98 ) for i in range(len(default_options.get('order_by'))))))99 # print('sort this table : ', order)100 type_checker(self, pick_all, bool),101 if pick_all:102 command = 'SELECT ' + cols + ' FROM ' + table + order103 # print('command to be executed on current operation: ', command)104 self.cursor.execute(command)105 return106 if all([107 type_checker(self, pick_cols, list),108 all((type_checker(self, col, str) for col in pick_cols)),109 len(pick_cols) >= 1110 ]):111 cols = str.join(', ', (col for col in pick_cols))112 command = 'SELECT ' + cols + ' FROM ' + table113 if default_options.get('field') is None and default_options.get('field_list') is None:114 command += order115 # print('command to be executed on current operation: ', command)116 self.cursor.execute(command)117 return118 type_checker(self, multi, bool)119 if multi:120 join_with = default_options.get('join_with')121 field_list = default_options.get('field_list')122 operator_list = default_options.get('operator_list')123 condition_checker(self,124 len(field_list) == len(operator_list), True,125 'discordance between fields and operators'126 )127 condition_checker(self,128 join_with in sqlite_logic_joiners,129 True,130 'must define a join operator for multi where clauses'131 )132 condition_checker(self, all(133 (type_checker(self, field, str) for field in field_list)134 ), True, 'fields should be a string')135 condition_checker(self, all(136 (type_checker(self, operator, str) for operator in operator_list)137 ), True, 'operators should be a string')138 compound_filter = str.join(139 ' %s ' % join_with,140 ('%s %s ?' % (field_list[index], operator_list[index]) for index in range(len(field_list)))141 )142 command = command + ' WHERE ' + compound_filter + order +';'143 # print('debug: inside branch multi command to be executed on current operation: ', command)144 if not multi: # single query conditions145 field = options.get('field')146 operator = options.get('operator')147 type_checker(self, operator, str)148 type_checker(self, field, str)149 condition_checker(self, operator in sqlite_query_operators, True,150 'operator < %s > not supported' % operator)151 command = command + ' WHERE ' + field + ' ' + operator + ' ?' + order +' ;'152 # print('debug: inside branch multi command to be executed on current operation: ', command)153 # print('command to be executed on current operation: ', command)154 type_checker(self, value, tuple)155 condition_checker(self, len(value) == str.count(command, '?'))156 self.cursor.execute(command, value)157 return158def _update_on_db(self, table, options):159 # | action: str in ['SET', ??? ]160 # | slave_col: str161 # | slave_op: str in query operators162 # | slave_col_list: list<str> >> used when many rows to update163 # | slave_op_list: list<str> in query operators >> idem above164 # | value: tuple165 # | value_list: list<tuple>166 # | master_col: str >> name of the master_col slave_col, the one that defines the comparison parameter167 # | master_op: >> str in query operators, this one discriminates the query results168 # | master_col_list: list<str> >> list with name of the master_col used on many cols updating169 # | master_op_list: >> list<str> in query operators, this one discriminates the query results170 # | bulk_updating: bool >> defines if updating one or many rows in a single query171 # | multi_cols: bool >> defines if updating one or many cols in a single query172 # | multi_filter: bool >> defines if use one or many cols for filter the query173 # | join_with: str in ['AND', 'OR']174 # | ...175 default_options = {'action': None,176 'slave_col': None, 'slave_op': None,177 'master_col': None, 'master_op': None, 'value': None,178 'slave_col_list': [None], 'slave_op_list': [None],179 'master_col_list': [None], 'master_op_list': [None], 'value_list': [None],180 'bulk_updating': False, 'multi_cols': False, 'multi_filter': False, 'join_with': None181 }182 default_options.update(options)183 action = default_options.get('action')184 bulk_updating = default_options.get('bulk_updating')185 multi_cols = default_options.get('multi_cols')186 multi_filter = default_options.get('multi_filter')187 # -----just 4 ref: these statements are used only inside the branch that needs it188 # slave_col = default_options.get('slave_col')189 # slave_op = default_options.get('slave_op')190 # slave_col_list = default_options.get('slave_col_list')191 # slave_op_list = default_options.get('slave_op_list')192 # value = default_options.get('value')193 # value_list = default_options.get('value_list')194 # master_col = default_options.get('master_col')195 # master_op = default_options.get('master_op')196 # master_col_list = default_options.get('master_col_list')197 # master_op_list = default_options.get('master_op_list')198 # join_with = default_options('join_with')199 condition_checker(self, action in sqlite_update_keys)200 type_checker(self, multi_cols, bool)201 type_checker(self, bulk_updating, bool)202 type_checker(self, multi_filter, bool)203 command = 'UPDATE ' + table + ' ' + action204 if multi_cols: # update many slave_cols per row205 slave_col_list = default_options.get('slave_col_list')206 slave_op_list = default_options.get('slave_op_list')207 type_checker(self, slave_col_list, list)208 type_checker(self, slave_op_list, list)209 condition_checker(self, all([210 all((type_checker(self, slave_col, str) for slave_col in slave_col_list)),211 all((type_checker(self, slave_op, str) for slave_op in slave_op_list)),212 all((condition_checker(self, slave_op in sqlite_query_operators) for slave_op in213 slave_op_list)),214 len(slave_col_list) == len(slave_op_list)215 ]))216 slave_col_parameter = str.join(', ',217 (' %s %s ? ' % (slave_col_list[index], slave_op_list[index]) for index in218 range(len(slave_col_list)))219 )220 command += slave_col_parameter221 if not multi_cols: # update a single slave_col per row222 slave_col = default_options.get('slave_col')223 slave_op = default_options.get('slave_op')224 condition_checker(self, all([225 type_checker(self, slave_col, str),226 type_checker(self, slave_op, str),227 condition_checker(self, slave_op in sqlite_query_operators)228 ]))229 slave_col_parameter = '%s %s ? ' % (slave_col, slave_op)230 command += slave_col_parameter231 command += 'WHERE '232 if multi_filter: # use many master_cols for filter the query before updating rows233 master_col_list = default_options.get('master_col_list')234 master_op_list = default_options.get('master_op_list')235 join_with = default_options.get('join_with')236 condition_checker(self, all([237 join_with in sqlite_logic_joiners,238 type_checker(self, master_col_list, list),239 type_checker(self, master_op_list, list),240 len(master_col_list) == len(master_op_list),241 all((type_checker(self, master_col, str) for master_col in master_col_list)),242 all((type_checker(self, master_op, str) for master_op in master_op_list)),243 all((condition_checker(self, master_op in sqlite_query_operators) for master_op in244 master_op_list))245 ]))246 compound_filter = str.join(247 ' %s ' % join_with,248 ('%s %s ?' % (master_col_list[index], master_op_list[index]) for index in range(len(master_col_list)))249 )250 command += compound_filter251 if not multi_filter: # use just one master_col for filter the query before updating rows252 master_col = default_options.get('master_col')253 master_op = default_options.get('master_op')254 condition_checker(self, all([255 type_checker(self, master_col, str),256 type_checker(self, master_op, str),257 ]))258 compound_filter = '%s %s ?' % (master_col, master_op)259 command += compound_filter260 # --- execution phase ----261 if bulk_updating: # perform many updating in a single query with executemany262 value_list = default_options.get('value_list')263 occurrences = str.count(command, '?')264 type_checker(self, value_list, list)265 condition_checker(self, any(266 (len(value_tuple) != occurrences for value_tuple in value_list)267 ), False)268 # print(command)269 self.cursor.executemany(command, value_list)270 self.connection.commit()271 return272 if not bulk_updating: # perform a single update with execute273 value = default_options.get('value')274 occurrences = str.count(command, '?')275 type_checker(self, value, tuple)276 condition_checker(self, len(value) == occurrences)277 # print(command)278 self.cursor.execute(command, value)279 self.connection.commit()280 return281 raise Exception('must define bulk updating parameter before proceed...')282def _delete_on_db(self, table, options):283 if options is None:284 command = 'DELETE FROM ' + table285 # print(command)286 self.cursor.execute(command)287 self.connection.commit()288 return289 # -> este metodo admite multi master_col290 # -> admite multi row con execute many...291 # | master_col: str >> this col determines the value for perform the comparison on292 # | master_op: str >> str in sqlite query operators. define how to compare the value293 # | master_col_list: list<str> >> this col determines the value for perform the comparison on294 # | master_op_list: list<str> >> str in sqlite query operators. define how to compare the value295 # | multi_filter: bool >> determines if using a single col for filtering or many296 # | bulk_updating: bool >> this prop determines if use execute or executemany ...297 # | value: tuple >> the value for set the filter298 # | value_list: list<tuple> >> the list with values for perform a multi delete in a single query299 # | join_with: str >> str in sqlite joiners ...300 default_options = {301 'master_col': None,302 'master_op': None,303 'master_col_list': [None],304 'master_op_list': [None],305 'bulk_updating': False,306 'value': None,307 'join_with': None,308 'value_list': [None],309 'multi-filter': False310 }311 default_options.update(options)312 bulk_updating = default_options.get('bulk_updating')313 multi_filter = default_options.get('multi_filter')314 # for ref purposes--- this props are defined only inside the corresponding branch if executed315 # value = default_options.get('value')316 # value_list = default_options.get('value_list')317 # join_with = default_options.get('join_with')318 # master_col = default_options.get('master_col')319 # master_op = default_options.get('master_op')320 # master_col_list = default_options.get('master_col_list')321 # master_op_list = default_options.get('master_op_list')322 condition_checker(self, all([323 type_checker(self, bulk_updating, bool),324 type_checker(self, multi_filter, bool)325 ]))326 command = 'DELETE FROM ' + table + ' WHERE'327 if multi_filter:328 master_col_list = default_options.get('master_col_list')329 master_op_list = default_options.get('master_op_list')330 join_with = default_options.get('join_with')331 condition_checker(self, join_with in sqlite_logic_joiners)332 type_checker(self, master_op_list, list)333 type_checker(self, master_col_list, list)334 condition_checker(self, all([335 len(master_col_list) == len(self, master_op_list),336 all((type_checker(self, master_col, str) for master_col in master_col_list)),337 all((type_checker(self, master_op, str) for master_op in master_op_list)),338 all((condition_checker(self, master_op in sqlite_query_operators) for master_op in339 master_op_list))340 ]))341 compound_filter = str.join(342 ' %s ' % join_with,343 (' %s %s ?' % (master_col_list[index], master_op_list[index]) for index in range(len(master_col_list)))344 )345 command = command + compound_filter + ' ;'346 if not multi_filter:347 master_col = default_options.get('master_col')348 master_op = default_options.get('master_op')349 condition_checker(self, all([350 type_checker(self, master_col, str),351 type_checker(self, master_op, str),352 condition_checker(self, master_op in sqlite_query_operators),353 ]))354 command = command + ' ' + master_col + ' ' + master_op + ' ? ;'355 if bulk_updating:356 value_list = default_options.get('value_list')357 condition_checker(self, all([358 type_checker(self, value_list, list),359 condition_checker(self, all(360 (type_checker(self, value_tuple, tuple) for value_tuple in value_list)361 )),362 condition_checker(self, all(363 (type_checker(self, value_tuple, tuple) for value_tuple in value_list)364 )),365 condition_checker(self, all(366 (len(tuple_value) == str.count(command, '?') for tuple_value in value_list)367 ))368 ]))369 # print(command)370 self.cursor.executemany(command, value_list)371 self.connection.commit()372 return373 if not bulk_updating:374 value = default_options.get('value')375 type_checker(self, value, tuple)376 condition_checker(self, len(value) == str.count(command, '?'))377 # print(command)378 self.cursor.execute(command, value)379 self.connection.commit()380 return381 raise Exception('must define bulk_updating property to <bool>')382def crud_driver(self, table, operation, options):383 type_checker(self, options, dict)384 type_checker(self, table, str)385 data = None386 try:387 if self.cursor is not None:388 close_cursor(self)389 initialize_cursor(self)390 if operation == 'create':391 _insert_on_db(self, table, options)392 if operation == 'read':393 _select_on_db(self, table, options)394 if operation == 'update':395 _update_on_db(self, table, options)396 if operation == 'delete':397 _delete_on_db(self, table, options)398 if operation == 'raw_exec':399 # print('debug: ejecutando raw execution with:')400 # print('debug: query: ',options.get('raw_exec'))401 # print('debug: values: ',options.get('value'))402 if any([403 isinstance(options.get('value'), list),404 isinstance(options.get('value'), tuple)405 ]) and len(options.get('value')) > 0:406 self.cursor.execute(options.get('raw_exec'), options.get('value'))407 else:408 self.cursor.execute(options.get('raw_exec'))409 except sqlite3.Error as error:410 # print('error inside crud driver: ', error)411 selfCloseInterface('error on Database Process',alert_level=3,title='DB Error',info=str(error))412 # raise error413 except ConditionFailedException as error2:414 # print(str(error2))415 # alert_on_error = MessageBox(lambda: # print(str(error)), str(error2), 'e', 'DB error')416 # alert_on_error.show()417 raise error2418 finally:419 if operation in ['raw_exec', 'read']:420 data = self.cursor.fetchall()421 close_cursor(self)422 # print('data from %s operation: ' % operation, data)423 return data424 if self.cursor is not None:425 close_cursor(self)426# ----aggregations427def find_total(self, table, slave, master, values, multi_filter=False, regexp=False):428 # this function returns only the first (and unique? ) result429 # so far regexp only works on single filter executions430 type_checker(self, values, tuple)431 total = 0432 operator = '=' if not regexp else 'REGEXP'433 if not multi_filter:434 type_checker(self, master, str)435 raw_execution_string = 'SELECT total(' + slave + ') FROM '+table+' WHERE ' + master + ' '+operator+' ? ;'436 total = crud_driver(self, table, 'raw_exec', {437 'raw_exec': raw_execution_string,438 'value': values439 })440 if multi_filter:441 type_checker(self, master, list)442 master_list = list(map(lambda i: ' '+str(i)+' '+operator+' ?', master))443 suffix = str.join(' AND ', master_list)444 total = crud_driver(self, table, 'raw_exec', {445 'raw_exec': 'SELECT total(' + slave + ') FROM ' + table + ' WHERE ' + suffix + ' ;',446 'value': values447 })448 # todo elaborar mapeo de ulti filter449 # print(total)...

Full Screen

Full Screen

Training.py

Source:Training.py Github

copy

Full Screen

1import Cnst2from ModelOptions import ModelOptions3from BoxEModel import BoxEMulti4import argparse5def stop_grad(v):6 if v in (Cnst.NO_STOPS, Cnst.STOP_SIZES, Cnst.STOP_POSITIONS, Cnst.STOP_BOTH):7 return v8 else:9 raise argparse.ArgumentTypeError('Invalid Stop Gradient Setting Entered')10def obj_fct(v):11 if v.lower() in ('negSamp', Cnst.NEG_SAMP, 'ns', 'n'):12 return Cnst.NEG_SAMP13 elif v.lower() in ('marginBased', Cnst.MARGIN_BASED, 'mb', 'm'):14 return Cnst.MARGIN_BASED15 else:16 raise argparse.ArgumentTypeError("Invalid Final Objective Function Used")17def loss_fct(v):18 if v.lower() in ('ply', Cnst.POLY_LOSS, 'p', 'polynomial'):19 return Cnst.POLY_LOSS20 elif v.lower() in ('q2box', Cnst.Q2B_LOSS, 'q', 'query2box'):21 return Cnst.Q2B_LOSS22 else:23 raise argparse.ArgumentTypeError("Invalid Final Loss Function Used")24def neg_samp(v):25 if v.lower() in ('u', 'unif', 'uniform'):26 return Cnst.UNIFORM27 elif v.lower() in ('gan', 'adversarial'):28 return Cnst.GAN 29 elif v.lower() in ('self-adv', 'self', 'sa', 'self-adversarial', 'selfadv'):30 return Cnst.SELFADV31 else:32 raise argparse.ArgumentTypeError('Invalid Negative Sampling Option selected')33def str2bool(v):34 if v.lower() in ('yes', 'true', 't', 'y', '1'):35 return True36 elif v.lower() in ('no', 'false', 'f', 'n', '0'):37 return False38 else:39 raise argparse.ArgumentTypeError('Boolean value expected.')40def train_commandline():41 default_options = ModelOptions() 42 default_options.running_mode = Cnst.TRAIN 43 parser = argparse.ArgumentParser(description='Set up BoxE training over a given KB')44 parser.add_argument("targetKB", type=str, help="The Knowledge Base on which to train")45 parser.add_argument("-validation", metavar='', type=str2bool, default=False, help=" Use Validation-Based "46 "training (early stopping)")47 parser.add_argument("-printFreq", metavar='', type=int, default=50, help="Batch Interval between which to log")48 parser.add_argument("-validCkpt", metavar='', type=int, default=50, help="Epoch Gap between validation "49 + "tests (if applicable)")50 parser.add_argument("-savePeriod", type=int, default=10000, metavar='',51 help="If no early stopping, batch intervals at which weight saving is done")52 parser.add_argument("-epochs", type=int, default=100000, metavar='', help="Maximum Number of Epochs to run")53 parser.add_argument("-resetWeights", type=str2bool, default=True, metavar='',54 help="Initialize weights (default) or start with existing weights")55 parser.add_argument("-lossFName", type=str, metavar='', default="losses", help="Loss Log File Name")56 parser.add_argument("-logToFile", type=str2bool, metavar='', default=True, help="Log to file (default)" +57 "or print to console")58 parser.add_argument("-logFName", type=str, metavar='', default="training_log.txt", help="Loss Log File Name")59 60 61 parser.add_argument("-useTB", type=str2bool, default=default_options.use_tensorboard, metavar='',62 help="Enable Use of TensorBoard during training")63 parser.add_argument('-embDim', type=int, default=default_options.embedding_dim, metavar='',64 help="Embedding Dimensionality for points and boxes")65 parser.add_argument('-negSampling', type=neg_samp, default=default_options.neg_sampling_opt, metavar='',66 help="Type of Negative Sampling to use (Default and Only Current Option: Uniform")67 parser.add_argument("-nbNegExp", type=int, default=default_options.nb_neg_examples_per_pos, metavar='',68 help="Number of Negative Examples per positive example (default "69 + str(default_options.nb_neg_examples_per_pos)+")")70 parser.add_argument("-batchSize", type=int, default=default_options.batch_size, metavar='',71 help="Batch Size to use for Training (default "+str(default_options.batch_size)+")")72 parser.add_argument("-lossMargin", type=float, default=default_options.loss_margin, metavar='',73 help="The maximum negative distance to consider")74 parser.add_argument("-advTemp", type=float, default=default_options.adversarial_temp, metavar='',75 help="The temperature to use for self-adversarial negative sampling")76 parser.add_argument("-regLambda", type=float, default=default_options.regularisation_lambda, metavar='',77 help="The weight of L2 regularization over bound width (BOX model) to apply")78 parser.add_argument("-totalLogBoxSize", type=float, default=default_options.total_log_box_size, metavar='',79 help="The total log box size to target during training")80 parser.add_argument("-boundScale", type=float, default=default_options.space_bound, metavar='',81 help="The finite bounds of the space (if bounded)")82 parser.add_argument("-learningRate", type=float, default=default_options.learning_rate, metavar='',83 help="Learning Rate to use for training (default "+str(default_options.learning_rate)+")")84 parser.add_argument("-lrDecay", type=float, default=default_options.learning_rate_decay, metavar='',85 help="Learning Rate Decay to use in training (default " +86 str(default_options.learning_rate_decay) + ")")87 parser.add_argument("-lrDecayStep", type=float, default=default_options.decay_period, metavar='',88 help="Decay Period for LR (default " +89 str(default_options.decay_period) + ")")90 parser.add_argument("-stopGradients", type=stop_grad, default=default_options.stop_gradient, metavar='',91 help="Stop Gradient Configuration for negative examples. NO STOP:" + Cnst.NO_STOPS92 + "|| STOP REL BOUNDS:" + Cnst.STOP_SIZES + " (default " + default_options.stop_gradient +93 ")")94 parser.add_argument("-stopNegated", type=str2bool, default=default_options.stop_gradient_negated, metavar='',95 help="Disable Gradients from non-replaced negative example components")96 parser.add_argument("-sharedShape", type=str2bool, default=default_options.shared_shape, metavar='',97 help="Specifies whether shape is shared by all boxes during training")98 parser.add_argument("-fixedWidth", type=str2bool, default=default_options.fixed_width, metavar='',99 help="Specifies whether box width (size) is learned during training")100 parser.add_argument("-learnableShape", type=str2bool, default=default_options.learnable_shape, metavar='',101 help="Specifies whether shape is learned during training")102 parser.add_argument("-useBumps", type=str2bool, default=default_options.use_bumps, metavar='',103 help="Allow pairwise bumping to occur, to prevent all-pair correctness (default " +104 str(default_options.use_bumps)+")")105 parser.add_argument("-hardSize", type=str2bool, default=default_options.hard_total_size, metavar='',106 help="Use Softmax to enforce that all boxes share a hard total size")107 parser.add_argument("-hardCodeSize", type=str2bool, default=default_options.hard_total_size, metavar='',108 help="Hard Code Size based on statistical appearances of relations in set (works only "109 "with shared shape)")110 parser.add_argument("-boundedPt", type=str2bool, default=default_options.bounded_pt_space, metavar='',111 help="Limit points (following bumps and all processing in the unbounded space) to be mapped to "112 "the bounded tanh ]-1,1[ space")113 parser.add_argument("-regPoints", type=float, default=default_options.regularisation_points, metavar='',114 help="Regularisation factor to apply to batch to prevent excessive divergence from center")115 parser.add_argument("-lossOrd", type=int, default=default_options.loss_norm_ord, metavar='',116 help="Order of loss normalisation to use (Default "+str(default_options.loss_norm_ord)+" )")117 parser.add_argument("-boundedBox", type=str2bool, default=default_options.bounded_box_space, metavar='',118 help="Limit boxes (following bumps and all processing in the unbounded space) to be mapped to "119 "the bounded tanh ]-1,1[ space")120 parser.add_argument("-objFct", type=obj_fct, default=default_options.obj_fct, metavar='',121 help="Choice of Objective Function in Training (Default " + str(default_options.obj_fct) + ")")122 parser.add_argument("-lossFct", type=loss_fct, default=default_options.loss_fct, metavar='',123 help="Choice of Loss Function in Training (Default " + str(default_options.obj_fct) + ")")124 parser.add_argument("-dimDropout", type=float, default=default_options.dim_dropout_prob, metavar='',125 help="Dropout probability to use when training the model (Default "126 + str(default_options.dim_dropout_prob)+")")127 parser.add_argument("-gradClip", type=float, default=default_options.gradient_clip, metavar='',128 help="Value to apply for gradient clipping (Default "129 + str(default_options.gradient_clip)+")")130 parser.add_argument("-boundedNorm", type=str2bool, default=default_options.bounded_box_space, metavar='',131 help="Limit boxes (following bumps and all processing in the unbounded space) to a minimum "132 "and maximum size per dimension")133 parser.add_argument("-normedBumps", type=str2bool, default=default_options.normed_bumps, metavar='',134 help="Restrict all bumps to be of L2 norm 1 (default +"+str(default_options.normed_bumps)+")")135 parser.add_argument("-separateValid", type=str2bool, default=False, metavar='',136 help="Use a duplicate model without negative sampling to perform quicker testing")137 parser.add_argument("-ruleDir", type=str, default=False, metavar='', help="Specify the txt "138 "file to read rules from (default no)")139 parser.add_argument("-augmentInv", type=str2bool, default=default_options.augment_inv, metavar='',140 help="For binary KBs, augment training set with inverse relations (default "141 + str(default_options.augment_inv)+")")142 parser.add_argument("-viz", type=str2bool, default=False, metavar='',143 help="Enable Data Logging for subsequent BoxEViz visualization")144 145 args = parser.parse_args()146 target_kb = args.targetKB147 feedback_period = args.printFreq148 save_period = args.savePeriod149 epoch_checkpoint = args.validCkpt150 num_epochs = args.epochs151 reset_weights = args.resetWeights152 loss_file_name = args.lossFName153 log_to_file = args.logToFile154 log_file_name = args.logFName155 156 default_options.batch_size = args.batchSize157 default_options.use_tensorboard = args.useTB158 default_options.embedding_dim = args.embDim159 default_options.neg_sampling_opt = args.negSampling160 default_options.nb_neg_examples_per_pos = args.nbNegExp161 default_options.learning_rate = args.learningRate162 default_options.learning_rate_decay = args.lrDecay163 default_options.decay_period = args.lrDecayStep164 default_options.stop_gradient = args.stopGradients165 default_options.adversarial_temp = args.advTemp166 default_options.total_log_box_size = args.totalLogBoxSize167 default_options.loss_margin = args.lossMargin168 default_options.regularisation_lambda = args.regLambda169 default_options.stop_gradient_negated = args.stopNegated170 default_options.use_bumps = args.useBumps171 default_options.shared_shape = args.sharedShape172 default_options.learnable_shape = args.learnableShape173 default_options.fixed_width = args.fixedWidth174 default_options.hard_total_size = args.hardSize175 default_options.hard_code_size = args.hardCodeSize176 default_options.bounded_pt_space = args.boundedPt177 default_options.bounded_box_space = args.boundedBox178 default_options.space_bound = args.boundScale179 default_options.obj_fct = args.objFct180 default_options.loss_fct = args.lossFct181 default_options.dim_dropout_prob = args.dimDropout182 default_options.regularisation_points = args.regPoints183 default_options.loss_norm_ord = args.lossOrd184 default_options.gradient_clip = args.gradClip185 default_options.bounded_norm = args.boundedNorm186 default_options.rule_dir = args.ruleDir187 default_options.normed_bumps = args.normedBumps188 default_options.augment_inv = args.augmentInv189 sepValid = args.separateValid190 model = BoxEMulti(target_kb, default_options)191 model.train_with_valid(print_period=feedback_period, epoch_ckpt=epoch_checkpoint, num_epochs=num_epochs,192 reset_weights=reset_weights, loss_file_name=loss_file_name, log_to_file=log_to_file,193 log_file_name=log_file_name, save_period=save_period, separate_valid_model=sepValid,194 viz_mode=args.viz)195if __name__ == "__main__":...

Full Screen

Full Screen

test_file_processor.py

Source:test_file_processor.py Github

copy

Full Screen

1"""Tests for the FileProcessor class."""2import ast3import tokenize4import mock5import pytest6from flake8 import processor7def test_read_lines_splits_lines(default_options):8 """Verify that read_lines splits the lines of the file."""9 file_processor = processor.FileProcessor(__file__, default_options)10 lines = file_processor.lines11 assert len(lines) > 512 assert lines[0].strip() == '"""Tests for the FileProcessor class."""'13def _lines_from_file(tmpdir, contents, options):14 f = tmpdir.join('f.py')15 # be careful to write the bytes exactly to avoid newline munging16 f.write_binary(contents)17 return processor.FileProcessor(f.strpath, options).lines18def test_read_lines_universal_newlines(tmpdir, default_options):19 r"""Verify that line endings are translated to \n."""20 lines = _lines_from_file(21 tmpdir, b'# coding: utf-8\r\nx = 1\r\n', default_options)22 assert lines == ['# coding: utf-8\n', 'x = 1\n']23def test_read_lines_incorrect_utf_16(tmpdir, default_options):24 """Verify that an incorrectly encoded file is read as latin-1."""25 lines = _lines_from_file(26 tmpdir, b'# coding: utf16\nx = 1\n', default_options)27 assert lines == ['# coding: utf16\n', 'x = 1\n']28def test_read_lines_unknown_encoding(tmpdir, default_options):29 """Verify that an unknown encoding is still read as latin-1."""30 lines = _lines_from_file(31 tmpdir, b'# coding: fake-encoding\nx = 1\n', default_options)32 assert lines == ['# coding: fake-encoding\n', 'x = 1\n']33@pytest.mark.parametrize('first_line', [34 '\xEF\xBB\xBF"""Module docstring."""\n',35 u'\uFEFF"""Module docstring."""\n',36])37def test_strip_utf_bom(first_line, default_options):38 r"""Verify that we strip '\xEF\xBB\xBF' from the first line."""39 lines = [first_line]40 file_processor = processor.FileProcessor('-', default_options, lines[:])41 assert file_processor.lines != lines42 assert file_processor.lines[0] == '"""Module docstring."""\n'43@pytest.mark.parametrize('lines, expected', [44 (['\xEF\xBB\xBF"""Module docstring."""\n'], False),45 ([u'\uFEFF"""Module docstring."""\n'], False),46 (['#!/usr/bin/python', '# flake8 is great', 'a = 1'], False),47 (['#!/usr/bin/python', '# flake8: noqa', 'a = 1'], True),48 (['#!/usr/bin/python', '# flake8:noqa', 'a = 1'], True),49 (['# flake8: noqa', '#!/usr/bin/python', 'a = 1'], True),50 (['# flake8:noqa', '#!/usr/bin/python', 'a = 1'], True),51 (['#!/usr/bin/python', 'a = 1', '# flake8: noqa'], True),52 (['#!/usr/bin/python', 'a = 1', '# flake8:noqa'], True),53 (['#!/usr/bin/python', 'a = 1 # flake8: noqa'], False),54 (['#!/usr/bin/python', 'a = 1 # flake8:noqa'], False),55])56def test_should_ignore_file(lines, expected, default_options):57 """Verify that we ignore a file if told to."""58 file_processor = processor.FileProcessor('-', default_options, lines)59 assert file_processor.should_ignore_file() is expected60def test_should_ignore_file_to_handle_disable_noqa(default_options):61 """Verify that we ignore a file if told to."""62 lines = ['# flake8: noqa']63 file_processor = processor.FileProcessor('-', default_options, lines)64 assert file_processor.should_ignore_file() is True65 default_options.disable_noqa = True66 file_processor = processor.FileProcessor('-', default_options, lines)67 assert file_processor.should_ignore_file() is False68@mock.patch('flake8.utils.stdin_get_value')69def test_read_lines_from_stdin(stdin_get_value, default_options):70 """Verify that we use our own utility function to retrieve stdin."""71 stdin_get_value.return_value = ''72 processor.FileProcessor('-', default_options)73 stdin_get_value.assert_called_once_with()74@mock.patch('flake8.utils.stdin_get_value')75def test_stdin_filename_attribute(stdin_get_value, default_options):76 """Verify that we update the filename attribute."""77 stdin_get_value.return_value = ''78 file_processor = processor.FileProcessor('-', default_options)79 assert file_processor.filename == 'stdin'80@mock.patch('flake8.utils.stdin_get_value')81def test_read_lines_uses_display_name(stdin_get_value, default_options):82 """Verify that when processing stdin we use a display name if present."""83 default_options.stdin_display_name = 'display_name.py'84 stdin_get_value.return_value = ''85 file_processor = processor.FileProcessor('-', default_options)86 assert file_processor.filename == 'display_name.py'87@mock.patch('flake8.utils.stdin_get_value')88def test_read_lines_ignores_empty_display_name(89 stdin_get_value, default_options,90):91 """Verify that when processing stdin we use a display name if present."""92 stdin_get_value.return_value = ''93 default_options.stdin_display_name = ''94 file_processor = processor.FileProcessor('-', default_options)95 assert file_processor.filename == 'stdin'96def test_noqa_line_for(default_options):97 """Verify we grab the correct line from the cached lines."""98 file_processor = processor.FileProcessor('-', default_options, lines=[99 'Line 1\n',100 'Line 2\n',101 'Line 3\n',102 ])103 for i in range(1, 4):104 assert file_processor.noqa_line_for(i) == 'Line {0}\n'.format(i)105def test_noqa_line_for_continuation(default_options):106 """Verify that the correct "line" is retrieved for continuation."""107 src = '''\108from foo \\109 import bar # 2110x = """111hello112world113""" # 7114'''115 lines = src.splitlines(True)116 file_processor = processor.FileProcessor('-', default_options, lines=lines)117 assert file_processor.noqa_line_for(0) is None118 l_1_2 = 'from foo \\\n import bar # 2\n'119 assert file_processor.noqa_line_for(1) == l_1_2120 assert file_processor.noqa_line_for(2) == l_1_2121 assert file_processor.noqa_line_for(3) == '\n'122 l_4_7 = 'x = """\nhello\nworld\n""" # 7\n'123 for i in (4, 5, 6, 7):124 assert file_processor.noqa_line_for(i) == l_4_7125 assert file_processor.noqa_line_for(8) is None126def test_noqa_line_for_no_eol_at_end_of_file(default_options):127 """Verify that we properly handle noqa line at the end of the file."""128 src = 'from foo \\\nimport bar' # no end of file newline129 lines = src.splitlines(True)130 file_processor = processor.FileProcessor('-', default_options, lines=lines)131 l_1_2 = 'from foo \\\nimport bar'132 assert file_processor.noqa_line_for(1) == l_1_2133 assert file_processor.noqa_line_for(2) == l_1_2134def test_next_line(default_options):135 """Verify we update the file_processor state for each new line."""136 file_processor = processor.FileProcessor('-', default_options, lines=[137 'Line 1',138 'Line 2',139 'Line 3',140 ])141 for i in range(1, 4):142 assert file_processor.next_line() == 'Line {}'.format(i)143 assert file_processor.line_number == i144@pytest.mark.parametrize('params, args, expected_kwargs', [145 ({'blank_before': True, 'blank_lines': True},146 None,147 {'blank_before': 0, 'blank_lines': 0}),148 ({'noqa': True, 'fake': True},149 {'fake': 'foo'},150 {'noqa': False, 'fake': 'foo'}),151 ({'blank_before': True, 'blank_lines': True, 'noqa': True},152 {'blank_before': 10, 'blank_lines': 5, 'noqa': True},153 {'blank_before': 10, 'blank_lines': 5, 'noqa': True}),154 ({}, {'fake': 'foo'}, {'fake': 'foo'}),155 ({'non-existent': False}, {'fake': 'foo'}, {'fake': 'foo'}),156])157def test_keyword_arguments_for(params, args, expected_kwargs, default_options):158 """Verify the keyword args are generated properly."""159 file_processor = processor.FileProcessor('-', default_options, lines=[160 'Line 1',161 ])162 kwargs_for = file_processor.keyword_arguments_for163 assert kwargs_for(params, args) == expected_kwargs164def test_keyword_arguments_for_does_not_handle_attribute_errors(165 default_options,166):167 """Verify we re-raise AttributeErrors."""168 file_processor = processor.FileProcessor('-', default_options, lines=[169 'Line 1',170 ])171 with pytest.raises(AttributeError):172 file_processor.keyword_arguments_for({'fake': True})173@pytest.mark.parametrize('unsplit_line, expected_lines', [174 ('line', []),175 ('line 1\n', ['line 1']),176 ('line 1\nline 2\n', ['line 1', 'line 2']),177 ('line 1\n\nline 2\n', ['line 1', '', 'line 2']),178])179def test_split_line(unsplit_line, expected_lines, default_options):180 """Verify the token line splitting."""181 file_processor = processor.FileProcessor('-', default_options, lines=[182 'Line 1',183 ])184 token = (1, unsplit_line, (0, 0), (0, 0), '')185 actual_lines = list(file_processor.split_line(token))186 assert expected_lines == actual_lines187 assert len(actual_lines) == file_processor.line_number188def test_build_ast(default_options):189 """Verify the logic for how we build an AST for plugins."""190 file_processor = processor.FileProcessor('-', default_options, lines=[191 'a = 1\n'192 ])193 module = file_processor.build_ast()194 assert isinstance(module, ast.Module)195def test_next_logical_line_updates_the_previous_logical_line(default_options):196 """Verify that we update our tracking of the previous logical line."""197 file_processor = processor.FileProcessor('-', default_options, lines=[198 'a = 1\n'199 ])200 file_processor.indent_level = 1201 file_processor.logical_line = 'a = 1'202 assert file_processor.previous_logical == ''203 assert file_processor.previous_indent_level == 0204 file_processor.next_logical_line()205 assert file_processor.previous_logical == 'a = 1'206 assert file_processor.previous_indent_level == 1207def test_visited_new_blank_line(default_options):208 """Verify we update the number of blank lines seen."""209 file_processor = processor.FileProcessor('-', default_options, lines=[210 'a = 1\n'211 ])212 assert file_processor.blank_lines == 0213 file_processor.visited_new_blank_line()214 assert file_processor.blank_lines == 1215def test_inside_multiline(default_options):216 """Verify we update the line number and reset multiline."""217 file_processor = processor.FileProcessor('-', default_options, lines=[218 'a = 1\n'219 ])220 assert file_processor.multiline is False221 assert file_processor.line_number == 0222 with file_processor.inside_multiline(10):223 assert file_processor.multiline is True224 assert file_processor.line_number == 10225 assert file_processor.multiline is False226@pytest.mark.parametrize('string, expected', [227 ('""', '""'),228 ("''", "''"),229 ('"a"', '"x"'),230 ("'a'", "'x'"),231 ('"x"', '"x"'),232 ("'x'", "'x'"),233 ('"abcdef"', '"xxxxxx"'),234 ("'abcdef'", "'xxxxxx'"),235 ('""""""', '""""""'),236 ("''''''", "''''''"),237 ('"""a"""', '"""x"""'),238 ("'''a'''", "'''x'''"),239 ('"""x"""', '"""x"""'),240 ("'''x'''", "'''x'''"),241 ('"""abcdef"""', '"""xxxxxx"""'),242 ("'''abcdef'''", "'''xxxxxx'''"),243 ('"""xxxxxx"""', '"""xxxxxx"""'),244 ("'''xxxxxx'''", "'''xxxxxx'''"),245])246def test_mutate_string(string, expected, default_options):247 """Verify we appropriately mutate the string to sanitize it."""248 actual = processor.mutate_string(string)249 assert expected == actual250@pytest.mark.parametrize('string, expected', [251 (' ', 4),252 (' ', 6),253 ('\t', 8),254 ('\t\t', 16),255 (' \t', 8),256 (' \t', 16),257])258def test_expand_indent(string, expected):259 """Verify we correctly measure the amount of indentation."""260 actual = processor.expand_indent(string)261 assert expected == actual262@pytest.mark.parametrize('token, log_string', [263 [(tokenize.COMMENT, '# this is a comment',264 (1, 0), # (start_row, start_column)265 (1, 19), # (end_ro, end_column)266 '# this is a comment',),267 "l.1\t[:19]\tCOMMENT\t'# this is a comment'"],268 [(tokenize.COMMENT, '# this is a comment',269 (1, 5), # (start_row, start_column)270 (1, 19), # (end_ro, end_column)271 '# this is a comment',),272 "l.1\t[5:19]\tCOMMENT\t'# this is a comment'"],273 [(tokenize.COMMENT, '# this is a comment',274 (1, 0), # (start_row, start_column)275 (2, 19), # (end_ro, end_column)276 '# this is a comment',),277 "l.1\tl.2\tCOMMENT\t'# this is a comment'"],278])279def test_log_token(token, log_string):280 """Verify we use the log object passed in."""281 log = mock.Mock()282 processor.log_token(log, token)283 log.log.assert_called_once_with(284 5, # flake8._EXTRA_VERBOSE285 log_string,286 )287@pytest.mark.parametrize('current_count, token_text, expected', [288 (0, '(', 1),289 (0, '[', 1),290 (0, '{', 1),291 (1, ')', 0),292 (1, ']', 0),293 (1, '}', 0),294 (10, '+', 10),295])296def test_count_parentheses(current_count, token_text, expected):297 """Verify our arithmetic is correct."""298 assert processor.count_parentheses(current_count, token_text) == expected299def test_nonexistent_file(default_options):300 """Verify that FileProcessor raises IOError when a file does not exist."""301 with pytest.raises(IOError):...

Full Screen

Full Screen

routes.js

Source:routes.js Github

copy

Full Screen

1import colors from "colors"2var _ = require('underscore')3var makeRoutes = function(options) {4 let default_options = {5 app: null,6 modelName: null,7 controller: null,8 prefix: '',9 allow_methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],10 secure_methods: {}11 }12 _.extend(default_options, options)13 console.log(`[Koapi]`.blue+` resource ready`.green + ` ${default_options.prefix}/${default_options.modelName}`.yellow);14 var secure_middleware = function *(next) {15 if (this.isAuthenticated()) {16 yield next17 } else {18 this.body = {19 error: {20 code: '401',21 message: 'Forbiden'22 }23 }24 this.status = 40125 }26 }27 var async_secure_middleware = function (next) {28 if (this.isAuthenticated()) {29 if (next)30 next();31 } else {32 this.body = {33 error: {34 code: '401',35 message: 'Forbiden'36 }37 }38 this.status = 40139 }40 }41 if (default_options.hasFiles) {42 // put method43 if(default_options.secure_methods['PUT']){44 // secure the method with authentication middleware45 let authentication = (default_options.secure_methods['PUT'] == 'default' ? secure_middleware : default_options.secure_methods['PUT'])46 default_options.app.put(default_options.prefix + ("/" + default_options.modelName + "/:id/:field"), authentication, function *() {47 default_options.controller.saveFile(this)48 this.status = 200;49 });50 }else{51 default_options.app.put(default_options.prefix + ("/" + default_options.modelName + "/:id/:field"), function *() {52 default_options.controller.saveFile(this)53 this.status = 200;54 });55 }56 // post methods57 if(default_options.secure_methods['POST']){58 // secure the method with authentication middleware59 let authentication = (default_options.secure_methods['POST'] == 'default' ? secure_middleware : default_options.secure_methods['POST'])60 default_options.app.post(default_options.prefix + ("/" + default_options.modelName + "/:id/:field"), authentication, function *() {61 default_options.controller.saveFile(this)62 this.status = 200;63 });64 }else{65 default_options.app.post(default_options.prefix + ("/" + default_options.modelName + "/:id/:field"), function *() {66 default_options.controller.saveFile(this)67 this.status = 200;68 });69 }70 }71 //let secure_methods = _.intersection(default_options.allow_methods, default_options.secure_methods)72 // collection route73 if (_.indexOf(default_options.allow_methods, 'GET') >= 0){74 if(default_options.secure_methods['GET']){75 // secure the method with authentication middleware76 let authentication = (default_options.secure_methods['GET'] == 'default' ? secure_middleware : default_options.secure_methods['GET'])77 default_options.app.get(default_options.prefix + ("/" + default_options.modelName), authentication, function* () {78 return yield default_options.controller.findAll(this)79 });80 }else{81 default_options.app.get(default_options.prefix + ("/" + default_options.modelName), function* () {82 return yield default_options.controller.findAll(this)83 });84 }85 }86 // detail route87 if (_.indexOf(default_options.allow_methods, 'GET') >= 0){88 if(default_options.secure_methods['GET']){89 // secure the method with authentication middleware90 let authentication = (default_options.secure_methods['GET'] == 'default' ? secure_middleware : default_options.secure_methods['GET'])91 default_options.app.get(default_options.prefix + ("/" + default_options.modelName + "/:id"), authentication, function* () {92 return yield default_options.controller.findById(this)93 });94 }else{95 default_options.app.get(default_options.prefix + ("/" + default_options.modelName + "/:id"), function* () {96 return yield default_options.controller.findById(this)97 });98 }99 }100 // create route101 if (_.indexOf(default_options.allow_methods, 'POST') >= 0){102 if(default_options.secure_methods['POST']){103 // secure the method with authentication middleware104 let authentication = (default_options.secure_methods['POST'] == 'default' ? secure_middleware : default_options.secure_methods['POST'])105 default_options.app.post(default_options.prefix + ("/" + default_options.modelName), authentication,function* () {106 return yield default_options.controller.create(this)107 });108 }else{109 default_options.app.post(default_options.prefix + ("/" + default_options.modelName), function* () {110 return yield default_options.controller.create(this)111 });112 }113 }114 // update with post route115 if (_.indexOf(default_options.allow_methods, 'POST') >= 0){116 if(default_options.secure_methods['POST']){117 // secure the method with authentication middleware118 let authentication = (default_options.secure_methods['POST'] == 'default' ? secure_middleware : default_options.secure_methods['POST'])119 default_options.app.post(default_options.prefix + ("/" + default_options.modelName + "/:id"), authentication, function* () {120 return yield default_options.controller.updateById(this)121 });122 }else{123 default_options.app.post(default_options.prefix + ("/" + default_options.modelName + "/:id"), function* () {124 return yield default_options.controller.updateById(this)125 });126 }127 }128 // update route129 if (_.indexOf(default_options.allow_methods, 'PUT') >= 0){130 if(default_options.secure_methods['PUT']){131 // secure the method with authentication middleware132 let authentication = (default_options.secure_methods['PUT'] == 'default' ? secure_middleware : default_options.secure_methods['PUT'])133 default_options.app.put(default_options.prefix + ("/" + default_options.modelName + "/:id"), authentication, function* () {134 return yield default_options.controller.updateById(this)135 });136 }else{137 default_options.app.put(default_options.prefix + ("/" + default_options.modelName + "/:id"), function* () {138 return yield default_options.controller.updateById(this)139 });140 }141 }142 // patch route143 if (_.indexOf(default_options.allow_methods, 'PATCH') >= 0){144 if(default_options.secure_methods['PATCH']){145 // secure the method with authentication middleware146 let authentication = (default_options.secure_methods['PATCH'] == 'default' ? secure_middleware : default_options.secure_methods['PATCH'])147 default_options.app.patch(default_options.prefix + ("/" + default_options.modelName + "/:id"), authentication, function* () {148 return yield default_options.controller.updateById(this)149 });150 }else{151 default_options.app.patch(default_options.prefix + ("/" + default_options.modelName + "/:id"), function* () {152 return yield default_options.controller.updateById(this)153 });154 }155 }156 // delete route157 if (_.indexOf(default_options.allow_methods, 'DELETE') >= 0){158 if(default_options.secure_methods['DELETE']){159 // secure the method with authentication middleware160 let authentication = (default_options.secure_methods['DELETE'] == 'default' ? secure_middleware : default_options.secure_methods['DELETE'])161 default_options.app.del(default_options.prefix + ("/" + default_options.modelName + "/:id"), authentication, function* () {162 return yield default_options.controller.deleteById(this)163 });164 }else{165 default_options.app.del(default_options.prefix + ("/" + default_options.modelName + "/:id"), function* () {166 return yield default_options.controller.deleteById(this)167 });168 }169 }170};...

Full Screen

Full Screen

options.test.ts

Source:options.test.ts Github

copy

Full Screen

1import {DEFAULT_OPTIONS, ParseFlavor} from '../../src/defaults';2import {normalizeOptions} from '../../src/options';3import {structuredClone} from '../../src/utils';4const getOptions = () => structuredClone(DEFAULT_OPTIONS);5test('default option normalize', () => {6 const default_options = normalizeOptions();7 expect(typeof default_options.parser.if === 'function').toBe(true);8});9test('option function normalize', () => {10 const options = getOptions();11 // @ts-ignore12 options.parser.if = (s: string) => s.split('');13 const default_options = normalizeOptions(options);14 expect(typeof default_options.parser.define === 'function').toBe(true);15 expect(typeof default_options.parser.if === 'function').toBe(true);16 expect(default_options.parser.if('test')).toStrictEqual(['t', 'e', 's', 't']);17});18test('option string normalize', () => {19 const options = getOptions();20 // @ts-ignore21 options.parser.file_detect = 'test';22 // @ts-ignore23 options.parser.if = 'test';24 const default_options = normalizeOptions(options);25 expect(default_options.parser.file_detect).toBeInstanceOf(RegExp);26 expect(typeof default_options.parser.if === 'function').toBe(true);27});28test('option unknown normalize', () => {29 const options = getOptions();30 // @ts-ignore31 options.parser.if = {};32 expect(() => normalizeOptions(options)).toThrow('Invalid parsing option: expected string, RegExp, or function');33});34test('option empty defines', () => {35 const options = getOptions();36 options.definitions = undefined;37 const default_options = normalizeOptions(options);38 expect(default_options.definitions).toStrictEqual({});39});40test('option set defines', () => {41 const options = getOptions();42 options.definitions = {43 'global': 'value',44 };45 const default_options = normalizeOptions(options);46 expect(default_options.definitions).toStrictEqual({47 'global': 'value',48 });49});50test('testing boolean false sandbox', () => {51 const options = getOptions();52 options.sandbox = false;53 const default_options = normalizeOptions(options);54 expect(default_options.sandbox).toBeUndefined();55});56test('testing boolean true sandbox', () => {57 const options = getOptions();58 options.sandbox = true;59 const default_options = normalizeOptions(options);60 expect(default_options.sandbox).toStrictEqual({61 memory_limit: 128,62 timeout: 10000,63 });64});65test('Test flavor parsing', () => {66 const options = getOptions();67 options.parser = ParseFlavor.at;68 let default_options = normalizeOptions(options);69 expect(default_options.parser.if('@if test')).toStrictEqual([70 {index: 0, value: '@if test'},71 {index: 0, value: 'test'},72 ]);73 options.parser = ParseFlavor.hash;74 default_options = normalizeOptions(options);75 expect(default_options.parser.if('#if test')).toStrictEqual([76 {index: 0, value: '#if test'},77 {index: 0, value: 'test'},78 ]);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Pact } = require('@pact-foundation/pact');2const { matcher, like, term } = require('@pact-foundation/pact/dsl/matchers');3const DEFAULT_OPTIONS = {4 log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),5 dir: path.resolve(process.cwd(), 'pacts'),6};7const provider = new Pact({8});9describe('Pact', () => {10 beforeAll(() => provider.setup());11 afterAll(() => provider.finalize());12 describe('when a request to get all users is made', () => {13 beforeAll(() => {14 return provider.addInteraction({15 withRequest: {16 headers: {17 },18 },19 willRespondWith: {20 headers: {21 'Content-Type': 'application/json; charset=utf-8',22 },23 body: [matcher.eachLike({ id: 1, name: 'John' })],24 },25 });26 });27 it('returns a successful body', async () => {28 const response = await axios.get(`${provider.mockService.baseUrl}/users`);29 expect(response.status).toEqual(200);30 expect(response.data).toEqual([{ id: 1, name: 'John' }]);31 await provider.verify();32 });33 });34});35const { Matchers } = require('@pact-foundation/pact');36const { like, eachLike } = Matchers;37const { server } = require('./server');38describe('User Service', () => {39 describe('get all users', () => {40 beforeAll(() => {41 const interaction = {42 withRequest: {43 headers: {44 },45 },46 willRespondWith: {47 headers: {

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 pact-foundation-pact 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