def test_find_empty(): red = RedBaron("") assert red.find("stuff") is None assert red.find("something_else") is None assert red.find("something_else", useless="pouet") is None with pytest.raises(AttributeError): red.will_raises
def test_node_elif_ifelseblock_next_intuitive(): red = RedBaron("if a:\n pass\nelif a:\n pass") assert red.find("elif").next_intuitive is None red = RedBaron("if a:\n pass\nelif a:\n pass\nelse:\n pass") assert red.find("elif").next_intuitive is red.find("else") red = RedBaron("if a:\n pass\nelif a:\n pass\nchocolat") assert red.find("elif").next_intuitive is red.find("name", "chocolat")
def test_append_newline_and_async_def_in_class_with_space(): red = RedBaron("""\ async def a(self, a): return False """) red.find("def").append("\n") red.find("def").append("class b:\n def c(self):\n return True\n") red.find("def").append("\n") red.find("def").append( "class b:\n async def c(self):\n return True\n") red.find("def").append("\n") assert_with_indent( red, """\ async def a(self, a): return False class b: def c(self): return True class b: async def c(self): return True """)
def test_node_else_elseelseblock_next_generator(): red = RedBaron("if a:\n pass\nelse:\n pass") assert len(list(red.else_.next_generator())) == 0 red = RedBaron("if a:\n pass\nelse:\n pass\nchocolat") assert list(red.else_.next_generator())[0] is red.find("name", "chocolat") red = RedBaron("if a:\n pass\nelse:\n pass\nchocolat") assert list(red.else_.next_generator()) == [red.find("name", "chocolat")]
def test_node_else_elseelseblock_previous_generator(): red = RedBaron("if a:\n pass\nelse:\n pass") assert len(list(red.else_.previous_generator())) == 1 red = RedBaron("chocolat\nif a:\n pass\nelse:\n pass\n") assert len(list(red.else_.previous_generator())) == 3 red = RedBaron("chocolat\nif a:\n pass\nelse:\n pass\n") assert list(red.else_.previous_generator())[0] is red.if_ red = RedBaron("chocolat\nif a:\n pass\nelse:\n pass\n") assert list(red.else_.previous_generator()) == [red.find("name", "chocolat"), red.find("endl"), red.if_][::-1]
def test_set_decorators_indented_def(): red = RedBaron("""class A(): def a(): pass def b(): pass """) red.find("def", "b").decorators = "@pouet\n@plop\n" assert len(red.find("def", "b").decorators) == 2 assert red.dumps() == """class A():
def test_node_else_elseelseblock_previous_generator(): red = RedBaron("if a:\n pass\nelse:\n pass") assert len(list(red.else_.previous_generator())) == 1 red = RedBaron("chocolat\nif a:\n pass\nelse:\n pass\n") assert len(list(red.else_.previous_generator())) == 3 red = RedBaron("chocolat\nif a:\n pass\nelse:\n pass\n") assert list(red.else_.previous_generator())[0] is red.if_ red = RedBaron("chocolat\nif a:\n pass\nelse:\n pass\n") assert list(red.else_.previous_generator()) == [ red.find("name", "chocolat"), red.find("endl"), red.if_ ][::-1]
def handle(self, *args, **options): call_command('migrate', interactive = False) try: company = Entity.objects.get(owner=True) self.stdout.write('Already configured') except Entity.DoesNotExist: entity = Entity() entity.name = 'Your company' entity.description = 'Your company description' entity.endpoint = 'http://*****:*****@test.test' liaison.phone = '123456789' liaison.address = 'Testing Road' liaison.zip = '123456' liaison.city = 'Testicity' liaison.provider = entity liaison.save() base = getattr(settings, 'BASE_DIR') settings_path = os.path.join(base, 'Exchange', 'settings.py') with open(settings_path, 'r+') as f: read_data = f.read() f.seek(0) red = RedBaron(read_data) red.find("assignment", target=lambda x: x.dumps() == "SENDER").value.replace("'" + str(entity.id) + "'") secret_key = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) red.find("assignment", target=lambda x: x.dumps() == "SECRET_KEY").value.replace("'" + secret_key + "'") f.truncate() code = red.dumps() f.write(code) f.closed print('Database content created') print('Provider configured') print('New secret key generated') self.stdout.write('Setup complete')
def test_node_elif_ifelseblock_next(): red = RedBaron("if a:\n pass\nelif a:\n pass") assert red.elif_.next is None red = RedBaron("if a:\n pass\nelif a:\n pass\nelse:\n pass") assert red.elif_.next is red.else_ red = RedBaron("if a:\n pass\nelif a:\n pass\nchocolat") assert red.elif_.next is red.find("name", "chocolat")
def compare(s1, s2, decay_factor = DEFAULT_DECAY_FACTOR): red1 = RedBaron(s1) red2 = RedBaron(s2) result = [] for ast_f2 in red2.find_all('def'): ast_f1 = red1.find('def', name = ast_f2.name) if ast_f1 is not None: additions, deletions = preprocess_files(ast_f1.dumps(), ast_f2.dumps()) comments, exceptions = preprocess_comments(ast_f2, additions) for a in additions: for c in comments: line, _ = c.left_bounds distance = math.fabs(line - a) score = int(c.score() - float(decay_factor) / (distance * distance)) c.setScore(score if score > 0 else 0) for d in deletions: for c in comments: line, _ = c.left_bounds line = line + 1 if line >= d else line distance = math.fabs(line - d) score = int(c.score() - float(decay_factor) / (distance * distance)) c.setScore(score if score > 0 else 0) result.extend(comments) result.extend(exceptions) else: result.extend(preprocess_comments(ast_f2, [])) return result
def test_node_if_ifelseblock_previous_intuitive(): red = RedBaron("if a:\n pass") assert red.if_.previous_intuitive is None red = RedBaron("chocolat\nif a:\n pass") assert red.if_.previous_intuitive is red.find("endl") red = RedBaron("pouet\nif a:\n pass\nelif a:\n pass\nelse:\n pass") assert red.else_.previous_intuitive is red.elif_ assert red.if_.previous is None
def test_append_newline_and_def_in_nested_class(): red = RedBaron("""\ class A: class B: pass """) # red.class_.class_.append("def b():\n return True") red.find("class").find("class").append("a = 1\n") assert_with_indent( red, """\ class A: class B: pass a = 1 """)
def test_node_if_ifelseblock_previous_intuitive(): red = RedBaron("if a:\n pass") assert red.if_.previous_intuitive is None red = RedBaron("chocolat\nif a:\n pass") assert red.if_.previous_intuitive is red.find("endl") red = RedBaron( "pouet\nif a:\n pass\nelif a:\n pass\nelse:\n pass") assert red.else_.previous_intuitive is red.elif_ assert red.if_.previous is None
def test_insert_nested_line_in_def_with_if(): red = RedBaron("""\ def a(self, a): if a == 42: return True return False """) red.find("def").find("if").insert(0, "a = 1\n") assert_with_indent( red, """\ def a(self, a): if a == 42: a = 1 return True return False """)
def test_set_attr_def_advanced_inline_dont_break_next_block_indent(): red = RedBaron(""" def c(): def zomg(): pass plop """) red.find("def", name="zomg").value = "\nreturn 42\n" assert red.dumps() == """
def test_set_attr_def_advanced_in_class_dont_break_next_block_indent(): red = RedBaron(""" class A(): def a(): pass def b(): pass """) red.find("def", name="a").value = "\nreturn 42\n" assert red.dumps() == """
def test_append_newline_line_in_def_with_if(): red = RedBaron("""\ def a(self, a): if a == 42: return True return False """) red.find("def").find("if").append("\n") red.find("def").find("if").extend(["\n", "a = 1\n", "\n"]) assert_with_indent( red, """\ def a(self, a): if a == 42: return True a = 1 return False """)
def test_set_attr_def_advanced_dont_break_next_block_indent_two_endl(): red = RedBaron(""" def c(): def zomg(): pass plop def d(): pass """) red.find("def", name="c").value = "\nreturn 42\n\n" assert red.dumps() == """
def test_extend_newline_and_def_in_def(): red = RedBaron("""\ def a(self, a): return False """) red.find("def").extend(["\n", "def b():\n return True\n", "\n"]) red.find("def").extend(["\n", "def b():\n return True\n", "\n"]) assert_with_indent( red, """\ def a(self, a): return False def b(): return True def b(): return True """)
def parse_pkginfo(path): red = RedBaron(open(path, "r").read()) depends = red.find("assign", lambda x: x.target.value == "__depends__") if not depends: print("I couldn't find __depends__ in the __pkginfo__.py :(") sys.exit(1) assert depends.value.type == "dict" # oupsi I'm lazy, it's bad :( # XXX use to_python() somehow return eval(depends.value.dumps()), red, depends
def test_node_if_ifelseblock_previous_intuitive(): red = RedBaron("if a:\n pass") assert red.find("if").previous_intuitive is None red = RedBaron("chocolat\nif a:\n pass") assert red.find("if").previous_intuitive is red.find("name", "chocolat") red = RedBaron( "pouet\nif a:\n pass\nelif a:\n pass\nelse:\n pass") assert red.find("else").previous_intuitive is red.find("elif") assert red.find("elif").previous_intuitive is red.find("if")
def normalize_dict_key(method: str) -> str: """ Remove statements unrelated to dict key access or field access :param method: :return: """ red = RedBaron(method) # remain_stmts = [] method_red = red.find('def') for i, stmt in enumerate(method_red.value): if len(stmt.find_all('dictnode')) != 0 or len(stmt.find_all('getitem')) != 0 or len(stmt.find_all('dotnode')) != 0: # remain_stmts.append(stmt.dumps()) continue else: del method_red.value[i] # red.value = '\n'.join(remain_stmts) return red.dumps()
def compare(s1, s2, decay_factor = PYTHON_DECAY_FACTOR): try: red1 = RedBaron(s1) red2 = RedBaron(s2) result = [] defs = red2.find_all('def') length = len(defs) for ast_f2 in defs: ast_f1 = red1.find('def', name = ast_f2.name) if ast_f1 is not None: additions, deletions = preprocess_files(ast_f1.dumps(), ast_f2.dumps(), ast_f2.absolute_bounding_box.top_left.line) comments, exceptions = preprocess_comments(ast_f2, additions) for a in additions: for c in comments: line, _ = c.left_bounds distance = line - a score = compute_addition(c, distance, decay_factor) c.setScore(score if score > 0 else 0) for d in deletions: for c in comments: line, _ = c.left_bounds line = line + 1 if line >= d else line distance = line - d score = compute_deletion(c, distance, decay_factor) c.setScore(score if score > 0 else 0) result.extend(comments) result.extend(exceptions) else: comments, _ = preprocess_comments(ast_f2, []) result.extend(comments) print_to_log('Result: ' + str(result)) return result except Exception as e: err = 'CommentHealth compare error: ' + str(e) return []
del ast_node.parent.value[index] def process_named_values(ast_node): parent = ast_node.parent if parent and parent.value == ast_node \ and ast_node.value != "True" and ast_node.value != "False": named_value_code = json_code_object(ast_node.dumps()) parent.value = RedBaron(named_value_code)[0] def dump_info(**kwargs): return json.dumps(kwargs, indent=2) setup_node = red.find("call", lambda ast_node: is_setup_args_node(ast_node)) args = setup_node.value args.find_all("dict_argument").apply(lambda ast_node: process_dict_args(ast_node)) args.find_all("name", lambda ast_node: process_named_values(ast_node)) args.find_all("call").apply(lambda ast_node: process_fn_calls(ast_node)) setup_node.previous.value = "dump_info" setup_call_node = setup_node.parent code = setup_call_node.dumps() if options.debug: print >> sys.stderr, code setup_info = eval(code) print setup_info
def test_default_test_value_find_class(): red = RedBaron("class a(): pass\nclass b(): pass") assert red.find("class", "b") == red.find("class", name="b")
def test_default_test_value_find_def(): red = RedBaron("def a(): pass\ndef b(): pass") assert red.find("def", "b") == red.find("def", name="b")
def test_find_kwarg_lambda(): red = RedBaron("[1, 2, 3, 4]") assert red.find("int", value=lambda x: int(x) % 2 == 0) == red("int")[1] assert red("int", value=lambda x: int(x) % 2 == 0) == red('int')[1::2]
def test_find_kwarg_regex_instance(): red = RedBaron("plop\npop\npouf\nabcd") assert red.find("name", value=re.compile("^po")) == red[1]
def test_identifier_find_kwarg_list_tuple_instance(): red = RedBaron("pouet\n'string'\n1") assert red.find(["name", "string"]) == red[0] assert red.find(("name", "string")) == red[0]
def test_identifier_find_kwarg_glob_syntaxe(): red = RedBaron("stuff\n1\n'string'") assert red.find("g:s*") == red[-1]
def test_identifier_find_kwarg_regex_instance(): red = RedBaron("stuff\n1\n'string'") assert red.find(re.compile("^[ni]")) == red[0]
def test_find_kwarg_glob_syntaxe(): red = RedBaron("plop\npop\npouf\nabcd") assert red.find("name", value="g:po*") == red[1]
def test_get_root(): red = RedBaron("def a(b=c):\n return 42") assert red is red.find("int").root
def test_next_rendered_trapped(): red = RedBaron(test_indent_code) assert red("endl")[5].next_rendered is red.find("name", "pouf")
def test_find_lambda(): red = RedBaron("[1, 2, 3, 4]") assert red.find("int", lambda x: int(x.value) % 2 == 0) == red('int')[1] assert red("int", lambda x: int(x.value) % 2 == 0) == red('int')[1::2]
def test_find(): red = RedBaron("def a(): b = c") assert red.find("name") is red[0].value[0].target assert red.find("name", value="c") is red[0].value[0].value assert red.name is red[0].value[0].target
def test_find_empty(): red = RedBaron("") assert red.find("stuff") is None assert red.find("something_else") is None assert red.find("something_else", useless="pouet") is None assert red.something_else is None
# General information about the project. project = u'RedBaron' copyright = u'2014, Laurent Peuch' import sys sys.path.append("..") from redbaron import RedBaron red = RedBaron(open("../setup.py", "r").read()) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = eval(red.find("call_argument", target=lambda x: x and x.dumps() == "version").value.value) # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files.
def test_find_case_insensitive(): red = RedBaron("a") assert red.find("NameNode") is red[0] assert red.find("NaMeNoDe") is red[0] assert red.find("namenode") is red[0]
def test_default_test_value_find(): red = RedBaron("badger\nmushroom\nsnake") assert red.find("name", "snake") == red.find("name", value="snake")
def test_find_kwarg_regex_syntaxe(): red = RedBaron("plop\npop\npouf\nabcd") assert red.find("name", value="re:^po") == red[1]
def test_parent_find_two_levels(): red = RedBaron(SOME_DATA_FOR_TEST) target = red.assignment.target assert target.parent_find('def') is red.find('def', name='a')
def test_identifier_find_kwarg_lambda(): red = RedBaron("stuff\n1\n'string'") assert red.find(lambda x: x in ["name", "int"]) == red[0] assert red(lambda x: x in ["name", "int"]) == red[:2].node_list
def test_identifier_find_kwarg_regex_syntaxe(): red = RedBaron("stuff\n1\n'string'") assert red.find("re:^[ni]") == red[0]
def test_find_kwarg_list_tuple_instance(): red = RedBaron("pouet\n'string'\n1") assert red.find("name", value=["pouet", 1]) == red[0] assert red.find("name", value=("pouet", 1)) == red[0]