├── .gitignore ├── doc ├── changes.rst ├── index.rst ├── templateutils.rst ├── checking.rst ├── Makefile └── conf.py ├── pyproject.toml ├── .github └── workflows │ └── test.yml ├── README.rst ├── LICENSE ├── astcheck.py └── test_astcheck.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__ 3 | build/ 4 | doc/_build 5 | MANIFEST 6 | dist/ 7 | -------------------------------------------------------------------------------- /doc/changes.rst: -------------------------------------------------------------------------------- 1 | Changes 2 | ======= 3 | 4 | Version 0.3 5 | ----------- 6 | 7 | * Added :class:`.single_assign` helper. 8 | * Requires Python >= 3.5. 9 | 10 | Version 0.2 11 | ----------- 12 | 13 | * Added :ref:`checker functions `. 14 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | astcheck |version| 2 | ================== 3 | 4 | astcheck is a module for checking a Python Abstract Syntax Tree against a 5 | template. This is useful for testing code that automatically generates or 6 | modifies Python code. 7 | 8 | For more details about the structure of ASTs, see my documentation project, 9 | `Green Tree Snakes `_. 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | checking 15 | templateutils 16 | changes 17 | 18 | 19 | Indices and tables 20 | ================== 21 | 22 | * :ref:`genindex` 23 | * :ref:`modindex` 24 | * :ref:`search` 25 | 26 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["flit_core >=3.2,<4"] 3 | build-backend = "flit_core.buildapi" 4 | 5 | [project] 6 | name = "astcheck" 7 | authors = [ 8 | {name = "Thomas Kluyver", email = "thomas@kluyver.me.uk"}, 9 | ] 10 | readme = "README.rst" 11 | classifiers = [ 12 | "Intended Audience :: Developers", 13 | "License :: OSI Approved :: MIT License", 14 | "Programming Language :: Python", 15 | "Programming Language :: Python :: 3", 16 | "Topic :: Software Development :: Code Generators", 17 | "Topic :: Software Development :: Testing", 18 | ] 19 | requires-python = ">=3.8" 20 | dynamic = ['version', 'description'] 21 | 22 | [project.urls] 23 | Source = "https://github.com/takluyver/astcheck" 24 | Documentation = "https://astcheck.readthedocs.io/en/latest/" 25 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: [ "3.8", "3.9", "3.10", "3.11", "3.12" ] 11 | steps: 12 | - uses: actions/checkout@v4 13 | 14 | - name: Setup Python ${{ matrix.python-version }} 15 | uses: actions/setup-python@v5 16 | with: 17 | python-version: ${{ matrix.python-version }} 18 | 19 | - uses: actions/cache@v4 20 | with: 21 | path: ~/.cache/pip 22 | key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('pyproject.toml') }} 23 | 24 | - name: Install dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | pip install . pytest pytest-cov 28 | 29 | - name: Run tests 30 | run: pytest --cov=astcheck --cov-report=xml 31 | 32 | - name: Upload coverage to codecov 33 | uses: codecov/codecov-action@v3 34 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | astcheck 2 | ======== 3 | 4 | astcheck compares Python Abstract Syntax Trees against a template. This is 5 | useful for testing software that automatically generates or modifies Python code. 6 | 7 | Installation:: 8 | 9 | pip install astcheck 10 | 11 | Example use: 12 | 13 | .. code:: python 14 | 15 | import ast, astcheck 16 | 17 | template = ast.Module(body=[ 18 | ast.FunctionDef(name='double', args=ast.arguments(args=[ast.arg(arg='a')])), 19 | ast.Assign(value=ast.Call(func=ast.Name(id='double'))) 20 | ]) 21 | 22 | sample = """ 23 | def double(a): 24 | do_things() 25 | return a*2 26 | b = double(a) 27 | """ 28 | 29 | astcheck.assert_ast_like(ast.parse(sample), template) 30 | 31 | Only the parts specified in the template are checked. In this example, the code 32 | inside the function, and the assignment target (``b``) could be anything. 33 | 34 | For more details, see `the documentation `_. 35 | -------------------------------------------------------------------------------- /doc/templateutils.rst: -------------------------------------------------------------------------------- 1 | Template building utilities 2 | =========================== 3 | 4 | .. currentmodule:: astcheck 5 | 6 | astcheck includes some utilities for building AST templates to check against. 7 | 8 | .. autofunction:: must_exist 9 | 10 | .. autofunction:: must_not_exist 11 | 12 | .. autoclass:: name_or_attr 13 | 14 | .. autoclass:: single_assign 15 | 16 | .. class:: listmiddle 17 | 18 | Helper to check only the beginning and/or end of a list. Instantiate it and 19 | add lists to it to match them at the start or the end. E.g. to test the final 20 | return statement of a function, while ignoring any other code in the function:: 21 | 22 | template = ast.FunctionDef(name="myfunc", 23 | body= astcheck.listmiddle()+[ast.Return(value=ast.Name(id="retval"))] 24 | ) 25 | 26 | sample = ast.parse(""" 27 | def myfunc(): 28 | retval = do_something() * 7 29 | return retval 30 | """) 31 | 32 | astcheck.assert_ast_like(sample.body[0], template) 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Thomas Kluyver 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /doc/checking.rst: -------------------------------------------------------------------------------- 1 | Checking ASTs 2 | ============= 3 | 4 | .. module:: astcheck 5 | 6 | Start by defining a template, a partial AST to compare against. You can fill in 7 | as many or as few fields as you want. For example, to check for assignment to 8 | a variable ``a``, but ignore the value: 9 | 10 | .. code-block:: python 11 | 12 | template = ast.Module(body=[ 13 | ast.Assign(targets=[ast.Name(id='a')]) 14 | ]) 15 | sample = ast.parse("a = 7") 16 | astcheck.assert_ast_like(sample, template) 17 | 18 | astcheck provides some helpers for defining flexible templates; see 19 | :doc:`templateutils`. 20 | 21 | .. autofunction:: assert_ast_like 22 | .. autofunction:: is_ast_like 23 | 24 | .. note:: 25 | The parameter order matters! Only fields present in ``template`` will be 26 | checked, so you can leave out bits of the code you don't care about. Normally, 27 | ``sample`` will be the result of the code you want to test, and ``template`` 28 | will be defined in your test file. 29 | 30 | .. _checkerfuncs: 31 | 32 | Checker functions 33 | ----------------- 34 | 35 | You may want to write more customised checks for part of the AST. To do so, you 36 | can attach 'checker functions' to any part of the template tree. Checker 37 | functions should accept two parameters: the node or value at the corresponding 38 | part of the sample tree, and the path to that node—a list of strings and integers 39 | representing the attribute and index access used to get there from the root of 40 | the sample tree. 41 | 42 | If the value passed is not acceptable, the checker function should raise one 43 | of the exceptions described below. Otherwise, it should return with no exception. 44 | The return value is ignored. 45 | 46 | For instance, this will test for a number literal less than 7: 47 | 48 | .. code-block:: python 49 | 50 | def less_than_seven(node, path): 51 | if not isinstance(node, ast.Num): 52 | raise astcheck.ASTNodeTypeMismatch(path, node, ast.Num()) 53 | if node.n >= 7: 54 | raise astcheck.ASTMismatch(path+['n'], node.n, '< 7') 55 | 56 | template = ast.Expression(body=ast.BinOp(left=less_than_seven)) 57 | sample = ast.parse('4+9', mode='eval') 58 | astcheck.assert_ast_like(sample, template) 59 | 60 | There are a few checker functions available in astcheck—see :doc:`templateutils`. 61 | 62 | Exceptions 63 | ---------- 64 | 65 | .. autoexception:: ASTMismatch 66 | :show-inheritance: 67 | 68 | The following exceptions are raised by :func:`assert_ast_like`. They should 69 | all produce useful error messages explaining which part of the AST differed and 70 | how: 71 | 72 | .. autoexception:: ASTNodeTypeMismatch 73 | :show-inheritance: 74 | 75 | .. autoexception:: ASTNodeListMismatch 76 | :show-inheritance: 77 | 78 | .. autoexception:: ASTPlainListMismatch 79 | :show-inheritance: 80 | 81 | .. autoexception:: ASTPlainObjMismatch 82 | :show-inheritance: 83 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/astcheck.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/astcheck.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/astcheck" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/astcheck" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # astcheck documentation build configuration file, created by 4 | # sphinx-quickstart on Thu Mar 27 17:53:06 2014. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | sys.path.insert(0, os.path.abspath('..')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.intersphinx', 34 | ] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'astcheck' 50 | copyright = u'2014, Thomas Kluyver' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = '0.4' 58 | # The full version, including alpha/beta/rc tags. 59 | release = '0.4.0' 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all 76 | # documents. 77 | #default_role = None 78 | 79 | # If true, '()' will be appended to :func: etc. cross-reference text. 80 | #add_function_parentheses = True 81 | 82 | # If true, the current module name will be prepended to all description 83 | # unit titles (such as .. function::). 84 | #add_module_names = True 85 | 86 | # If true, sectionauthor and moduleauthor directives will be shown in the 87 | # output. They are ignored by default. 88 | #show_authors = False 89 | 90 | # The name of the Pygments (syntax highlighting) style to use. 91 | pygments_style = 'sphinx' 92 | 93 | # A list of ignored prefixes for module index sorting. 94 | #modindex_common_prefix = [] 95 | 96 | # If true, keep warnings as "system message" paragraphs in the built documents. 97 | #keep_warnings = False 98 | 99 | 100 | # -- Options for HTML output ---------------------------------------------- 101 | 102 | # The theme to use for HTML and HTML Help pages. See the documentation for 103 | # a list of builtin themes. 104 | html_theme = 'default' 105 | 106 | # Theme options are theme-specific and customize the look and feel of a theme 107 | # further. For a list of options available for each theme, see the 108 | # documentation. 109 | #html_theme_options = {} 110 | 111 | # Add any paths that contain custom themes here, relative to this directory. 112 | #html_theme_path = [] 113 | 114 | # The name for this set of Sphinx documents. If None, it defaults to 115 | # " v documentation". 116 | #html_title = None 117 | 118 | # A shorter title for the navigation bar. Default is the same as html_title. 119 | #html_short_title = None 120 | 121 | # The name of an image file (relative to this directory) to place at the top 122 | # of the sidebar. 123 | #html_logo = None 124 | 125 | # The name of an image file (within the static path) to use as favicon of the 126 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 127 | # pixels large. 128 | #html_favicon = None 129 | 130 | # Add any paths that contain custom static files (such as style sheets) here, 131 | # relative to this directory. They are copied after the builtin static files, 132 | # so a file named "default.css" will overwrite the builtin "default.css". 133 | html_static_path = ['_static'] 134 | 135 | # Add any extra paths that contain custom files (such as robots.txt or 136 | # .htaccess) here, relative to this directory. These files are copied 137 | # directly to the root of the documentation. 138 | #html_extra_path = [] 139 | 140 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 141 | # using the given strftime format. 142 | #html_last_updated_fmt = '%b %d, %Y' 143 | 144 | # If true, SmartyPants will be used to convert quotes and dashes to 145 | # typographically correct entities. 146 | #html_use_smartypants = True 147 | 148 | # Custom sidebar templates, maps document names to template names. 149 | #html_sidebars = {} 150 | 151 | # Additional templates that should be rendered to pages, maps page names to 152 | # template names. 153 | #html_additional_pages = {} 154 | 155 | # If false, no module index is generated. 156 | #html_domain_indices = True 157 | 158 | # If false, no index is generated. 159 | #html_use_index = True 160 | 161 | # If true, the index is split into individual pages for each letter. 162 | #html_split_index = False 163 | 164 | # If true, links to the reST sources are added to the pages. 165 | #html_show_sourcelink = True 166 | 167 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 168 | #html_show_sphinx = True 169 | 170 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 171 | #html_show_copyright = True 172 | 173 | # If true, an OpenSearch description file will be output, and all pages will 174 | # contain a tag referring to it. The value of this option must be the 175 | # base URL from which the finished HTML is served. 176 | #html_use_opensearch = '' 177 | 178 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 179 | #html_file_suffix = None 180 | 181 | # Output file base name for HTML help builder. 182 | htmlhelp_basename = 'astcheckdoc' 183 | 184 | 185 | # -- Options for LaTeX output --------------------------------------------- 186 | 187 | latex_elements = { 188 | # The paper size ('letterpaper' or 'a4paper'). 189 | #'papersize': 'letterpaper', 190 | 191 | # The font size ('10pt', '11pt' or '12pt'). 192 | #'pointsize': '10pt', 193 | 194 | # Additional stuff for the LaTeX preamble. 195 | #'preamble': '', 196 | } 197 | 198 | # Grouping the document tree into LaTeX files. List of tuples 199 | # (source start file, target name, title, 200 | # author, documentclass [howto, manual, or own class]). 201 | latex_documents = [ 202 | ('index', 'astcheck.tex', u'astcheck Documentation', 203 | u'Thomas Kluyver', 'manual'), 204 | ] 205 | 206 | # The name of an image file (relative to this directory) to place at the top of 207 | # the title page. 208 | #latex_logo = None 209 | 210 | # For "manual" documents, if this is true, then toplevel headings are parts, 211 | # not chapters. 212 | #latex_use_parts = False 213 | 214 | # If true, show page references after internal links. 215 | #latex_show_pagerefs = False 216 | 217 | # If true, show URL addresses after external links. 218 | #latex_show_urls = False 219 | 220 | # Documents to append as an appendix to all manuals. 221 | #latex_appendices = [] 222 | 223 | # If false, no module index is generated. 224 | #latex_domain_indices = True 225 | 226 | 227 | # -- Options for manual page output --------------------------------------- 228 | 229 | # One entry per manual page. List of tuples 230 | # (source start file, name, description, authors, manual section). 231 | man_pages = [ 232 | ('index', 'astcheck', u'astcheck Documentation', 233 | [u'Thomas Kluyver'], 1) 234 | ] 235 | 236 | # If true, show URL addresses after external links. 237 | #man_show_urls = False 238 | 239 | 240 | # -- Options for Texinfo output ------------------------------------------- 241 | 242 | # Grouping the document tree into Texinfo files. List of tuples 243 | # (source start file, target name, title, author, 244 | # dir menu entry, description, category) 245 | texinfo_documents = [ 246 | ('index', 'astcheck', u'astcheck Documentation', 247 | u'Thomas Kluyver', 'astcheck', 'One line description of project.', 248 | 'Miscellaneous'), 249 | ] 250 | 251 | # Documents to append as an appendix to all manuals. 252 | #texinfo_appendices = [] 253 | 254 | # If false, no module index is generated. 255 | #texinfo_domain_indices = True 256 | 257 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 258 | #texinfo_show_urls = 'footnote' 259 | 260 | # If true, do not generate a @detailmenu in the "Top" node's menu. 261 | #texinfo_no_detailmenu = False 262 | 263 | 264 | # Example configuration for intersphinx: refer to the Python standard library. 265 | intersphinx_mapping = {'python': ('http://docs.python.org/3', None)} 266 | -------------------------------------------------------------------------------- /astcheck.py: -------------------------------------------------------------------------------- 1 | """Check Python ASTs against templates""" 2 | import ast 3 | 4 | __version__ = '0.4.0' 5 | 6 | def mkarg(name): 7 | # This was defined for Python 2-3 compatibility, and now left in place to 8 | # avoid breaking code that uses it. 9 | return ast.arg(arg=name) 10 | 11 | def must_exist(node, path): 12 | """Checker function for an item or list that must exist 13 | 14 | This matches any value except None and the empty list. 15 | 16 | For instance, to match for loops with an else clause:: 17 | 18 | ast.For(orelse=astcheck.must_exist) 19 | """ 20 | if (node is None) or (node == []): 21 | raise ASTMismatch(path, node, "non empty") 22 | 23 | def must_not_exist(node, path): 24 | """Checker function for things that must not exist 25 | 26 | This accepts only None and the empty list. 27 | 28 | For instance, to check that a function has no decorators:: 29 | 30 | ast.FunctionDef(decorator_list=astcheck.must_not_exist) 31 | """ 32 | if (node is None) or (node == []): 33 | return 34 | raise ASTMismatch(path, node, "nothing") 35 | 36 | class name_or_attr(object): 37 | """Checker for :class:`ast.Name` or :class:`ast.Attribute` 38 | 39 | These are often used in similar ways - depending on how you do imports, 40 | objects will be referenced as names or as attributes of a module. By using 41 | this function to build your template, you can allow either. For instance, 42 | this will match both ``f()`` and ``mod.f()``:: 43 | 44 | ast.Call(func=astcheck.name_or_attr('f')) 45 | """ 46 | def __init__(self, name): 47 | self.name = name 48 | 49 | def __repr__(self): 50 | return "astcheck.name_or_attr(%r)" % self.name 51 | 52 | def __call__(self, node, path): 53 | if isinstance(node, ast.Name): 54 | if node.id != self.name: 55 | raise ASTPlainObjMismatch(path+['id'], node.id, self.name) 56 | elif isinstance(node, ast.Attribute): 57 | if node.attr != self.name: 58 | raise ASTPlainObjMismatch(path+['attr'], node.attr, self.name) 59 | else: 60 | raise ASTNodeTypeMismatch(path, node, "Name or Attribute") 61 | 62 | class single_assign: 63 | """Checker for :class:`ast.Assign` or :class:`ast.AnnAssign` 64 | 65 | :class:`~ast.Assign` is a plain assignment. This will match only assignments 66 | to a single target (``a = 1`` but not ``a = b = 1``). 67 | :class:`~ast.AnnAssign` is an annotated assignment, like ``a: int = 7``. 68 | *target* and *value* may be AST nodes to check, so this would match any 69 | assignment to ``a``:: 70 | 71 | astcheck.single_assign(target=ast.Name(id='a')) 72 | 73 | Annotated assignments don't necessarily have a value: ``a: int`` is parsed 74 | as an :class:`~ast.AnnAssign` node. Use :func:`must_exist` to avoid matching 75 | these:: 76 | 77 | astcheck.single_assign(target=ast.Name(id='a'), value=astcheck.must_exist) 78 | """ 79 | def __init__(self, target=None, value=None): 80 | self.target = target 81 | self.value = value 82 | 83 | def __repr__(self): 84 | return "astcheck.single_assign(%r, %r)" % (self.target, self.value) 85 | 86 | def __call__(self, node, path): 87 | if isinstance(node, ast.Assign): 88 | if len(node.targets) != 1: 89 | raise ASTNodeListMismatch(path+['targets'], node.targets, [self.target]) 90 | if self.target is not None: 91 | assert_ast_like(node.targets[0], self.target, path + ['targets', 0]) 92 | if self.value is not None: 93 | assert_ast_like(node.value, self.value, path + ['value']) 94 | elif hasattr(ast, 'AnnAssign') and isinstance(node, ast.AnnAssign): 95 | if self.target is not None: 96 | assert_ast_like(node.target, self.target, path + ['target']) 97 | if self.value is not None: 98 | assert_ast_like(node.value, self.value, path + ['value']) 99 | else: 100 | raise ASTNodeTypeMismatch(path, node, "Assign or AnnAssign") 101 | 102 | class listmiddle(object): 103 | def __init__(self, front=None, back=None): 104 | super(listmiddle, self).__init__() 105 | self.front = front or [] 106 | self.back = back or [] 107 | 108 | def __radd__(self, other): 109 | if not isinstance(other, list): 110 | raise TypeError("Cannot add {} and listmiddle objects".format(type(other))) 111 | return listmiddle(other+self.front, self.back) 112 | 113 | def __add__(self, other): 114 | if not isinstance(other, list): 115 | raise TypeError("Cannot add listmiddle and {} objects".format(type(other))) 116 | return listmiddle(self.front, self.back + other) 117 | 118 | def __call__(self, sample_list, path): 119 | if not isinstance(sample_list, list): 120 | raise ASTNodeTypeMismatch(path, sample_list, list) 121 | 122 | if self.front: 123 | nfront = len(self.front) 124 | if len(sample_list) < nfront: 125 | raise ASTNodeListMismatch(path+[''], sample_list, self.front) 126 | _check_node_list(path, sample_list[:nfront], self.front) 127 | if self.back: 128 | nback = len(self.back) 129 | if len(sample_list) < nback: 130 | raise ASTNodeListMismatch(path+[''], sample_list, self.back) 131 | _check_node_list(path, sample_list[-nback:], self.back, -nback) 132 | 133 | def format_path(path): 134 | formed = path[:1] 135 | for part in path[1:]: 136 | if isinstance(part, int): 137 | formed.append("[%d]" % part) 138 | else: 139 | formed.append("."+part) 140 | return "".join(formed) 141 | 142 | class ASTMismatch(AssertionError): 143 | """Base exception for differing ASTs.""" 144 | def __init__(self, path, got, expected): 145 | self.path = path 146 | self.expected = expected 147 | self.got = got 148 | 149 | def __str__(self): 150 | return ("Mismatch at {}.\n" 151 | "Found : {}\n" 152 | "Expected: {}").format(format_path(self.path), self.got, self.expected) 153 | 154 | class ASTNodeTypeMismatch(ASTMismatch): 155 | """An AST node was of the wrong type.""" 156 | def __str__(self): 157 | expected = type(self.expected).__name__ if isinstance(self.expected, ast.AST) else self.expected 158 | return "At {}, found {} node instead of {}".format(format_path(self.path), 159 | type(self.got).__name__, expected) 160 | 161 | class ASTNodeListMismatch(ASTMismatch): 162 | """A list of AST nodes had the wrong length.""" 163 | def __str__(self): 164 | return "At {}, found {} node(s) instead of {}".format(format_path(self.path), 165 | len(self.got), len(self.expected)) 166 | 167 | class ASTPlainListMismatch(ASTMismatch): 168 | """A list of non-AST objects did not match. 169 | 170 | e.g. A :class:`ast.Global` node has a ``names`` list of plain strings 171 | """ 172 | def __str__(self): 173 | return ("At {}, lists differ.\n" 174 | "Found : {}\n" 175 | "Expected: {}").format(format_path(self.path), self.got, self.expected) 176 | 177 | class ASTPlainObjMismatch(ASTMismatch): 178 | """A single value, such as a variable name, did not match.""" 179 | def __str__(self): 180 | return "At {}, found {!r} instead of {!r}".format(format_path(self.path), 181 | self.got, self.expected) 182 | 183 | def _check_node_list(path, sample, template, start_enumerate=0): 184 | """Check a list of nodes, e.g. function body""" 185 | if len(sample) != len(template): 186 | raise ASTNodeListMismatch(path, sample, template) 187 | 188 | for i, (sample_node, template_node) in enumerate(zip(sample, template), start=start_enumerate): 189 | if callable(template_node): 190 | # Checker function inside a list 191 | template_node(sample_node, path+[i]) 192 | else: 193 | assert_ast_like(sample_node, template_node, path+[i]) 194 | 195 | def assert_ast_like(sample, template, _path=None): 196 | """Check that the sample AST matches the template. 197 | 198 | Raises a suitable subclass of :exc:`ASTMismatch` if a difference is detected. 199 | 200 | The ``_path`` parameter is used for recursion; you shouldn't normally pass it. 201 | """ 202 | if _path is None: 203 | _path = ['tree'] 204 | 205 | if callable(template): 206 | # Checker function at the top level 207 | return template(sample, _path) 208 | 209 | if not isinstance(sample, type(template)): 210 | raise ASTNodeTypeMismatch(_path, sample, template) 211 | 212 | for name, template_field in ast.iter_fields(template): 213 | sample_field = getattr(sample, name) 214 | field_path = _path + [name] 215 | 216 | if isinstance(template_field, list): 217 | if template_field and (isinstance(template_field[0], ast.AST) 218 | or callable(template_field[0])): 219 | _check_node_list(field_path, sample_field, template_field) 220 | else: 221 | # List of plain values, e.g. 'global' statement names 222 | if sample_field != template_field: 223 | raise ASTPlainListMismatch(field_path, sample_field, template_field) 224 | 225 | elif isinstance(template_field, ast.AST): 226 | assert_ast_like(sample_field, template_field, field_path) 227 | 228 | elif callable(template_field): 229 | # Checker function 230 | template_field(sample_field, field_path) 231 | 232 | # From Python 3.9, fields can't be entirely absent, as they could 233 | # in earlier versions, so None means unspecified. To specify a field 234 | # should be None, use must_not_exist. 235 | elif template_field is not None: 236 | # Single value, e.g. Name.id 237 | if sample_field != template_field: 238 | raise ASTPlainObjMismatch(field_path, sample_field, template_field) 239 | 240 | def is_ast_like(sample, template): 241 | """Returns True if the sample AST matches the template.""" 242 | try: 243 | assert_ast_like(sample, template) 244 | return True 245 | except ASTMismatch: 246 | return False 247 | -------------------------------------------------------------------------------- /test_astcheck.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import unittest 3 | import re 4 | 5 | import pytest 6 | 7 | import ast 8 | import astcheck 9 | from astcheck import (assert_ast_like, is_ast_like, mkarg, format_path, 10 | listmiddle, name_or_attr, 11 | ) 12 | 13 | sample1_code = """ 14 | def foobar(z, y, a, x, d): 15 | pass 16 | 17 | b, subfunc, a, x = foobar(z, y, a, x, d) 18 | """ 19 | sample1 = ast.parse(sample1_code) 20 | 21 | template1 = ast.Module(body=[ 22 | ast.FunctionDef(name="foobar", args=ast.arguments(args=[ 23 | mkarg(name) for name in ['z', 'y', 'a', 'x', 'd'] 24 | ])), 25 | ast.Assign(targets=[ast.Tuple(ctx=ast.Store(), names=[ 26 | ast.Name(id=id, ctx=ast.Store()) for id in ['b', 'subfunc', 'a', 'x'] 27 | ])], 28 | value = ast.Call(func=ast.Name(id="foobar", ctx=ast.Load()), 29 | args=[ 30 | ast.Name(id=id, ctx=ast.Load()) for id in ['z', 'y', 'a', 'x', 'd'] 31 | ]) 32 | ) 33 | ]) 34 | 35 | template1_wrongnode = ast.Module(body=[ 36 | ast.FunctionDef(name="foobar", args=ast.arguments(args=[ 37 | mkarg(name) for name in ['z', 'y', 'a', 'x', 'd'] 38 | ])), 39 | ast.Pass() 40 | ]) 41 | 42 | template1_wrongnodelist = ast.Module(body=[ 43 | ast.FunctionDef(name="foobar", args=ast.arguments(args=[ 44 | mkarg(name) for name in ['z', 'y', 'a', 'x'] 45 | ])), 46 | ast.Assign(targets=[ast.Tuple(ctx=ast.Store(), names=[ 47 | ast.Name(id=id, ctx=ast.Store()) for id in ['b', 'subfunc', 'a', 'x'] 48 | ])], 49 | value = ast.Call(func=ast.Name(id="foobar", ctx=ast.Load()), 50 | args=[ 51 | ast.Name(id=id, ctx=ast.Load()) for id in ['z', 'y', 'a', 'x', 'd'] 52 | ]) 53 | ) 54 | ]) 55 | 56 | template1_wrongvalue = ast.Module(body=[ 57 | ast.FunctionDef(name="foobar", args=ast.arguments(args=[ 58 | mkarg(name) for name in ['z', 'y', 'a', 'x', 'e'] 59 | ])), 60 | ast.Assign(targets=[ast.Tuple(ctx=ast.Store(), names=[ 61 | ast.Name(id=id, ctx=ast.Store()) for id in ['b', 'subfunc', 'a', 'x'] 62 | ])], 63 | value = ast.Call(func=ast.Name(id="foobar", ctx=ast.Load()), 64 | args=[ 65 | ast.Name(id=id, ctx=ast.Load()) for id in ['z', 'y', 'a', 'x', 'd'] 66 | ]) 67 | ) 68 | ]) 69 | 70 | sample2_code = """ 71 | def foo(): 72 | global x 73 | """ 74 | 75 | sample2 = ast.parse(sample2_code) 76 | 77 | template2 = ast.Module(body=[ 78 | ast.FunctionDef(name="foo", args=ast.arguments(args=[]), body=[ 79 | ast.Global(names=['x']) 80 | ]) 81 | ]) 82 | 83 | template2_wronglist = ast.Module(body=[ 84 | ast.FunctionDef(name="foo", args=ast.arguments(args=[]), body=[ 85 | ast.Global(names=['x', 'y']) 86 | ]) 87 | ]) 88 | 89 | class AstCheckTests(unittest.TestCase): 90 | def test_matching(self): 91 | assert_ast_like(sample1, template1) 92 | assert is_ast_like(sample1, template1) 93 | assert_ast_like(sample2, template2) 94 | assert is_ast_like(sample2, template2) 95 | 96 | def test_wrongnode(self): 97 | with self.assertRaises(astcheck.ASTNodeTypeMismatch): 98 | assert_ast_like(sample1, template1_wrongnode) 99 | assert not is_ast_like(sample1, template1_wrongnode) 100 | 101 | def test_wrong_nodelist(self): 102 | with self.assertRaisesRegex(astcheck.ASTNodeListMismatch, re.escape("5 node(s) instead of 4")): 103 | assert_ast_like(sample1, template1_wrongnodelist) 104 | assert not is_ast_like(sample1, template1_wrongnodelist) 105 | 106 | def test_wrong_plain_value(self): 107 | with self.assertRaisesRegex(astcheck.ASTPlainObjMismatch, "'d' instead of 'e'"): 108 | assert_ast_like(sample1, template1_wrongvalue) 109 | assert not is_ast_like(sample1, template1_wrongvalue) 110 | 111 | def test_wrong_plain_list(self): 112 | with self.assertRaisesRegex(astcheck.ASTPlainListMismatch, re.escape("Expected: ['x', 'y']")): 113 | assert_ast_like(sample2, template2_wronglist) 114 | assert not is_ast_like(sample2, template2_wronglist) 115 | 116 | def test_format_path(): 117 | assert format_path(['tree', 'body', 0, 'name']) == 'tree.body[0].name' 118 | 119 | sample3_code = """ 120 | del a 121 | del b 122 | del c 123 | del d 124 | """ 125 | 126 | sample3 = ast.parse(sample3_code) 127 | 128 | template3 = ast.Module(body=[ast.Delete(targets=[ast.Name(id='a')])] \ 129 | + listmiddle() \ 130 | + [ast.Delete(targets=[ast.Name(id='d')])]) 131 | 132 | template3_too_few_nodes = ast.Module( 133 | body=[ast.Delete(targets=[ast.Name(id=n)]) for n in 'abcde'] + listmiddle() 134 | ) 135 | 136 | template3_wrong_front = ast.Module( 137 | body=[ast.Delete(targets=[ast.Name(id='q')])] + listmiddle() 138 | ) 139 | 140 | template3_wrong_back = ast.Module( 141 | body= listmiddle() + [ast.Delete(targets=[ast.Name(id='q')])] 142 | ) 143 | 144 | template3_wrong_node_type = ast.Module( 145 | body=listmiddle() + [ast.Pass()] 146 | ) 147 | 148 | class TestPartialNodeLists(unittest.TestCase): 149 | def test_matching(self): 150 | assert_ast_like(sample3, template3) 151 | assert is_ast_like(sample3, template3) 152 | assert isinstance(template3.body.front[0], ast.Delete) 153 | assert isinstance(template3.body.back[0], ast.Delete) 154 | 155 | def test_too_few_nodes(self): 156 | with self.assertRaises(astcheck.ASTNodeListMismatch) as raised: 157 | assert_ast_like(sample3, template3_too_few_nodes) 158 | 159 | assert raised.exception.path == ['tree', 'body', ''] 160 | 161 | def test_wrong_front(self): 162 | with self.assertRaises(astcheck.ASTPlainObjMismatch) as raised: 163 | assert_ast_like(sample3, template3_wrong_front) 164 | 165 | assert raised.exception.path[:3] == ['tree', 'body', 0] 166 | 167 | def test_wrong_back(self): 168 | with self.assertRaises(astcheck.ASTPlainObjMismatch) as raised: 169 | assert_ast_like(sample3, template3_wrong_back) 170 | 171 | assert raised.exception.path[:3] == ['tree', 'body', -1] 172 | 173 | def test_wrong_node_type(self): 174 | with self.assertRaises(astcheck.ASTNodeTypeMismatch) as raised: 175 | assert_ast_like(sample3, template3_wrong_node_type) 176 | 177 | assert raised.exception.path == ['tree', 'body', -1] 178 | 179 | sample4_code = "a.b * c + 4" 180 | sample4 = ast.parse(sample4_code, mode='eval') 181 | 182 | template4 = ast.Expression(body=ast.BinOp( 183 | left=ast.BinOp(left=name_or_attr('b'), op=ast.Mult(), right=name_or_attr('c')), 184 | op = ast.Add(), right=ast.Constant(value=4) 185 | ) 186 | ) 187 | 188 | template4_not_name_or_attr = ast.Expression(body=ast.BinOp(right=name_or_attr('x'))) 189 | 190 | template4_name_wrong = ast.Expression(body=ast.BinOp( 191 | left=ast.BinOp(right=name_or_attr('d')) 192 | )) 193 | 194 | template4_attr_wrong = ast.Expression(body=ast.BinOp( 195 | left=ast.BinOp(left=name_or_attr('d')) 196 | )) 197 | 198 | class TestNameOrAttr(unittest.TestCase): 199 | def test_name_or_attr_correct(self): 200 | assert_ast_like(sample4, template4) 201 | assert is_ast_like(sample4, template4) 202 | 203 | def test_not_name_or_attr(self): 204 | with self.assertRaises(astcheck.ASTNodeTypeMismatch) as raised: 205 | assert_ast_like(sample4, template4_not_name_or_attr) 206 | 207 | assert raised.exception.path == ['tree', 'body', 'right'] 208 | 209 | def test_name_wrong(self): 210 | with self.assertRaises(astcheck.ASTPlainObjMismatch) as raised: 211 | assert_ast_like(sample4, template4_name_wrong) 212 | 213 | assert raised.exception.path == ['tree', 'body', 'left', 'right', 'id'] 214 | 215 | def test_attr_wrong(self): 216 | with self.assertRaises(astcheck.ASTPlainObjMismatch) as raised: 217 | assert_ast_like(sample4, template4_attr_wrong) 218 | 219 | assert raised.exception.path == ['tree', 'body', 'left', 'left', 'attr'] 220 | 221 | assign_sample_code = """ 222 | a = 1 223 | c = d = 3 224 | e.f = 4 225 | """ 226 | assign_sample = ast.parse(assign_sample_code, mode='exec') 227 | 228 | def test_single_assign(): 229 | assert_ast_like(assign_sample.body[0], astcheck.single_assign()) 230 | with pytest.raises(astcheck.ASTNodeListMismatch): 231 | assert_ast_like(assign_sample.body[1], astcheck.single_assign()) 232 | assert_ast_like(assign_sample.body[2], astcheck.single_assign()) 233 | 234 | def test_single_assign_target_value(): 235 | assert_ast_like(assign_sample.body[0], astcheck.single_assign( 236 | target=ast.Name(id='a'), value=ast.Constant(1), 237 | )) 238 | with pytest.raises(astcheck.ASTPlainObjMismatch): 239 | assert_ast_like(assign_sample.body[0], astcheck.single_assign( 240 | target=ast.Name(id='z') 241 | )) 242 | with pytest.raises(astcheck.ASTPlainObjMismatch): 243 | assert_ast_like(assign_sample.body[0], astcheck.single_assign( 244 | value=ast.Constant(99) 245 | )) 246 | 247 | assert_ast_like(assign_sample.body[2], astcheck.single_assign( 248 | target=astcheck.name_or_attr('f'), value=ast.Constant(4), 249 | )) 250 | with pytest.raises(astcheck.ASTPlainObjMismatch): 251 | assert_ast_like(assign_sample.body[2], astcheck.single_assign( 252 | target=astcheck.name_or_attr('z') 253 | )) 254 | 255 | 256 | @pytest.mark.skipif(sys.version_info < (3, 6), reason="Python < 3.6") 257 | def test_single_assign_annotated(): 258 | ann_assign_sample_code = ( 259 | "b: int = 2\n" 260 | "g.h: int = 5" 261 | ) 262 | b, g_h = ast.parse(ann_assign_sample_code, mode='exec').body 263 | 264 | assert_ast_like(b, astcheck.single_assign()) 265 | assert_ast_like(b, astcheck.single_assign( 266 | target=ast.Name(id='b'), value=ast.Constant(2), 267 | )) 268 | with pytest.raises(astcheck.ASTPlainObjMismatch): 269 | assert_ast_like(b, astcheck.single_assign( 270 | target=ast.Name(id='z') 271 | )) 272 | with pytest.raises(astcheck.ASTPlainObjMismatch): 273 | assert_ast_like(b, astcheck.single_assign( 274 | value=ast.Constant(99) 275 | )) 276 | 277 | assert_ast_like(g_h, astcheck.single_assign()) 278 | assert_ast_like(g_h, astcheck.single_assign( 279 | target=astcheck.name_or_attr('h'), value=ast.Constant(5), 280 | )) 281 | with pytest.raises(astcheck.ASTPlainObjMismatch): 282 | assert_ast_like(g_h, astcheck.single_assign( 283 | target=astcheck.name_or_attr('z') 284 | )) 285 | 286 | 287 | number_sample_code = "9 - 4" 288 | number_sample = ast.parse(number_sample_code, mode='eval') 289 | 290 | def less_than_seven(node, path): 291 | if not isinstance(node, ast.Constant): 292 | raise astcheck.ASTNodeTypeMismatch(path, node, ast.Constant()) 293 | n = node.value 294 | if not isinstance(n, (int, float)): 295 | raise astcheck.ASTNodeTypeMismatch(path, node, 'number') 296 | if n >= 7: 297 | raise astcheck.ASTMismatch(path+['n'], node.value, '< 7') 298 | 299 | number_template_ok = ast.Expression(body=ast.BinOp(left=ast.Constant(value=9), 300 | op=ast.Sub(), right=less_than_seven 301 | )) 302 | 303 | number_template_wrong = ast.Expression(body=ast.BinOp(left=less_than_seven)) 304 | 305 | for_else_sample_code = """for a in b: 306 | pass 307 | else: 308 | pass 309 | """ 310 | 311 | for_else_sample = ast.parse(for_else_sample_code) 312 | 313 | for_noelse_sample_code = """for a in b: 314 | pass 315 | """ 316 | 317 | for_noelse_sample = ast.parse(for_noelse_sample_code) 318 | 319 | for_else_template = ast.For(orelse=astcheck.must_exist) 320 | 321 | for_noelse_template = ast.For(orelse=astcheck.must_not_exist) 322 | 323 | class TestCheckerFunction(unittest.TestCase): 324 | def test_lt_7(self): 325 | assert_ast_like(number_sample, number_template_ok) 326 | 327 | def test_lt_7_wrong(self): 328 | with self.assertRaisesRegex(astcheck.ASTMismatch, "Expected: < 7") as raised: 329 | assert_ast_like(number_sample, number_template_wrong) 330 | 331 | assert raised.exception.path == ['tree', 'body', 'left', 'n'] 332 | 333 | def test_must_exist(self): 334 | assert_ast_like(for_else_sample.body[0], for_else_template) 335 | 336 | with self.assertRaisesRegex(astcheck.ASTMismatch, "Expected: non empty") as raised: 337 | assert_ast_like(for_noelse_sample.body[0], for_else_template) 338 | 339 | assert raised.exception.path == ['tree', 'orelse'] 340 | 341 | def test_must_not_exist(self): 342 | assert_ast_like(for_noelse_sample.body[0], for_noelse_template) 343 | 344 | with self.assertRaisesRegex(astcheck.ASTMismatch, "Expected: nothing") as raised: 345 | assert_ast_like(for_else_sample.body[0], for_noelse_template) 346 | 347 | assert raised.exception.path == ['tree', 'orelse'] 348 | 349 | 350 | def test_missing_field(): 351 | mod = ast.parse("import foo as bar") 352 | assert_ast_like(mod.body[0], ast.Import(names=[ast.alias(name='foo')])) 353 | --------------------------------------------------------------------------------