How to use directive method in ng-mocks

Best JavaScript code snippet using ng-mocks

test_preprocessor.py

Source:test_preprocessor.py Github

copy

Full Screen

...35 parsed = None36 def check_calls(self, *expected):37 super().check_calls(*expected)38 self.assertEqual(self.parsed or [], [])39 def _parse_directive(self, line):40 self.calls.append(41 ('_parse_directive', line))42 self.try_next_exc()43 return self.parsed.pop(0)44 def test_no_lines(self):45 lines = []46 results = list(47 iter_lines(lines, _parse_directive=self._parse_directive))48 self.assertEqual(results, [])49 self.check_calls()50 def test_no_directives(self):51 lines = textwrap.dedent('''52 // xyz53 typedef enum {54 SPAM55 EGGS56 } kind;57 struct info {58 kind kind;59 int status;60 };61 typedef struct spam {62 struct info info;63 } myspam;64 static int spam = 0;65 /**66 * ...67 */68 static char *69 get_name(int arg,70 char *default,71 )72 {73 return default74 }75 int check(void) {76 return 0;77 }78 ''')[1:-1].splitlines()79 expected = [(lno, line, None, ())80 for lno, line in enumerate(lines, 1)]81 expected[1] = (2, ' ', None, ())82 expected[20] = (21, ' ', None, ())83 del expected[19]84 del expected[18]85 results = list(86 iter_lines(lines, _parse_directive=self._parse_directive))87 self.assertEqual(results, expected)88 self.check_calls()89 def test_single_directives(self):90 tests = [91 ('#include <stdio>', Include('<stdio>')),92 ('#define SPAM 1', Constant('SPAM', '1')),93 ('#define SPAM() 1', Macro('SPAM', (), '1')),94 ('#define SPAM(a, b) a = b;', Macro('SPAM', ('a', 'b'), 'a = b;')),95 ('#if defined(SPAM)', IfDirective('if', 'defined(SPAM)')),96 ('#ifdef SPAM', IfDirective('ifdef', 'SPAM')),97 ('#ifndef SPAM', IfDirective('ifndef', 'SPAM')),98 ('#elseif defined(SPAM)', IfDirective('elseif', 'defined(SPAM)')),99 ('#else', OtherDirective('else', None)),100 ('#endif', OtherDirective('endif', None)),101 ('#error ...', OtherDirective('error', '...')),102 ('#warning ...', OtherDirective('warning', '...')),103 ('#__FILE__ ...', OtherDirective('__FILE__', '...')),104 ('#__LINE__ ...', OtherDirective('__LINE__', '...')),105 ('#__DATE__ ...', OtherDirective('__DATE__', '...')),106 ('#__TIME__ ...', OtherDirective('__TIME__', '...')),107 ('#__TIMESTAMP__ ...', OtherDirective('__TIMESTAMP__', '...')),108 ]109 for line, directive in tests:110 with self.subTest(line):111 self.reset()112 self.parsed = [113 directive,114 ]115 text = textwrap.dedent('''116 static int spam = 0;117 {}118 static char buffer[256];119 ''').strip().format(line)120 lines = text.strip().splitlines()121 results = list(122 iter_lines(lines, _parse_directive=self._parse_directive))123 self.assertEqual(results, [124 (1, 'static int spam = 0;', None, ()),125 (2, line, directive, ()),126 ((3, 'static char buffer[256];', None, ('defined(SPAM)',))127 if directive.kind in ('if', 'ifdef', 'elseif')128 else (3, 'static char buffer[256];', None, ('! defined(SPAM)',))129 if directive.kind == 'ifndef'130 else (3, 'static char buffer[256];', None, ())),131 ])132 self.check_calls(133 ('_parse_directive', line),134 )135 def test_directive_whitespace(self):136 line = ' # define eggs ( a , b ) { a = b ; } '137 directive = Macro('eggs', ('a', 'b'), '{ a = b; }')138 self.parsed = [139 directive,140 ]141 lines = [line]142 results = list(143 iter_lines(lines, _parse_directive=self._parse_directive))144 self.assertEqual(results, [145 (1, line, directive, ()),146 ])147 self.check_calls(148 ('_parse_directive', '#define eggs ( a , b ) { a = b ; }'),149 )150 @unittest.skipIf(sys.platform == 'win32', 'needs fix under Windows')151 def test_split_lines(self):152 directive = Macro('eggs', ('a', 'b'), '{ a = b; }')153 self.parsed = [154 directive,155 ]156 text = textwrap.dedent(r'''157 static int spam = 0;158 #define eggs(a, b) \159 { \160 a = b; \161 }162 static char buffer[256];163 ''').strip()164 lines = [line + '\n' for line in text.splitlines()]165 lines[-1] = lines[-1][:-1]166 results = list(167 iter_lines(lines, _parse_directive=self._parse_directive))168 self.assertEqual(results, [169 (1, 'static int spam = 0;\n', None, ()),170 (5, '#define eggs(a, b) { a = b; }\n', directive, ()),171 (6, 'static char buffer[256];', None, ()),172 ])173 self.check_calls(174 ('_parse_directive', '#define eggs(a, b) { a = b; }'),175 )176 def test_nested_conditions(self):177 directives = [178 IfDirective('ifdef', 'SPAM'),179 IfDirective('if', 'SPAM == 1'),180 IfDirective('elseif', 'SPAM == 2'),181 OtherDirective('else', None),182 OtherDirective('endif', None),183 OtherDirective('endif', None),184 ]185 self.parsed = list(directives)186 text = textwrap.dedent(r'''187 static int spam = 0;188 #ifdef SPAM189 static int start = 0;190 # if SPAM == 1191 static char buffer[10];192 # elif SPAM == 2193 static char buffer[100];194 # else195 static char buffer[256];196 # endif197 static int end = 0;198 #endif199 static int eggs = 0;200 ''').strip()201 lines = [line for line in text.splitlines() if line.strip()]202 results = list(203 iter_lines(lines, _parse_directive=self._parse_directive))204 self.assertEqual(results, [205 (1, 'static int spam = 0;', None, ()),206 (2, '#ifdef SPAM', directives[0], ()),207 (3, 'static int start = 0;', None, ('defined(SPAM)',)),208 (4, '# if SPAM == 1', directives[1], ('defined(SPAM)',)),209 (5, 'static char buffer[10];', None, ('defined(SPAM)', 'SPAM == 1')),210 (6, '# elif SPAM == 2', directives[2], ('defined(SPAM)', 'SPAM == 1')),211 (7, 'static char buffer[100];', None, ('defined(SPAM)', '! (SPAM == 1)', 'SPAM == 2')),212 (8, '# else', directives[3], ('defined(SPAM)', '! (SPAM == 1)', 'SPAM == 2')),213 (9, 'static char buffer[256];', None, ('defined(SPAM)', '! (SPAM == 1)', '! (SPAM == 2)')),214 (10, '# endif', directives[4], ('defined(SPAM)', '! (SPAM == 1)', '! (SPAM == 2)')),215 (11, 'static int end = 0;', None, ('defined(SPAM)',)),216 (12, '#endif', directives[5], ('defined(SPAM)',)),217 (13, 'static int eggs = 0;', None, ()),218 ])219 self.check_calls(220 ('_parse_directive', '#ifdef SPAM'),221 ('_parse_directive', '#if SPAM == 1'),222 ('_parse_directive', '#elif SPAM == 2'),223 ('_parse_directive', '#else'),224 ('_parse_directive', '#endif'),225 ('_parse_directive', '#endif'),226 )227 def test_split_blocks(self):228 directives = [229 IfDirective('ifdef', 'SPAM'),230 OtherDirective('else', None),231 OtherDirective('endif', None),232 ]233 self.parsed = list(directives)234 text = textwrap.dedent(r'''235 void str_copy(char *buffer, *orig);236 int init(char *name) {237 static int initialized = 0;238 if (initialized) {239 return 0;240 }241 #ifdef SPAM242 static char buffer[10];243 str_copy(buffer, char);244 }245 void copy(char *buffer, *orig) {246 strncpy(buffer, orig, 9);247 buffer[9] = 0;248 }249 #else250 static char buffer[256];251 str_copy(buffer, char);252 }253 void copy(char *buffer, *orig) {254 strcpy(buffer, orig);255 }256 #endif257 ''').strip()258 lines = [line for line in text.splitlines() if line.strip()]259 results = list(260 iter_lines(lines, _parse_directive=self._parse_directive))261 self.assertEqual(results, [262 (1, 'void str_copy(char *buffer, *orig);', None, ()),263 (2, 'int init(char *name) {', None, ()),264 (3, ' static int initialized = 0;', None, ()),265 (4, ' if (initialized) {', None, ()),266 (5, ' return 0;', None, ()),267 (6, ' }', None, ()),268 (7, '#ifdef SPAM', directives[0], ()),269 (8, ' static char buffer[10];', None, ('defined(SPAM)',)),270 (9, ' str_copy(buffer, char);', None, ('defined(SPAM)',)),271 (10, '}', None, ('defined(SPAM)',)),272 (11, 'void copy(char *buffer, *orig) {', None, ('defined(SPAM)',)),273 (12, ' strncpy(buffer, orig, 9);', None, ('defined(SPAM)',)),274 (13, ' buffer[9] = 0;', None, ('defined(SPAM)',)),275 (14, '}', None, ('defined(SPAM)',)),276 (15, '#else', directives[1], ('defined(SPAM)',)),277 (16, ' static char buffer[256];', None, ('! (defined(SPAM))',)),278 (17, ' str_copy(buffer, char);', None, ('! (defined(SPAM))',)),279 (18, '}', None, ('! (defined(SPAM))',)),280 (19, 'void copy(char *buffer, *orig) {', None, ('! (defined(SPAM))',)),281 (20, ' strcpy(buffer, orig);', None, ('! (defined(SPAM))',)),282 (21, '}', None, ('! (defined(SPAM))',)),283 (22, '#endif', directives[2], ('! (defined(SPAM))',)),284 ])285 self.check_calls(286 ('_parse_directive', '#ifdef SPAM'),287 ('_parse_directive', '#else'),288 ('_parse_directive', '#endif'),289 )290 @unittest.skipIf(sys.platform == 'win32', 'needs fix under Windows')291 def test_basic(self):292 directives = [293 Include('<stdio.h>'),294 IfDirective('ifdef', 'SPAM'),295 IfDirective('if', '! defined(HAM) || !HAM'),296 Constant('HAM', '0'),297 IfDirective('elseif', 'HAM < 0'),298 Constant('HAM', '-1'),299 OtherDirective('else', None),300 OtherDirective('endif', None),301 OtherDirective('endif', None),302 IfDirective('if', 'defined(HAM) && (HAM < 0 || ! HAM)'),303 OtherDirective('undef', 'HAM'),304 OtherDirective('endif', None),305 IfDirective('ifndef', 'HAM'),306 OtherDirective('endif', None),307 ]308 self.parsed = list(directives)309 text = textwrap.dedent(r'''310 #include <stdio.h>311 print("begin");312 #ifdef SPAM313 print("spam");314 #if ! defined(HAM) || !HAM315 # DEFINE HAM 0316 #elseif HAM < 0317 # DEFINE HAM -1318 #else319 print("ham HAM");320 #endif321 #endif322 #if defined(HAM) && \323 (HAM < 0 || ! HAM)324 print("ham?");325 #undef HAM326 # endif327 #ifndef HAM328 print("no ham");329 #endif330 print("end");331 ''')[1:-1]332 lines = [line + '\n' for line in text.splitlines()]333 lines[-1] = lines[-1][:-1]334 results = list(335 iter_lines(lines, _parse_directive=self._parse_directive))336 self.assertEqual(results, [337 (1, '#include <stdio.h>\n', Include('<stdio.h>'), ()),338 (2, 'print("begin");\n', None, ()),339 #340 (3, '#ifdef SPAM\n',341 IfDirective('ifdef', 'SPAM'),342 ()),343 (4, ' print("spam");\n',344 None,345 ('defined(SPAM)',)),346 (5, ' #if ! defined(HAM) || !HAM\n',347 IfDirective('if', '! defined(HAM) || !HAM'),348 ('defined(SPAM)',)),349 (6, '# DEFINE HAM 0\n',350 Constant('HAM', '0'),351 ('defined(SPAM)', '! defined(HAM) || !HAM')),352 (7, ' #elseif HAM < 0\n',353 IfDirective('elseif', 'HAM < 0'),354 ('defined(SPAM)', '! defined(HAM) || !HAM')),355 (8, '# DEFINE HAM -1\n',356 Constant('HAM', '-1'),357 ('defined(SPAM)', '! (! defined(HAM) || !HAM)', 'HAM < 0')),358 (9, ' #else\n',359 OtherDirective('else', None),360 ('defined(SPAM)', '! (! defined(HAM) || !HAM)', 'HAM < 0')),361 (10, ' print("ham HAM");\n',362 None,363 ('defined(SPAM)', '! (! defined(HAM) || !HAM)', '! (HAM < 0)')),364 (11, ' #endif\n',365 OtherDirective('endif', None),366 ('defined(SPAM)', '! (! defined(HAM) || !HAM)', '! (HAM < 0)')),367 (12, '#endif\n',368 OtherDirective('endif', None),369 ('defined(SPAM)',)),370 #371 (13, '\n', None, ()),372 #373 (15, '#if defined(HAM) && (HAM < 0 || ! HAM)\n',374 IfDirective('if', 'defined(HAM) && (HAM < 0 || ! HAM)'),375 ()),376 (16, ' print("ham?");\n',377 None,378 ('defined(HAM) && (HAM < 0 || ! HAM)',)),379 (17, ' #undef HAM\n',380 OtherDirective('undef', 'HAM'),381 ('defined(HAM) && (HAM < 0 || ! HAM)',)),382 (18, '# endif\n',383 OtherDirective('endif', None),384 ('defined(HAM) && (HAM < 0 || ! HAM)',)),385 #386 (19, '\n', None, ()),387 #388 (20, '#ifndef HAM\n',389 IfDirective('ifndef', 'HAM'),390 ()),391 (21, ' print("no ham");\n',392 None,393 ('! defined(HAM)',)),394 (22, '#endif\n',395 OtherDirective('endif', None),396 ('! defined(HAM)',)),397 #398 (23, 'print("end");', None, ()),399 ])400 @unittest.skipIf(sys.platform == 'win32', 'needs fix under Windows')401 def test_typical(self):402 # We use Include/compile.h from commit 66c4f3f38b86. It has403 # a good enough mix of code without being too large.404 directives = [405 IfDirective('ifndef', 'Py_COMPILE_H'),406 Constant('Py_COMPILE_H', None),407 IfDirective('ifndef', 'Py_LIMITED_API'),408 Include('"code.h"'),409 IfDirective('ifdef', '__cplusplus'),410 OtherDirective('endif', None),411 Constant('PyCF_MASK', '(CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | CO_FUTURE_GENERATOR_STOP | CO_FUTURE_ANNOTATIONS)'),412 Constant('PyCF_MASK_OBSOLETE', '(CO_NESTED)'),413 Constant('PyCF_SOURCE_IS_UTF8', ' 0x0100'),414 Constant('PyCF_DONT_IMPLY_DEDENT', '0x0200'),415 Constant('PyCF_ONLY_AST', '0x0400'),416 Constant('PyCF_IGNORE_COOKIE', '0x0800'),417 Constant('PyCF_TYPE_COMMENTS', '0x1000'),418 Constant('PyCF_ALLOW_TOP_LEVEL_AWAIT', '0x2000'),419 IfDirective('ifndef', 'Py_LIMITED_API'),420 OtherDirective('endif', None),421 Constant('FUTURE_NESTED_SCOPES', '"nested_scopes"'),422 Constant('FUTURE_GENERATORS', '"generators"'),423 Constant('FUTURE_DIVISION', '"division"'),424 Constant('FUTURE_ABSOLUTE_IMPORT', '"absolute_import"'),425 Constant('FUTURE_WITH_STATEMENT', '"with_statement"'),426 Constant('FUTURE_PRINT_FUNCTION', '"print_function"'),427 Constant('FUTURE_UNICODE_LITERALS', '"unicode_literals"'),428 Constant('FUTURE_BARRY_AS_BDFL', '"barry_as_FLUFL"'),429 Constant('FUTURE_GENERATOR_STOP', '"generator_stop"'),430 Constant('FUTURE_ANNOTATIONS', '"annotations"'),431 Macro('PyAST_Compile', ('mod', 's', 'f', 'ar'), 'PyAST_CompileEx(mod, s, f, -1, ar)'),432 Constant('PY_INVALID_STACK_EFFECT', 'INT_MAX'),433 IfDirective('ifdef', '__cplusplus'),434 OtherDirective('endif', None),435 OtherDirective('endif', None), # ifndef Py_LIMITED_API436 Constant('Py_single_input', '256'),437 Constant('Py_file_input', '257'),438 Constant('Py_eval_input', '258'),439 Constant('Py_func_type_input', '345'),440 OtherDirective('endif', None), # ifndef Py_COMPILE_H441 ]442 self.parsed = list(directives)443 text = textwrap.dedent(r'''444 #ifndef Py_COMPILE_H445 #define Py_COMPILE_H446 #ifndef Py_LIMITED_API447 #include "code.h"448 #ifdef __cplusplus449 extern "C" {450 #endif451 /* Public interface */452 struct _node; /* Declare the existence of this type */453 PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, const char *);454 /* XXX (ncoghlan): Unprefixed type name in a public API! */455 #define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | \456 CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | \457 CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | \458 CO_FUTURE_GENERATOR_STOP | CO_FUTURE_ANNOTATIONS)459 #define PyCF_MASK_OBSOLETE (CO_NESTED)460 #define PyCF_SOURCE_IS_UTF8 0x0100461 #define PyCF_DONT_IMPLY_DEDENT 0x0200462 #define PyCF_ONLY_AST 0x0400463 #define PyCF_IGNORE_COOKIE 0x0800464 #define PyCF_TYPE_COMMENTS 0x1000465 #define PyCF_ALLOW_TOP_LEVEL_AWAIT 0x2000466 #ifndef Py_LIMITED_API467 typedef struct {468 int cf_flags; /* bitmask of CO_xxx flags relevant to future */469 int cf_feature_version; /* minor Python version (PyCF_ONLY_AST) */470 } PyCompilerFlags;471 #endif472 /* Future feature support */473 typedef struct {474 int ff_features; /* flags set by future statements */475 int ff_lineno; /* line number of last future statement */476 } PyFutureFeatures;477 #define FUTURE_NESTED_SCOPES "nested_scopes"478 #define FUTURE_GENERATORS "generators"479 #define FUTURE_DIVISION "division"480 #define FUTURE_ABSOLUTE_IMPORT "absolute_import"481 #define FUTURE_WITH_STATEMENT "with_statement"482 #define FUTURE_PRINT_FUNCTION "print_function"483 #define FUTURE_UNICODE_LITERALS "unicode_literals"484 #define FUTURE_BARRY_AS_BDFL "barry_as_FLUFL"485 #define FUTURE_GENERATOR_STOP "generator_stop"486 #define FUTURE_ANNOTATIONS "annotations"487 struct _mod; /* Declare the existence of this type */488 #define PyAST_Compile(mod, s, f, ar) PyAST_CompileEx(mod, s, f, -1, ar)489 PyAPI_FUNC(PyCodeObject *) PyAST_CompileEx(490 struct _mod *mod,491 const char *filename, /* decoded from the filesystem encoding */492 PyCompilerFlags *flags,493 int optimize,494 PyArena *arena);495 PyAPI_FUNC(PyCodeObject *) PyAST_CompileObject(496 struct _mod *mod,497 PyObject *filename,498 PyCompilerFlags *flags,499 int optimize,500 PyArena *arena);501 PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromAST(502 struct _mod * mod,503 const char *filename /* decoded from the filesystem encoding */504 );505 PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromASTObject(506 struct _mod * mod,507 PyObject *filename508 );509 /* _Py_Mangle is defined in compile.c */510 PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name);511 #define PY_INVALID_STACK_EFFECT INT_MAX512 PyAPI_FUNC(int) PyCompile_OpcodeStackEffect(int opcode, int oparg);513 PyAPI_FUNC(int) PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump);514 PyAPI_FUNC(int) _PyAST_Optimize(struct _mod *, PyArena *arena, int optimize);515 #ifdef __cplusplus516 }517 #endif518 #endif /* !Py_LIMITED_API */519 /* These definitions must match corresponding definitions in graminit.h. */520 #define Py_single_input 256521 #define Py_file_input 257522 #define Py_eval_input 258523 #define Py_func_type_input 345524 #endif /* !Py_COMPILE_H */525 ''').strip()526 lines = [line + '\n' for line in text.splitlines()]527 lines[-1] = lines[-1][:-1]528 results = list(529 iter_lines(lines, _parse_directive=self._parse_directive))530 self.assertEqual(results, [531 (1, '#ifndef Py_COMPILE_H\n',532 IfDirective('ifndef', 'Py_COMPILE_H'),533 ()),534 (2, '#define Py_COMPILE_H\n',535 Constant('Py_COMPILE_H', None),536 ('! defined(Py_COMPILE_H)',)),537 (3, '\n',538 None,539 ('! defined(Py_COMPILE_H)',)),540 (4, '#ifndef Py_LIMITED_API\n',541 IfDirective('ifndef', 'Py_LIMITED_API'),542 ('! defined(Py_COMPILE_H)',)),543 (5, '#include "code.h"\n',544 Include('"code.h"'),545 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),546 (6, '\n',547 None,548 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),549 (7, '#ifdef __cplusplus\n',550 IfDirective('ifdef', '__cplusplus'),551 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),552 (8, 'extern "C" {\n',553 None,554 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', 'defined(__cplusplus)')),555 (9, '#endif\n',556 OtherDirective('endif', None),557 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', 'defined(__cplusplus)')),558 (10, '\n',559 None,560 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),561 (11, ' \n',562 None,563 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),564 (12, 'struct _node; \n',565 None,566 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),567 (13, 'PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, const char *);\n',568 None,569 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),570 (14, ' \n',571 None,572 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),573 (15, '\n',574 None,575 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),576 (19, '#define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | CO_FUTURE_GENERATOR_STOP | CO_FUTURE_ANNOTATIONS)\n',577 Constant('PyCF_MASK', '(CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | CO_FUTURE_GENERATOR_STOP | CO_FUTURE_ANNOTATIONS)'),578 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),579 (20, '#define PyCF_MASK_OBSOLETE (CO_NESTED)\n',580 Constant('PyCF_MASK_OBSOLETE', '(CO_NESTED)'),581 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),582 (21, '#define PyCF_SOURCE_IS_UTF8 0x0100\n',583 Constant('PyCF_SOURCE_IS_UTF8', ' 0x0100'),584 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),585 (22, '#define PyCF_DONT_IMPLY_DEDENT 0x0200\n',586 Constant('PyCF_DONT_IMPLY_DEDENT', '0x0200'),587 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),588 (23, '#define PyCF_ONLY_AST 0x0400\n',589 Constant('PyCF_ONLY_AST', '0x0400'),590 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),591 (24, '#define PyCF_IGNORE_COOKIE 0x0800\n',592 Constant('PyCF_IGNORE_COOKIE', '0x0800'),593 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),594 (25, '#define PyCF_TYPE_COMMENTS 0x1000\n',595 Constant('PyCF_TYPE_COMMENTS', '0x1000'),596 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),597 (26, '#define PyCF_ALLOW_TOP_LEVEL_AWAIT 0x2000\n',598 Constant('PyCF_ALLOW_TOP_LEVEL_AWAIT', '0x2000'),599 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),600 (27, '\n',601 None,602 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),603 (28, '#ifndef Py_LIMITED_API\n',604 IfDirective('ifndef', 'Py_LIMITED_API'),605 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),606 (29, 'typedef struct {\n',607 None,608 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', '! defined(Py_LIMITED_API)')),609 (30, ' int cf_flags; \n',610 None,611 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', '! defined(Py_LIMITED_API)')),612 (31, ' int cf_feature_version; \n',613 None,614 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', '! defined(Py_LIMITED_API)')),615 (32, '} PyCompilerFlags;\n',616 None,617 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', '! defined(Py_LIMITED_API)')),618 (33, '#endif\n',619 OtherDirective('endif', None),620 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', '! defined(Py_LIMITED_API)')),621 (34, '\n',622 None,623 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),624 (35, ' \n',625 None,626 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),627 (36, '\n',628 None,629 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),630 (37, 'typedef struct {\n',631 None,632 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),633 (38, ' int ff_features; \n',634 None,635 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),636 (39, ' int ff_lineno; \n',637 None,638 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),639 (40, '} PyFutureFeatures;\n',640 None,641 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),642 (41, '\n',643 None,644 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),645 (42, '#define FUTURE_NESTED_SCOPES "nested_scopes"\n',646 Constant('FUTURE_NESTED_SCOPES', '"nested_scopes"'),647 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),648 (43, '#define FUTURE_GENERATORS "generators"\n',649 Constant('FUTURE_GENERATORS', '"generators"'),650 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),651 (44, '#define FUTURE_DIVISION "division"\n',652 Constant('FUTURE_DIVISION', '"division"'),653 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),654 (45, '#define FUTURE_ABSOLUTE_IMPORT "absolute_import"\n',655 Constant('FUTURE_ABSOLUTE_IMPORT', '"absolute_import"'),656 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),657 (46, '#define FUTURE_WITH_STATEMENT "with_statement"\n',658 Constant('FUTURE_WITH_STATEMENT', '"with_statement"'),659 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),660 (47, '#define FUTURE_PRINT_FUNCTION "print_function"\n',661 Constant('FUTURE_PRINT_FUNCTION', '"print_function"'),662 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),663 (48, '#define FUTURE_UNICODE_LITERALS "unicode_literals"\n',664 Constant('FUTURE_UNICODE_LITERALS', '"unicode_literals"'),665 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),666 (49, '#define FUTURE_BARRY_AS_BDFL "barry_as_FLUFL"\n',667 Constant('FUTURE_BARRY_AS_BDFL', '"barry_as_FLUFL"'),668 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),669 (50, '#define FUTURE_GENERATOR_STOP "generator_stop"\n',670 Constant('FUTURE_GENERATOR_STOP', '"generator_stop"'),671 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),672 (51, '#define FUTURE_ANNOTATIONS "annotations"\n',673 Constant('FUTURE_ANNOTATIONS', '"annotations"'),674 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),675 (52, '\n',676 None,677 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),678 (53, 'struct _mod; \n',679 None,680 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),681 (54, '#define PyAST_Compile(mod, s, f, ar) PyAST_CompileEx(mod, s, f, -1, ar)\n',682 Macro('PyAST_Compile', ('mod', 's', 'f', 'ar'), 'PyAST_CompileEx(mod, s, f, -1, ar)'),683 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),684 (55, 'PyAPI_FUNC(PyCodeObject *) PyAST_CompileEx(\n',685 None,686 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),687 (56, ' struct _mod *mod,\n',688 None,689 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),690 (57, ' const char *filename, \n',691 None,692 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),693 (58, ' PyCompilerFlags *flags,\n',694 None,695 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),696 (59, ' int optimize,\n',697 None,698 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),699 (60, ' PyArena *arena);\n',700 None,701 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),702 (61, 'PyAPI_FUNC(PyCodeObject *) PyAST_CompileObject(\n',703 None,704 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),705 (62, ' struct _mod *mod,\n',706 None,707 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),708 (63, ' PyObject *filename,\n',709 None,710 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),711 (64, ' PyCompilerFlags *flags,\n',712 None,713 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),714 (65, ' int optimize,\n',715 None,716 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),717 (66, ' PyArena *arena);\n',718 None,719 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),720 (67, 'PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromAST(\n',721 None,722 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),723 (68, ' struct _mod * mod,\n',724 None,725 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),726 (69, ' const char *filename \n',727 None,728 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),729 (70, ' );\n',730 None,731 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),732 (71, 'PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromASTObject(\n',733 None,734 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),735 (72, ' struct _mod * mod,\n',736 None,737 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),738 (73, ' PyObject *filename\n',739 None,740 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),741 (74, ' );\n',742 None,743 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),744 (75, '\n',745 None,746 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),747 (76, ' \n',748 None,749 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),750 (77, 'PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name);\n',751 None,752 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),753 (78, '\n',754 None,755 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),756 (79, '#define PY_INVALID_STACK_EFFECT INT_MAX\n',757 Constant('PY_INVALID_STACK_EFFECT', 'INT_MAX'),758 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),759 (80, 'PyAPI_FUNC(int) PyCompile_OpcodeStackEffect(int opcode, int oparg);\n',760 None,761 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),762 (81, 'PyAPI_FUNC(int) PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump);\n',763 None,764 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),765 (82, '\n',766 None,767 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),768 (83, 'PyAPI_FUNC(int) _PyAST_Optimize(struct _mod *, PyArena *arena, int optimize);\n',769 None,770 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),771 (84, '\n',772 None,773 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),774 (85, '#ifdef __cplusplus\n',775 IfDirective('ifdef', '__cplusplus'),776 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),777 (86, '}\n',778 None,779 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', 'defined(__cplusplus)')),780 (87, '#endif\n',781 OtherDirective('endif', None),782 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)', 'defined(__cplusplus)')),783 (88, '\n',784 None,785 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),786 (89, '#endif \n',787 OtherDirective('endif', None),788 ('! defined(Py_COMPILE_H)', '! defined(Py_LIMITED_API)')),789 (90, '\n',790 None,791 ('! defined(Py_COMPILE_H)',)),792 (91, ' \n',793 None,794 ('! defined(Py_COMPILE_H)',)),795 (92, '#define Py_single_input 256\n',796 Constant('Py_single_input', '256'),797 ('! defined(Py_COMPILE_H)',)),798 (93, '#define Py_file_input 257\n',799 Constant('Py_file_input', '257'),800 ('! defined(Py_COMPILE_H)',)),801 (94, '#define Py_eval_input 258\n',802 Constant('Py_eval_input', '258'),803 ('! defined(Py_COMPILE_H)',)),804 (95, '#define Py_func_type_input 345\n',805 Constant('Py_func_type_input', '345'),806 ('! defined(Py_COMPILE_H)',)),807 (96, '\n',808 None,809 ('! defined(Py_COMPILE_H)',)),810 (97, '#endif ',811 OtherDirective('endif', None),812 ('! defined(Py_COMPILE_H)',)),813 ])814 self.check_calls(815 ('_parse_directive', '#ifndef Py_COMPILE_H'),816 ('_parse_directive', '#define Py_COMPILE_H'),817 ('_parse_directive', '#ifndef Py_LIMITED_API'),818 ('_parse_directive', '#include "code.h"'),819 ('_parse_directive', '#ifdef __cplusplus'),820 ('_parse_directive', '#endif'),821 ('_parse_directive', '#define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | CO_FUTURE_GENERATOR_STOP | CO_FUTURE_ANNOTATIONS)'),822 ('_parse_directive', '#define PyCF_MASK_OBSOLETE (CO_NESTED)'),823 ('_parse_directive', '#define PyCF_SOURCE_IS_UTF8 0x0100'),824 ('_parse_directive', '#define PyCF_DONT_IMPLY_DEDENT 0x0200'),825 ('_parse_directive', '#define PyCF_ONLY_AST 0x0400'),826 ('_parse_directive', '#define PyCF_IGNORE_COOKIE 0x0800'),827 ('_parse_directive', '#define PyCF_TYPE_COMMENTS 0x1000'),828 ('_parse_directive', '#define PyCF_ALLOW_TOP_LEVEL_AWAIT 0x2000'),829 ('_parse_directive', '#ifndef Py_LIMITED_API'),830 ('_parse_directive', '#endif'),831 ('_parse_directive', '#define FUTURE_NESTED_SCOPES "nested_scopes"'),832 ('_parse_directive', '#define FUTURE_GENERATORS "generators"'),833 ('_parse_directive', '#define FUTURE_DIVISION "division"'),834 ('_parse_directive', '#define FUTURE_ABSOLUTE_IMPORT "absolute_import"'),835 ('_parse_directive', '#define FUTURE_WITH_STATEMENT "with_statement"'),836 ('_parse_directive', '#define FUTURE_PRINT_FUNCTION "print_function"'),837 ('_parse_directive', '#define FUTURE_UNICODE_LITERALS "unicode_literals"'),838 ('_parse_directive', '#define FUTURE_BARRY_AS_BDFL "barry_as_FLUFL"'),839 ('_parse_directive', '#define FUTURE_GENERATOR_STOP "generator_stop"'),840 ('_parse_directive', '#define FUTURE_ANNOTATIONS "annotations"'),841 ('_parse_directive', '#define PyAST_Compile(mod, s, f, ar) PyAST_CompileEx(mod, s, f, -1, ar)'),842 ('_parse_directive', '#define PY_INVALID_STACK_EFFECT INT_MAX'),843 ('_parse_directive', '#ifdef __cplusplus'),844 ('_parse_directive', '#endif'),845 ('_parse_directive', '#endif'),846 ('_parse_directive', '#define Py_single_input 256'),847 ('_parse_directive', '#define Py_file_input 257'),848 ('_parse_directive', '#define Py_eval_input 258'),849 ('_parse_directive', '#define Py_func_type_input 345'),850 ('_parse_directive', '#endif'),851 )852class ParseDirectiveTests(unittest.TestCase):853 def test_directives(self):854 tests = [855 # includes856 ('#include "internal/pycore_pystate.h"', Include('"internal/pycore_pystate.h"')),857 ('#include <stdio>', Include('<stdio>')),858 # defines859 ('#define SPAM int', Constant('SPAM', 'int')),860 ('#define SPAM', Constant('SPAM', '')),861 ('#define SPAM(x, y) run(x, y)', Macro('SPAM', ('x', 'y'), 'run(x, y)')),862 ('#undef SPAM', None),863 # conditionals864 ('#if SPAM', IfDirective('if', 'SPAM')),865 # XXX complex conditionls866 ('#ifdef SPAM', IfDirective('ifdef', 'SPAM')),867 ('#ifndef SPAM', IfDirective('ifndef', 'SPAM')),868 ('#elseif SPAM', IfDirective('elseif', 'SPAM')),869 # XXX complex conditionls870 ('#else', OtherDirective('else', '')),871 ('#endif', OtherDirective('endif', '')),872 # other873 ('#error oops!', None),874 ('#warning oops!', None),875 ('#pragma ...', None),876 ('#__FILE__ ...', None),877 ('#__LINE__ ...', None),878 ('#__DATE__ ...', None),879 ('#__TIME__ ...', None),880 ('#__TIMESTAMP__ ...', None),881 # extra whitespace882 (' # include <stdio> ', Include('<stdio>')),883 ('#else ', OtherDirective('else', '')),884 ('#endif ', OtherDirective('endif', '')),885 ('#define SPAM int ', Constant('SPAM', 'int')),886 ('#define SPAM ', Constant('SPAM', '')),887 ]888 for line, expected in tests:889 if expected is None:890 kind, _, text = line[1:].partition(' ')891 expected = OtherDirective(kind, text)892 with self.subTest(line):893 directive = parse_directive(line)894 self.assertEqual(directive, expected)895 def test_bad_directives(self):896 tests = [897 # valid directives with bad text898 '#define 123',899 '#else spam',900 '#endif spam',901 ]902 for kind in PreprocessorDirective.KINDS:903 # missing leading "#"904 tests.append(kind)905 if kind in ('else', 'endif'):906 continue907 # valid directives with missing text908 tests.append('#' + kind)909 tests.append('#' + kind + ' ')910 for line in tests:911 with self.subTest(line):912 with self.assertRaises(ValueError):913 parse_directive(line)914 def test_not_directives(self):915 tests = [916 '',917 ' ',918 'directive',919 'directive?',920 '???',921 ]922 for line in tests:923 with self.subTest(line):924 with self.assertRaises(ValueError):925 parse_directive(line)926class ConstantTests(unittest.TestCase):927 def test_type(self):928 directive = Constant('SPAM', '123')929 self.assertIs(type(directive), Constant)930 self.assertIsInstance(directive, PreprocessorDirective)931 def test_attrs(self):932 d = Constant('SPAM', '123')933 kind, name, value = d.kind, d.name, d.value934 self.assertEqual(kind, 'define')935 self.assertEqual(name, 'SPAM')936 self.assertEqual(value, '123')937 def test_text(self):938 tests = [939 (('SPAM', '123'), 'SPAM 123'),...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from khayyam import SATURDAY, MONDAY3from khayyam.compat import get_unicode4from khayyam.formatting import constants as consts5from .base import Directive, CompositeDateDirective, CompositeDatetimeDirective6from .day import \7 PersianDayDirective, \8 DayOfYearDirective, \9 PersianDayOfYearDirective10from .month import PersianMonthDirective11from .ampm import BaseAmPmDirective, AmPmDirective, AmPmASCIIDirective12from .time import \13 PersianMicrosecondDirective, \14 PersianHour12Directive, \15 PersianHour24Directive, \16 PersianSecondDirective, \17 PersianMinuteDirective18from .year import \19 ShortYearDirective, \20 PersianYearDirective, \21 PersianShortYearDirective22from .tz import UTCOffsetDirective, TimezoneNameDirective, PersianUTCOffsetDirective23__author__ = 'vahid'24DATE_FORMAT_DIRECTIVES = [25 # YEAR26 Directive('Y', 'year', consts.YEAR_REGEX, int, lambda d: '%.4d' % d.year),27 ShortYearDirective('y', 'shortyear', consts.SHORT_YEAR_REGEX, int),28 PersianYearDirective('N', 'persianyear', consts.PERSIAN_YEAR_REGEX),29 PersianYearDirective('O', 'persianyearzeropadded', consts.PERSIAN_YEAR_ZERO_PADDED_REGEX,30 zero_padding=True, zero_padding_length=4),31 PersianShortYearDirective('n', 'persianshortyear', consts.PERSIAN_SHORT_YEAR_REGEX, ),32 PersianShortYearDirective('u', 'persianshortyearzeropadded', consts.PERSIAN_SHORT_YEAR_ZERO_PADDED_REGEX,33 zero_padding=True),34 # MONTH35 PersianMonthDirective('R', 'persianmonth', consts.PERSIAN_MONTH_REGEX),36 PersianMonthDirective('P', 'persianmonthzeropadded', consts.PERSIAN_MONTH_ZERO_PADDED_REGEX, zero_padding=True),37 Directive('m', 'month', consts.MONTH_REGEX, int, lambda d: '%.2d' % d.month),38 Directive('b', 'monthabbr', consts.PERSIAN_MONTH_ABBRS_REGEX, get_unicode, lambda d: d.monthabbr(),39 lambda ctx, f: ctx.update(40 {'month': [(k, v) for k, v in consts.PERSIAN_MONTH_ABBRS.items() if v == ctx['monthabbr']][0][0]})),41 Directive('B', 'monthname', consts.PERSIAN_MONTH_NAMES_REGEX, get_unicode, lambda d: d.monthname(),42 lambda ctx, f: ctx.update(43 {'month': [(k, v) for k, v in consts.PERSIAN_MONTH_NAMES.items() if v == ctx['monthname']][0][0]})),44 Directive('g', 'monthabbr_ascii', consts.PERSIAN_MONTH_ABBRS_ASCII_REGEX, get_unicode,45 lambda d: d.monthabbr_ascii(),46 lambda ctx, f: ctx.update({'month': [(k, v) for k, v in consts.PERSIAN_MONTH_ABBRS_ASCII.items() if47 v == ctx['monthabbr_ascii']][0][0]})),48 Directive('G', 'monthnameascii', consts.PERSIAN_MONTH_NAMES_ASCII_REGEX, get_unicode,49 lambda d: d.monthnameascii(),50 lambda ctx, f: ctx.update({'month': [(k, v) for k, v in consts.PERSIAN_MONTH_NAMES_ASCII.items() if51 v == ctx['monthnameascii']][0][0]})),52 # DAY53 Directive('d', 'day', consts.DAY_REGEX, int, lambda d: '%.2d' % d.day),54 PersianDayDirective('D', 'persianday', consts.PERSIAN_DAY_REGEX),55 PersianDayDirective('K', 'persiandayzeropadded', consts.PERSIAN_DAY_ZERO_PADDED_REGEX, zero_padding=True),56 DayOfYearDirective('j', 'dayofyear', consts.DAY_OF_YEAR_REGEX, int),57 PersianDayOfYearDirective('J', 'persiandayofyear', consts.PERSIAN_DAY_OF_YEAR_REGEX),58 PersianDayOfYearDirective('V', 'persiandayofyearzeropadded', consts.PERSIAN_DAY_OF_YEAR_ZERO_PADDED_REGEX,59 zero_padding=True, zero_padding_length=3),60 # WEEK61 Directive('w', 'weekday', consts.WEEKDAY_REGEX, int, lambda d: '%d' % d.weekday()),62 Directive('W', 'weekofyear', consts.WEEK_OF_YEAR_REGEX, int, lambda d: '%.2d' % d.weekofyear(SATURDAY)),63 Directive('U', 'weekofyear', consts.WEEK_OF_YEAR_REGEX, int, lambda d: '%.2d' % d.weekofyear(MONDAY)),64 Directive('a', 'weekdayabbr', consts.PERSIAN_WEEKDAY_ABBRS_REGEX, get_unicode, lambda d: d.weekdayabbr()),65 Directive('A', 'weekdayname', consts.PERSIAN_WEEKDAY_NAMES_REGEX, get_unicode, lambda d: d.weekdayname()),66 Directive('e', 'weekdayabbrascii', consts.PERSIAN_WEEKDAY_ABBRS_ASCII_REGEX, get_unicode,67 lambda d: d.weekdayabbrascii()),68 Directive('E', 'weekdaynameascii', consts.PERSIAN_WEEKDAY_NAMES_ASCII_REGEX, get_unicode,69 lambda d: d.weekdaynameascii()),70 Directive('T', 'englishweekdaynameascii', consts.ENGLISH_WEEKDAY_NAMES_ASCII_REGEX, get_unicode,71 lambda d: d.englishweekdaynameascii()),72 # COMPOSITE73 CompositeDateDirective('x', 'localdateformat', '%s %s %s %s' % (74 consts.PERSIAN_WEEKDAY_NAMES_REGEX,75 consts.PERSIAN_DAY_REGEX,76 consts.PERSIAN_MONTH_NAMES_REGEX,77 consts.PERSIAN_YEAR_REGEX78 ), "%A %D %B %N"),79 # MISCELLANEOUS80 Directive('%', 'percent', '%', None, lambda d: '%', ),81]82TIME_FORMAT_DIRECTIVES = [83 # HOUR84 Directive('H', 'hour', consts.HOUR24_REGEX, int, lambda d: '%.2d' % d.hour),85 PersianHour24Directive('k', 'persianhour24', consts.PERSIAN_HOUR24_REGEX),86 PersianHour24Directive('h', 'persianhour24zeropadded', consts.PERSIAN_HOUR24_ZERO_PADDED_REGEX, zero_padding=True),87 Directive('I', 'hour12', consts.HOUR12_REGEX, int, lambda d: '%.2d' % d.hour12()),88 PersianHour12Directive('l', 'persianhour12', consts.PERSIAN_HOUR12_REGEX),89 PersianHour12Directive('i', 'persianhour12zeropadded', consts.PERSIAN_HOUR12_ZERO_PADDED_REGEX, zero_padding=True),90 # MINUTE91 Directive('M', 'minute', consts.MINUTE_REGEX, int, lambda d: '%.2d' % d.minute),92 PersianMinuteDirective('v', 'persianminute', consts.PERSIAN_MINUTE_REGEX),93 PersianMinuteDirective('r', 'persianminutezeropadded', consts.PERSIAN_MINUTE_ZERO_PADDED_REGEX, zero_padding=True),94 # SECOND95 Directive('S', 'second', consts.SECOND_REGEX, int, lambda d: '%.2d' % d.second),96 PersianSecondDirective('L', 'persiansecond', consts.PERSIAN_SECOND_REGEX),97 PersianSecondDirective('s', 'persiansecondzeropadded', consts.PERSIAN_SECOND_ZERO_PADDED_REGEX, zero_padding=True),98 # MICROSECOND99 Directive('f', 'microsecond', consts.MICROSECOND_REGEX, int, lambda d: '%.6d' % d.microsecond),100 PersianMicrosecondDirective('F', 'persianmicrosecond', consts.PERSIAN_MICROSECOND_REGEX),101 # AMP-PM102 AmPmDirective('p', 'ampm', consts.AM_PM_REGEX),103 AmPmASCIIDirective('t', 'ampmascii', consts.AM_PM_ASCII_REGEX),104 # TIMEZONE105 UTCOffsetDirective('z', 'utcoffset', consts.UTC_OFFSET_FORMAT_REGEX, get_unicode),106 TimezoneNameDirective('Z', 'tzname', consts.TZ_NAME_FORMAT_REGEX, get_unicode),107 PersianUTCOffsetDirective('o', 'persianutcoffset', consts.PERSIAN_UTC_OFFSET_FORMAT_REGEX),108 # COMPOSITE109 CompositeDatetimeDirective('c', 'localshortdatetimeformat', '%s %s %s %s %s:%s' % (110 consts.PERSIAN_WEEKDAY_ABBRS_REGEX,111 consts.PERSIAN_DAY_REGEX,112 consts.PERSIAN_MONTH_ABBRS_REGEX,113 consts.PERSIAN_SHORT_YEAR_REGEX,114 consts.PERSIAN_HOUR24_REGEX,115 consts.PERSIAN_MINUTE_REGEX116 ), "%a %D %b %n %k:%v"),117 CompositeDatetimeDirective('C', 'localdatetimeformat', '%s %s %s %s %s:%s:%s %s' % (118 consts.PERSIAN_WEEKDAY_NAMES_REGEX,119 consts.PERSIAN_DAY_REGEX,120 consts.PERSIAN_MONTH_NAMES_REGEX,121 consts.PERSIAN_YEAR_REGEX,122 consts.PERSIAN_HOUR12_ZERO_PADDED_REGEX,123 consts.PERSIAN_MINUTE_ZERO_PADDED_REGEX,124 consts.PERSIAN_SECOND_ZERO_PADDED_REGEX,125 consts.AM_PM_REGEX126 ), "%A %D %B %N %i:%r:%s %p"),127 CompositeDatetimeDirective('q', 'localshortdatetimeformatascii', '%s %s %s %s %s:%s' % (128 consts.PERSIAN_WEEKDAY_ABBRS_ASCII_REGEX,129 consts.DAY_REGEX,130 consts.PERSIAN_MONTH_ABBRS_ASCII_REGEX,131 consts.SHORT_YEAR_REGEX,132 consts.HOUR24_REGEX,133 consts.MINUTE_REGEX134 ), "%e %d %g %y %H:%M"),135 CompositeDatetimeDirective('Q', 'localdatetimeformatascii', '%s %s %s %s %s:%s:%s %s' % (136 consts.PERSIAN_WEEKDAY_NAMES_ASCII_REGEX,137 consts.DAY_REGEX,138 consts.PERSIAN_MONTH_NAMES_ASCII_REGEX,139 consts.YEAR_REGEX,140 consts.HOUR12_REGEX,141 consts.MINUTE_REGEX,142 consts.SECOND_REGEX,143 consts.AM_PM_ASCII_REGEX144 ), "%E %d %G %Y %I:%M:%S %t"),145 CompositeDatetimeDirective('X', 'localtimeformat', '%s:%s:%s %s' % (146 consts.PERSIAN_HOUR12_ZERO_PADDED_REGEX,147 consts.PERSIAN_MINUTE_ZERO_PADDED_REGEX,148 consts.PERSIAN_SECOND_ZERO_PADDED_REGEX,149 consts.AM_PM_REGEX150 ), "%i:%r:%s %p"),151]152DATETIME_FORMAT_DIRECTIVES = DATE_FORMAT_DIRECTIVES + TIME_FORMAT_DIRECTIVES153__all__ = [154 'Directive',155 'PersianDayDirective',156 'DayOfYearDirective',157 'PersianDayOfYearDirective',158 'PersianMonthDirective',159 'AmPmDirective',160 'AmPmASCIIDirective',161 'PersianMicrosecondDirective',162 'PersianHour12Directive',163 'PersianHour24Directive',164 'PersianSecondDirective',165 'PersianMinuteDirective',166 'ShortYearDirective',167 'PersianYearDirective',168 'PersianShortYearDirective',169 'UTCOffsetDirective',170 'TimezoneNameDirective',171 'PersianUTCOffsetDirective',172 'DATE_FORMAT_DIRECTIVES',173 'TIME_FORMAT_DIRECTIVES',174 'DATETIME_FORMAT_DIRECTIVES',175]176"""177Available directives: T...

Full Screen

Full Screen

test_directive_definition.py

Source:test_directive_definition.py Github

copy

Full Screen

1import pytest2from tartiflette.language.ast import DirectiveDefinitionNode3def test_directivedefinitionnode__init__():4 directive_definition_node = DirectiveDefinitionNode(5 name="directiveDefinitionName",6 locations="directiveDefinitionLocations",7 description="directiveDefinitionDescription",8 arguments="directiveDefinitionArguments",9 location="directiveDefinitionLocation",10 )11 assert directive_definition_node.name == "directiveDefinitionName"12 assert (13 directive_definition_node.locations == "directiveDefinitionLocations"14 )15 assert (16 directive_definition_node.description17 == "directiveDefinitionDescription"18 )19 assert (20 directive_definition_node.arguments == "directiveDefinitionArguments"21 )22 assert directive_definition_node.location == "directiveDefinitionLocation"23@pytest.mark.parametrize(24 "directive_definition_node,other,expected",25 [26 (27 DirectiveDefinitionNode(28 name="directiveDefinitionName",29 locations="directiveDefinitionLocations",30 description="directiveDefinitionDescription",31 arguments="directiveDefinitionArguments",32 location="directiveDefinitionLocation",33 ),34 Ellipsis,35 False,36 ),37 (38 DirectiveDefinitionNode(39 name="directiveDefinitionName",40 locations="directiveDefinitionLocations",41 description="directiveDefinitionDescription",42 arguments="directiveDefinitionArguments",43 location="directiveDefinitionLocation",44 ),45 DirectiveDefinitionNode(46 name="directiveDefinitionNameBis",47 locations="directiveDefinitionLocations",48 description="directiveDefinitionDescription",49 arguments="directiveDefinitionArguments",50 location="directiveDefinitionLocation",51 ),52 False,53 ),54 (55 DirectiveDefinitionNode(56 name="directiveDefinitionName",57 locations="directiveDefinitionLocations",58 description="directiveDefinitionDescription",59 arguments="directiveDefinitionArguments",60 location="directiveDefinitionLocation",61 ),62 DirectiveDefinitionNode(63 name="directiveDefinitionName",64 locations="directiveDefinitionLocationsBis",65 description="directiveDefinitionDescription",66 arguments="directiveDefinitionArguments",67 location="directiveDefinitionLocation",68 ),69 False,70 ),71 (72 DirectiveDefinitionNode(73 name="directiveDefinitionName",74 locations="directiveDefinitionLocations",75 description="directiveDefinitionDescription",76 arguments="directiveDefinitionArguments",77 location="directiveDefinitionLocation",78 ),79 DirectiveDefinitionNode(80 name="directiveDefinitionName",81 locations="directiveDefinitionLocations",82 description="directiveDefinitionDescriptionBis",83 arguments="directiveDefinitionArguments",84 location="directiveDefinitionLocation",85 ),86 False,87 ),88 (89 DirectiveDefinitionNode(90 name="directiveDefinitionName",91 locations="directiveDefinitionLocations",92 description="directiveDefinitionDescription",93 arguments="directiveDefinitionArguments",94 location="directiveDefinitionLocation",95 ),96 DirectiveDefinitionNode(97 name="directiveDefinitionName",98 locations="directiveDefinitionLocations",99 description="directiveDefinitionDescription",100 arguments="directiveDefinitionArgumentsBis",101 location="directiveDefinitionLocation",102 ),103 False,104 ),105 (106 DirectiveDefinitionNode(107 name="directiveDefinitionName",108 locations="directiveDefinitionLocations",109 description="directiveDefinitionDescription",110 arguments="directiveDefinitionArguments",111 location="directiveDefinitionLocation",112 ),113 DirectiveDefinitionNode(114 name="directiveDefinitionName",115 locations="directiveDefinitionLocations",116 description="directiveDefinitionDescription",117 arguments="directiveDefinitionArguments",118 location="directiveDefinitionLocationBis",119 ),120 False,121 ),122 (123 DirectiveDefinitionNode(124 name="directiveDefinitionName",125 locations="directiveDefinitionLocations",126 description="directiveDefinitionDescription",127 arguments="directiveDefinitionArguments",128 location="directiveDefinitionLocation",129 ),130 DirectiveDefinitionNode(131 name="directiveDefinitionName",132 locations="directiveDefinitionLocations",133 description="directiveDefinitionDescription",134 arguments="directiveDefinitionArguments",135 location="directiveDefinitionLocation",136 ),137 True,138 ),139 ],140)141def test_directivedefinitionnode__eq__(142 directive_definition_node, other, expected143):144 assert (directive_definition_node == other) is expected145@pytest.mark.parametrize(146 "directive_definition_node,expected",147 [148 (149 DirectiveDefinitionNode(150 name="directiveDefinitionName",151 locations="directiveDefinitionLocations",152 description="directiveDefinitionDescription",153 arguments="directiveDefinitionArguments",154 location="directiveDefinitionLocation",155 ),156 "DirectiveDefinitionNode("157 "description='directiveDefinitionDescription', "158 "name='directiveDefinitionName', "159 "arguments='directiveDefinitionArguments', "160 "locations='directiveDefinitionLocations', "161 "location='directiveDefinitionLocation')",162 )163 ],164)165def test_directivedefinitionnode__repr__(directive_definition_node, expected):...

Full Screen

Full Screen

test_test_directives.py

Source:test_test_directives.py Github

copy

Full Screen

1#! /usr/bin/env python2# $Id: test_test_directives.py 4564 2006-05-21 20:44:42Z wiemann $3# Author: David Goodger <goodger@python.org>4# Copyright: This module has been placed in the public domain.5"""6Tests for misc.py test directives.7"""8from __init__ import DocutilsTestSupport9def suite():10 s = DocutilsTestSupport.ParserTestSuite()11 s.generateTests(totest)12 return s13totest = {}14totest['test_directives'] = [15["""\16.. reStructuredText-test-directive::17Paragraph.18""",19"""\20<document source="test data">21 <system_message level="1" line="1" source="test data" type="INFO">22 <paragraph>23 Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: None24 <paragraph>25 Paragraph.26"""],27["""\28.. reStructuredText-test-directive ::29An optional space before the "::".30""",31"""\32<document source="test data">33 <system_message level="1" line="1" source="test data" type="INFO">34 <paragraph>35 Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content: None36 <paragraph>37 An optional space before the "::".38"""],39["""\40.. reStructuredText-test-directive:: argument41Paragraph.42""",43"""\44<document source="test data">45 <system_message level="1" line="1" source="test data" type="INFO">46 <paragraph>47 Directive processed. Type="reStructuredText-test-directive", arguments=['argument'], options={}, content: None48 <paragraph>49 Paragraph.50"""],51["""\52.. reStructuredText-test-directive:: argument53 :option: value54Paragraph.55""",56"""\57<document source="test data">58 <system_message level="1" line="1" source="test data" type="INFO">59 <paragraph>60 Directive processed. Type="reStructuredText-test-directive", arguments=['argument'], options={'option': 'value'}, content: None61 <paragraph>62 Paragraph.63"""],64["""\65.. reStructuredText-test-directive:: :option: value66Paragraph.67""",68"""\69<document source="test data">70 <system_message level="1" line="1" source="test data" type="INFO">71 <paragraph>72 Directive processed. Type="reStructuredText-test-directive", arguments=[], options={'option': 'value'}, content: None73 <paragraph>74 Paragraph.75"""],76["""\77.. reStructuredText-test-directive:: :option:78Paragraph.79""",80"""\81<document source="test data">82 <system_message level="3" line="1" source="test data" type="ERROR">83 <paragraph>84 Error in "reStructuredText-test-directive" directive:85 invalid option value: (option: "option"; value: None)86 argument required but none supplied.87 <literal_block xml:space="preserve">88 .. reStructuredText-test-directive:: :option:89 <paragraph>90 Paragraph.91"""],92["""\93.. reStructuredText-test-directive::94 Directive block contains one paragraph, with a blank line before.95Paragraph.96""",97"""\98<document source="test data">99 <system_message level="1" line="1" source="test data" type="INFO">100 <paragraph>101 Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content:102 <literal_block xml:space="preserve">103 Directive block contains one paragraph, with a blank line before.104 <paragraph>105 Paragraph.106"""],107["""\108.. reStructuredText-test-directive::109 Directive block contains one paragraph, with two blank lines before.110Paragraph.111""",112"""\113<document source="test data">114 <system_message level="1" line="1" source="test data" type="INFO">115 <paragraph>116 Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content:117 <literal_block xml:space="preserve">118 Directive block contains one paragraph, with two blank lines before.119 <paragraph>120 Paragraph.121"""],122["""\123.. reStructuredText-test-directive::124 Directive block contains one paragraph, no blank line before.125Paragraph.126""",127"""\128<document source="test data">129 <system_message level="1" line="1" source="test data" type="INFO">130 <paragraph>131 Directive processed. Type="reStructuredText-test-directive", arguments=['Directive block contains one paragraph, no blank line before.'], options={}, content: None132 <paragraph>133 Paragraph.134"""],135["""\136.. reStructuredText-test-directive::137 block138no blank line.139Paragraph.140""",141"""\142<document source="test data">143 <system_message level="1" line="1" source="test data" type="INFO">144 <paragraph>145 Directive processed. Type="reStructuredText-test-directive", arguments=['block'], options={}, content: None146 <system_message level="2" line="3" source="test data" type="WARNING">147 <paragraph>148 Explicit markup ends without a blank line; unexpected unindent.149 <paragraph>150 no blank line.151 <paragraph>152 Paragraph.153"""],154["""\155.. reStructuredText-test-directive:: argument156 :option: * value1157 * value2158Paragraph.159""",160"""\161<document source="test data">162 <system_message level="1" line="1" source="test data" type="INFO">163 <paragraph>164 Directive processed. Type="reStructuredText-test-directive", arguments=['argument'], options={'option': '* value1\\n* value2'}, content: None165 <paragraph>166 Paragraph.167"""],168["""\169.. reStructuredText-test-directive::170 Directive \\block \\*contains* \\\\backslashes.171""",172"""\173<document source="test data">174 <system_message level="1" line="1" source="test data" type="INFO">175 <paragraph>176 Directive processed. Type="reStructuredText-test-directive", arguments=[], options={}, content:177 <literal_block xml:space="preserve">178 Directive \\block \\*contains* \\\\backslashes.179"""],180]181if __name__ == '__main__':182 import unittest...

Full Screen

Full Screen

test_block.py

Source:test_block.py Github

copy

Full Screen

1from nose.tools import assert_equals, assert_true, assert_false2from tests.asserts import assert_is_instance, assert_is_none, assert_is_not_none3from gixy.parser.nginx_parser import NginxParser4from gixy.directives.block import *5# TODO(buglloc): what about include block?6def _get_parsed(config):7 root = NginxParser(cwd='', allow_includes=False).parse(config)8 return root.children[0]9def test_block():10 config = 'some {some;}'11 directive = _get_parsed(config)12 assert_is_instance(directive, Block)13 assert_true(directive.is_block)14 assert_true(directive.self_context)15 assert_false(directive.provide_variables)16def test_http():17 config = '''18http {19 default_type application/octet-stream;20 sendfile on;21 keepalive_timeout 65;22}23 '''24 directive = _get_parsed(config)25 assert_is_instance(directive, HttpBlock)26 assert_true(directive.is_block)27 assert_true(directive.self_context)28 assert_false(directive.provide_variables)29def test_server():30 config = '''31server {32 listen 80;33 server_name _;34 server_name cool.io;35}36 '''37 directive = _get_parsed(config)38 assert_is_instance(directive, ServerBlock)39 assert_true(directive.is_block)40 assert_true(directive.self_context)41 assert_equals([d.args[0] for d in directive.get_names()], ['_', 'cool.io'])42 assert_false(directive.provide_variables)43def test_location():44 config = '''45location / {46}47 '''48 directive = _get_parsed(config)49 assert_is_instance(directive, LocationBlock)50 assert_true(directive.is_block)51 assert_true(directive.self_context)52 assert_true(directive.provide_variables)53 assert_is_none(directive.modifier)54 assert_equals(directive.path, '/')55 assert_false(directive.is_internal)56def test_location_internal():57 config = '''58location / {59 internal;60}61 '''62 directive = _get_parsed(config)63 assert_is_instance(directive, LocationBlock)64 assert_true(directive.is_internal)65def test_location_modifier():66 config = '''67location = / {68}69 '''70 directive = _get_parsed(config)71 assert_is_instance(directive, LocationBlock)72 assert_equals(directive.modifier, '=')73 assert_equals(directive.path, '/')74def test_if():75 config = '''76if ($some) {77}78 '''79 directive = _get_parsed(config)80 assert_is_instance(directive, IfBlock)81 assert_true(directive.is_block)82 assert_false(directive.self_context)83 assert_false(directive.provide_variables)84 assert_equals(directive.variable, '$some')85 assert_is_none(directive.operand)86 assert_is_none(directive.value)87def test_if_modifier():88 config = '''89if (-f /some) {90}91 '''92 directive = _get_parsed(config)93 assert_is_instance(directive, IfBlock)94 assert_equals(directive.operand, '-f')95 assert_equals(directive.value, '/some')96 assert_is_none(directive.variable)97def test_if_variable():98 config = '''99if ($http_some = '/some') {100}101 '''102 directive = _get_parsed(config)103 assert_is_instance(directive, IfBlock)104 assert_equals(directive.variable, '$http_some')105 assert_equals(directive.operand, '=')106 assert_equals(directive.value, '/some')107def test_block_some_flat():108 config = '''109 some {110 default_type application/octet-stream;111 sendfile on;112 if (-f /some/) {113 keepalive_timeout 65;114 }115 }116 '''117 directive = _get_parsed(config)118 for d in ['default_type', 'sendfile', 'keepalive_timeout']:119 c = directive.some(d, flat=True)120 assert_is_not_none(c)121 assert_equals(c.name, d)122def test_block_some_not_flat():123 config = '''124 some {125 default_type application/octet-stream;126 sendfile on;127 if (-f /some/) {128 keepalive_timeout 65;129 }130 }131 '''132 directive = _get_parsed(config)133 c = directive.some('keepalive_timeout', flat=False)134 assert_is_none(c)135def test_block_find_flat():136 config = '''137 some {138 directive 1;139 if (-f /some/) {140 directive 2;141 }142 }143 '''144 directive = _get_parsed(config)145 finds = directive.find('directive', flat=True)146 assert_equals(len(finds), 2)147 assert_equals([x.name for x in finds], ['directive', 'directive'])148 assert_equals([x.args[0] for x in finds], ['1', '2'])149def test_block_find_not_flat():150 config = '''151 some {152 directive 1;153 if (-f /some/) {154 directive 2;155 }156 }157 '''158 directive = _get_parsed(config)159 finds = directive.find('directive', flat=False)160 assert_equals(len(finds), 1)161 assert_equals([x.name for x in finds], ['directive'])162 assert_equals([x.args[0] for x in finds], ['1'])163def test_block_map():164 config = '''165map $some_var $some_other_var {166 a b;167 default c;168}169 '''170 directive = _get_parsed(config)171 assert_is_instance(directive, MapBlock)172 assert_true(directive.is_block)173 assert_false(directive.self_context)174 assert_true(directive.provide_variables)175 assert_equals(directive.variable, 'some_other_var')176def test_block_geo_two_vars():177 config = '''178geo $some_var $some_other_var {179 1.2.3.4 b;180 default c;181}182 '''183 directive = _get_parsed(config)184 assert_is_instance(directive, GeoBlock)185 assert_true(directive.is_block)186 assert_false(directive.self_context)187 assert_true(directive.provide_variables)188 assert_equals(directive.variable, 'some_other_var')189def test_block_geo_one_var():190 config = '''191geo $some_var {192 5.6.7.8 d;193 default e;194}195 '''196 directive = _get_parsed(config)197 assert_is_instance(directive, GeoBlock)198 assert_true(directive.is_block)199 assert_false(directive.self_context)200 assert_true(directive.provide_variables)...

Full Screen

Full Screen

bl_rst_completeness.py

Source:bl_rst_completeness.py Github

copy

Full Screen

1# ##### BEGIN GPL LICENSE BLOCK #####2#3# This program is free software; you can redistribute it and/or4# modify it under the terms of the GNU General Public License5# as published by the Free Software Foundation; either version 26# of the License, or (at your option) any later version.7#8# This program is distributed in the hope that it will be useful,9# but WITHOUT ANY WARRANTY; without even the implied warranty of10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11# GNU General Public License for more details.12#13# You should have received a copy of the GNU General Public License14# along with this program; if not, write to the Free Software Foundation,15# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.16#17# ##### END GPL LICENSE BLOCK #####18# <pep8 compliant>19# run this script in the game engine.20# or on the command line with...21# ./blender.bin --background -noaudio --python tests/python/bl_rst_completeness.py22'''23filepath = "/src/blender/tests/python/bl_rst_completeness.py"24exec(compile(open(filepath).read(), filepath, 'exec'))25'''26import os27THIS_DIR = os.path.dirname(__file__)28RST_DIR = os.path.normpath(os.path.join(THIS_DIR, "..", "..", "doc", "python_api", "rst"))29import sys30sys.path.append(THIS_DIR)31import rst_to_doctree_mini32# (file, module)33modules = (34 ("bgl.rst", "bgl", True),35 ("gpu.rst", "gpu", False),36)37def is_directive_pydata(filepath, directive):38 if directive.type in {"function", "method", "class", "attribute", "data"}:39 return True40 elif directive.type in {"module", "note", "warning", "code-block", "hlist", "seealso"}:41 return False42 elif directive.type == "literalinclude": # TODO43 return False44 else:45 print(directive_to_str(filepath, directive), end=" ")46 print("unknown directive type %r" % directive.type)47 return False48def directive_to_str(filepath, directive):49 return "%s:%d:%d:" % (filepath, directive.line + 1, directive.indent)50def directive_members_dict(filepath, directive_members):51 return {directive.value_strip: directive for directive in directive_members52 if is_directive_pydata(filepath, directive)}53def module_validate(filepath, mod, mod_name, doctree, partial_ok):54 # RST member missing from MODULE ???55 for directive in doctree:56 # print(directive.type)57 if is_directive_pydata(filepath, directive):58 attr = directive.value_strip59 has_attr = hasattr(mod, attr)60 ok = False61 if not has_attr:62 # so we can have glNormal docs cover glNormal3f63 if partial_ok:64 for s in dir(mod):65 if s.startswith(attr):66 ok = True67 break68 if not ok:69 print(directive_to_str(filepath, directive), end=" ")70 print("rst contains non existing member %r" % attr)71 # if its a class, scan down the class...72 # print(directive.type)73 if has_attr:74 if directive.type == "class":75 cls = getattr(mod, attr)76 # print("directive: ", directive)77 for directive_child in directive.members:78 # print("directive_child: ", directive_child)79 if is_directive_pydata(filepath, directive_child):80 attr_child = directive_child.value_strip81 if attr_child not in cls.__dict__:82 attr_id = "%s.%s" % (attr, attr_child)83 print(directive_to_str(filepath, directive_child), end=" ")84 print("rst contains non existing class member %r" % attr_id)85 # MODULE member missing from RST ???86 doctree_dict = directive_members_dict(filepath, doctree)87 for attr in dir(mod):88 if attr.startswith("_"):89 continue90 directive = doctree_dict.get(attr)91 if directive is None:92 print("module contains undocumented member %r from %r" % ("%s.%s" % (mod_name, attr), filepath))93 else:94 if directive.type == "class":95 directive_dict = directive_members_dict(filepath, directive.members)96 cls = getattr(mod, attr)97 for attr_child in cls.__dict__.keys():98 if attr_child.startswith("_"):99 continue100 if attr_child not in directive_dict:101 attr_id = "%s.%s.%s" % (mod_name, attr, attr_child), filepath102 print("module contains undocumented member %r from %r" % attr_id)103def main():104 for filename, modname, partial_ok in modules:105 filepath = os.path.join(RST_DIR, filename)106 if not os.path.exists(filepath):107 raise Exception("%r not found" % filepath)108 doctree = rst_to_doctree_mini.parse_rst_py(filepath)109 __import__(modname)110 mod = sys.modules[modname]111 module_validate(filepath, mod, modname, doctree, partial_ok)112if __name__ == "__main__":...

Full Screen

Full Screen

known_directives.py

Source:known_directives.py Github

copy

Full Screen

1from ...error import GraphQLError2from ...language import ast3from ...type.directives import DirectiveLocation4from .base import ValidationRule5class KnownDirectives(ValidationRule):6 def enter_Directive(self, node, key, parent, path, ancestors):7 directive_def = next(8 (9 definition10 for definition in self.context.get_schema().get_directives()11 if definition.name == node.name.value12 ),13 None,14 )15 if not directive_def:16 return self.context.report_error(17 GraphQLError(self.unknown_directive_message(node.name.value), [node])18 )19 candidate_location = get_directive_location_for_ast_path(ancestors)20 if not candidate_location:21 self.context.report_error(22 GraphQLError(23 self.misplaced_directive_message(node.name.value, node.type), [node]24 )25 )26 elif candidate_location not in directive_def.locations:27 self.context.report_error(28 GraphQLError(29 self.misplaced_directive_message(30 node.name.value, candidate_location31 ),32 [node],33 )34 )35 @staticmethod36 def unknown_directive_message(directive_name):37 return 'Unknown directive "{}".'.format(directive_name)38 @staticmethod39 def misplaced_directive_message(directive_name, location):40 return 'Directive "{}" may not be used on "{}".'.format(41 directive_name, location42 )43_operation_definition_map = {44 "query": DirectiveLocation.QUERY,45 "mutation": DirectiveLocation.MUTATION,46 "subscription": DirectiveLocation.SUBSCRIPTION,47}48def get_directive_location_for_ast_path(ancestors):49 applied_to = ancestors[-1]50 if isinstance(applied_to, ast.OperationDefinition):51 return _operation_definition_map.get(applied_to.operation)52 elif isinstance(applied_to, ast.Field):53 return DirectiveLocation.FIELD54 elif isinstance(applied_to, ast.FragmentSpread):55 return DirectiveLocation.FRAGMENT_SPREAD56 elif isinstance(applied_to, ast.InlineFragment):57 return DirectiveLocation.INLINE_FRAGMENT58 elif isinstance(applied_to, ast.FragmentDefinition):59 return DirectiveLocation.FRAGMENT_DEFINITION60 elif isinstance(applied_to, ast.SchemaDefinition):61 return DirectiveLocation.SCHEMA62 elif isinstance(applied_to, ast.ScalarTypeDefinition):63 return DirectiveLocation.SCALAR64 elif isinstance(applied_to, ast.ObjectTypeDefinition):65 return DirectiveLocation.OBJECT66 elif isinstance(applied_to, ast.FieldDefinition):67 return DirectiveLocation.FIELD_DEFINITION68 elif isinstance(applied_to, ast.InterfaceTypeDefinition):69 return DirectiveLocation.INTERFACE70 elif isinstance(applied_to, ast.UnionTypeDefinition):71 return DirectiveLocation.UNION72 elif isinstance(applied_to, ast.EnumTypeDefinition):73 return DirectiveLocation.ENUM74 elif isinstance(applied_to, ast.EnumValueDefinition):75 return DirectiveLocation.ENUM_VALUE76 elif isinstance(applied_to, ast.InputObjectTypeDefinition):77 return DirectiveLocation.INPUT_OBJECT78 elif isinstance(applied_to, ast.InputValueDefinition):79 parent_node = ancestors[-3]80 return (81 DirectiveLocation.INPUT_FIELD_DEFINITION82 if isinstance(parent_node, ast.InputObjectTypeDefinition)83 else DirectiveLocation.ARGUMENT_DEFINITION...

Full Screen

Full Screen

constant_directive_runme.py

Source:constant_directive_runme.py Github

copy

Full Screen

1import constant_directive2if not isinstance(constant_directive.TYPE1_CONSTANT1, constant_directive.Type1):3 raise RuntimeError("Failure: TYPE1_CONSTANT1 type: {}".format(4 type(constant_directive.TYPE1_CONSTANT1)))5if not isinstance(constant_directive.getType1Instance(), constant_directive.Type1):6 raise RuntimeError("Failure: getType1Instance() type: {}".format(7 type(constant_directive.getType1Instance())))8if constant_directive.TYPE1_CONSTANT1.val != 1:9 raise RuntimeError("constant_directive.TYPE1_CONSTANT1.val is %r (should be 1)" %10 constant_directive.TYPE1_CONSTANT1.val)11if constant_directive.TYPE1_CONSTANT2.val != 2:12 raise RuntimeError("constant_directive.TYPE1_CONSTANT2.val is %r (should be 2)" %13 constant_directive.TYPE1_CONSTANT2.val)14if constant_directive.TYPE1_CONSTANT3.val != 3:15 raise RuntimeError("constant_directive.TYPE1_CONSTANT3.val is %r (should be 3)" %16 constant_directive.TYPE1_CONSTANT3.val)17if constant_directive.TYPE1CONST_CONSTANT1.val != 1:18 raise RuntimeError("constant_directive.TYPE1CONST_CONSTANT1.val is %r (should be 1)" %19 constant_directive.TYPE1CONST_CONSTANT1.val)20if constant_directive.TYPE1CPTR_CONSTANT1.val != 1:21 raise RuntimeError("constant_directive.TYPE1CPTR_CONSTANT1.val is %r (should be 1)" %...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4import { MyDirective } from './my.directive';5describe('AppComponent', () => {6 beforeEach(() => MockBuilder(AppComponent, AppModule));7 it('should create the app', () => {8 const fixture = MockRender(AppComponent);9 const app = fixture.point.componentInstance;10 expect(app).toBeTruthy();11 });12 it('should render title in a h1 tag', () => {13 const fixture = MockRender(AppComponent);14 fixture.detectChanges();15 const compiled = fixture.nativeElement;16 expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');17 });18 it('should render directive', () => {19 const fixture = MockRender(AppComponent);20 fixture.detectChanges();21 const compiled = fixture.nativeElement;22 expect(compiled.querySelector('div').textContent).toContain('Directive');23 });24});25import { Component } from '@angular/core';26import { MyDirective } from './my.directive';27@Component({28})29export class AppComponent {30 title = 'app';31}32import { Directive } from '@angular/core';33@Directive({34})35export class MyDirective { }36import { BrowserModule } from '@angular/platform-browser';37import { NgModule } from '@angular/core';38import { AppComponent } from './app.component';39import { MyDirective } from './my.directive';40@NgModule({41 imports: [42})43export class AppModule { }44div {45 background-color: red;46}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { MockBuilder, MockRender } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4import { MockComponent } from 'ng-mocks';5MockComponent({ selector: 'app-test', inputs: ['test'] });6MockComponent({ selector: 'app-test', template: 'test' });7MockComponent({ selector: 'app-test', inputs: ['test'], template: 'test' });8MockComponent({ selector: 'app-test', inputs: ['test'], template: 'test' });9describe('AppComponent', () => {10 beforeEach(() => MockBuilder(AppComponent, AppModule));11 it('should create the app', () => {12 const fixture = MockRender(AppComponent);13 expect(fixture.point.componentInstance).toBeTruthy();14 });15});16import { Component } from '@angular/core';17@Component({18})19export class AppComponent {20 title = 'app';21}22import { NgModule } from '@angular/core';23import { BrowserModule } from '@angular/platform-browser';24import { AppComponent } from './app.component';25import { TestComponent } from './test/test.component';26@NgModule({27 imports: [BrowserModule],28})29export class AppModule {}30import { Component, Input } from '@angular/core';31@Component({32})33export class TestComponent {34 @Input() test: string;35}36<div>{{ test }}</div>37import { MockBuilder, MockRender } from 'ng-mocks';38import { AppModule } from './app.module';39import { AppComponent } from './app.component';40import { MockDirective } from 'ng-mocks

Full Screen

Using AI Code Generation

copy

Full Screen

1var app = angular.module('app', []);2app.directive('myDirective', function () {3 return {4 };5});6var app = angular.module('app', []);7app.component('myComponent', {8});9describe('myDirective', function () {10 beforeEach(function () {11 angular.mock.module('app');12 angular.mock.inject(function ($compile, $rootScope) {13 var scope = $rootScope.$new();14 var element = $compile('<my-directive></my-directive>')(scope);15 scope.$digest();16 this.element = element;17 });18 angular.mock.module('app');19 angular.mock.inject(function ($compile, $rootScope) {20 var scope = $rootScope.$new();21 var element = $compile('<my-component></my-component>')(scope);22 scope.$digest();23 this.element = element;24 });25 });26 it('should render the directive', function () {27 expect(this.element.text()).toEqual('Hello World!');28 });29});30The beforeEach() function is used to initialize the test environment. In the beforeEach() function, we have to use the angular.mock.module() function to load the module that we want to test. The angular.mock.module() function takes the name of the module as the parameter. After that, we have to use the angular.mock.inject() function to inject the dependencies that we want to test. The angular.mock.inject() function takes a callback function as the parameter. Inside the callback function, we can use the $compile, $rootScope, and other dependencies that we want to test. After that, we have to use the $compile() function to compile the HTML template. The $compile() function takes the HTML template as the parameter. After that, we have to use the $rootScope.$new() function to create a new scope. After that

Full Screen

Using AI Code Generation

copy

Full Screen

1var ngMocks = require('ng-mocks');2ngMocks.directive('myDirective', function() {3 return {4 };5});6describe('myDirective', function() {7 var $compile, $rootScope;8 beforeEach(angular.mock.module('myApp'));9 beforeEach(inject(function(_$compile_, _$rootScope_) {10 $compile = _$compile_;11 $rootScope = _$rootScope_;12 }));13 it('should render the directive', function() {14 var element = $compile('<div my-directive></div>')($rootScope);15 $rootScope.$digest();16 expect(element.html()).toContain('My directive');17 });18});19var ngMocks = require('ng-mocks');20ngMocks.module('myApp', function($compileProvider) {21 $compileProvider.directive('myDirective', function() {22 return {23 };24 });25});26describe('myDirective', function() {27 var $compile, $rootScope;28 beforeEach(angular.mock.module('myApp'));29 beforeEach(inject(function(_$compile_, _$rootScope_) {30 $compile = _$compile_;31 $rootScope = _$rootScope_;32 }));33 it('should render the directive', function() {34 var element = $compile('<div my-directive></div>')($rootScope);35 $rootScope.$digest();36 expect(element.html()).toContain('My directive');37 });38});39var ngMocks = require('ng-mocks');40ngMocks.module('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('AppComponent', () => {2 beforeEach(async(() => {3 TestBed.configureTestingModule({4 imports: [5 MockModule(MatIconModule, MatIconTestingModule)6 }).compileComponents();7 }));8 it('should create the app', () => {9 const fixture = TestBed.createComponent(AppComponent);10 const app = fixture.componentInstance;11 expect(app).toBeTruthy();12 });13 it(`should have as title 'ng-mocks-test'`, () => {14 const fixture = TestBed.createComponent(AppComponent);15 const app = fixture.componentInstance;16 expect(app.title).toEqual('ng-mocks-test');17 });18 it('should render title', () => {19 const fixture = TestBed.createComponent(AppComponent);20 fixture.detectChanges();21 const compiled = fixture.nativeElement;22 expect(compiled.querySelector('.content span').textContent).toContain('ng-mocks-test app is running!');23 });24});25import { NO_ERRORS_SCHEMA } from '@angular/core';26import { ComponentFixture, TestBed } from '@angular/core/testing';27import { MatIconModule } from '@angular/material/icon';28import { MatIconTestingModule } from '@angular/material/icon/testing';29import { AppComponent } from './app.component';30describe('AppComponent', () => {31 let component: AppComponent;32 let fixture: ComponentFixture<AppComponent>;33 beforeEach(async () => {34 await TestBed.configureTestingModule({35 imports: [36 MockModule(MatIconModule, MatIconTestingModule)37 })38 .compileComponents();39 });40 beforeEach(() => {41 fixture = TestBed.createComponent(AppComponent);

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 ng-mocks 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