testpath-0.3.1/000077500000000000000000000000001311130627200133435ustar00rootroot00000000000000testpath-0.3.1/.gitignore000066400000000000000000000000671311130627200153360ustar00rootroot00000000000000__pycache__ *.pyc /doc/_build /MANIFEST /build/ /dist/ testpath-0.3.1/.travis.yml000066400000000000000000000004251311130627200154550ustar00rootroot00000000000000language: python python: - "2.7" - "3.3" - "3.4" # command to run tests script: py.test install: if [[ $TRAVIS_PYTHON_VERSION == 2.7 ]] || [[ $TRAVIS_PYTHON_VERSION == 3.3 ]]; then pip install pathlib2; fi # Enable new Travis stack, should speed up builds sudo: false testpath-0.3.1/LICENSE000066400000000000000000000021101311130627200143420ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015, The Jupyter Development Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. testpath-0.3.1/README.rst000066400000000000000000000006721311130627200150370ustar00rootroot00000000000000Testpath is a collection of utilities for Python code working with files and commands. It contains functions to check things on the filesystem, and tools for mocking system commands and recording calls to those. `Documentation on ReadTheDocs `_ e.g.:: import testpath testpath.assert_isfile(path) with testpath.assert_calls('git', ['add', path]): function_under_test() testpath-0.3.1/doc/000077500000000000000000000000001311130627200141105ustar00rootroot00000000000000testpath-0.3.1/doc/Makefile000066400000000000000000000151621311130627200155550ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(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/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Testpath.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Testpath.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Testpath" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Testpath" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." testpath-0.3.1/doc/commands.rst000066400000000000000000000020541311130627200164440ustar00rootroot00000000000000Mocking system commands ======================= Mocking is a technique to replace parts of a system with interfaces that don't do anything, but which your tests can check whether and how they were called. The :mod:`unittest.mock` module in Python 3 lets you mock Python functions and classes. These tools let you mock external commands. Commands are mocked by creating a real file in a temporary directory which is added to the :envvar:`PATH` environment variable, not by replacing Python functions. So if you mock ``foo``, and your Python code runs a shell script which calls ``foo``, it will be the mocked command that it runs. By default, mocked commands record each call made to them, so that your test can check these. Using the :class:`MockCommand` API, you can mock a command to do something else. .. note:: These tools work by changing global state. They're not safe to use if commands may be called from multiple threads or coroutines. .. currentmodule:: testpath .. autofunction:: assert_calls .. autoclass:: MockCommand :members: get_calls testpath-0.3.1/doc/conf.py000066400000000000000000000203371311130627200154140ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Testpath documentation build configuration file, created by # sphinx-quickstart on Sun Feb 1 17:05:52 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Testpath' copyright = '2015, Jupyter Development Team' # 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 = '0.3.1' # 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. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Testpathdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Testpath.tex', 'Testpath Documentation', 'Jupyter Development Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'testpath', 'Testpath Documentation', ['Jupyter Development Team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Testpath', 'Testpath Documentation', 'Jupyter Development Team', 'Testpath', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'python': ('http://docs.python.org/3', None)} testpath-0.3.1/doc/env.rst000066400000000000000000000005221311130627200154310ustar00rootroot00000000000000Modifying environment variables =============================== These functions allow you to temporarily modify the environment variables, which is often useful for testing code that calls other processes. .. currentmodule:: testpath .. autofunction:: modified_env .. autofunction:: temporary_env .. autofunction:: make_env_restorer testpath-0.3.1/doc/fsasserts.rst000066400000000000000000000010301311130627200166510ustar00rootroot00000000000000Assertion functions for the filesystem ====================================== These functions make it easy to check the state of files and directories. When the assertion is not true, they provide informative error messages. .. module:: testpath .. autofunction:: assert_path_exists .. autofunction:: assert_not_path_exists .. autofunction:: assert_isfile .. autofunction:: assert_not_isfile .. autofunction:: assert_isdir .. autofunction:: assert_not_isdir .. autofunction:: assert_islink .. autofunction:: assert_not_islink testpath-0.3.1/doc/index.rst000066400000000000000000000005501311130627200157510ustar00rootroot00000000000000Testpath ======== Testpath is a collection of utilities for testing code which uses and manipulates the filesystem and system commands. Install it with:: pip install testpath Contents: .. toctree:: :maxdepth: 2 fsasserts commands env tempdir Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` testpath-0.3.1/doc/make.bat000066400000000000000000000150611311130627200155200ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Testpath.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Testpath.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end testpath-0.3.1/doc/tempdir.rst000066400000000000000000000005151311130627200163070ustar00rootroot00000000000000Utilities for temporary directories =================================== .. module:: testpath.tempdir This module exposes :func:`tempfile.TemporaryDirectory`, with a backported copy so that it can be used on Python 2. In addition, it contains: .. autoclass:: NamedFileInTemporaryDirectory .. autoclass:: TemporaryWorkingDirectory testpath-0.3.1/flit.ini000066400000000000000000000007601311130627200150050ustar00rootroot00000000000000[metadata] module=testpath author=Jupyter Development Team author-email=jupyter@googlegroups.com home-page=https://github.com/jupyter/testpath description-file=README.rst dev-requires = pathlib2; python_version == "2.7" or python_version == "3.3" classifiers = Intended Audience :: Developers License :: OSI Approved :: MIT License Programming Language :: Python Programming Language :: Python :: 2 Programming Language :: Python :: 3 Topic :: Software Development :: Testing testpath-0.3.1/testpath/000077500000000000000000000000001311130627200151775ustar00rootroot00000000000000testpath-0.3.1/testpath/__init__.py000066400000000000000000000003341311130627200173100ustar00rootroot00000000000000"""Test utilities for code working with files and commands""" from .asserts import * from .env import temporary_env, modified_env, make_env_restorer from .commands import MockCommand, assert_calls __version__ = '0.3.1' testpath-0.3.1/testpath/asserts.py000066400000000000000000000106031311130627200172350ustar00rootroot00000000000000import os import stat try: from pathlib import Path except ImportError: try: # Python 2 backport from pathlib2 import Path except ImportError: class Path(object): """Dummy for isinstance checks""" pass __all__ = ['assert_path_exists', 'assert_not_path_exists', 'assert_isfile', 'assert_not_isfile', 'assert_isdir', 'assert_not_isdir', 'assert_islink', 'assert_not_islink', ] def _strpath(p): if isinstance(p, Path): return str(p) return p def _stat_for_assert(path, follow_symlinks=True, msg=None): stat = os.stat if follow_symlinks else os.lstat try: return stat(path) except OSError: if msg is None: msg = "Path does not exist, or can't be stat-ed: %r" % path raise AssertionError(msg) def assert_path_exists(path, msg=None): """Assert that something exists at the given path. """ _stat_for_assert(_strpath(path), True, msg) def assert_not_path_exists(path, msg=None): """Assert that nothing exists at the given path. """ path = _strpath(path) if os.path.exists(path): if msg is None: msg = "Path exists: %r" % path raise AssertionError(msg) def assert_isfile(path, follow_symlinks=True, msg=None): """Assert that path exists and is a regular file. With follow_symlinks=True, the default, this will pass if path is a symlink to a regular file. With follow_symlinks=False, it will fail in that case. """ path = _strpath(path) st = _stat_for_assert(path, follow_symlinks, msg) if not stat.S_ISREG(st.st_mode): if msg is None: msg = "Path exists, but is not a regular file: %r" % path raise AssertionError(msg) def assert_not_isfile(path, follow_symlinks=True, msg=None): """Assert that path exists but is not a regular file. With follow_symlinks=True, the default, this will fail if path is a symlink to a regular file. With follow_symlinks=False, it will pass in that case. """ path = _strpath(path) st = _stat_for_assert(path, follow_symlinks, msg) if stat.S_ISREG(st.st_mode): if msg is None: msg = "Path is a regular file: %r" % path raise AssertionError(msg) def assert_isdir(path, follow_symlinks=True, msg=None): """Assert that path exists and is a directory. With follow_symlinks=True, the default, this will pass if path is a symlink to a directory. With follow_symlinks=False, it will fail in that case. """ path = _strpath(path) st = _stat_for_assert(path, follow_symlinks, msg) if not stat.S_ISDIR(st.st_mode): if msg is None: msg = "Path exists, but is not a directory: %r" % path raise AssertionError(msg) def assert_not_isdir(path, follow_symlinks=True, msg=None): """Assert that path exists but is not a directory. With follow_symlinks=True, the default, this will fail if path is a symlink to a directory. With follow_symlinks=False, it will pass in that case. """ path = _strpath(path) st = _stat_for_assert(path, follow_symlinks, msg) if stat.S_ISDIR(st.st_mode): if msg is None: msg = "Path is a directory: %r" % path raise AssertionError(msg) _link_target_msg = """Symlink target of: {path} Expected: {expected} Actual: {actual} """ def assert_islink(path, to=None, msg=None): """Assert that path exists and is a symlink. If to is specified, also check that it is the target of the symlink. """ path = _strpath(path) st = _stat_for_assert(path, False, msg) if not stat.S_ISLNK(st.st_mode): if msg is None: msg = "Path exists, but is not a symlink: %r" % path raise AssertionError(msg) if to is not None: to = _strpath(to) target = os.readlink(path) # TODO: Normalise the target to an absolute path? if target != to: if msg is None: msg = _link_target_msg.format(path=path, expected=to, actual=target) raise AssertionError(msg) def assert_not_islink(path, msg=None): """Assert that path exists but is not a symlink. """ path = _strpath(path) st = _stat_for_assert(path, False, msg) if stat.S_ISLNK(st.st_mode): if msg is None: msg = "Path is a symlink: %r" % path raise AssertionError(msg) testpath-0.3.1/testpath/commands.py000066400000000000000000000120271311130627200173540ustar00rootroot00000000000000import contextlib import json import os import shutil import sys import tempfile __all__ = ['MockCommand', 'assert_calls'] pkgdir = os.path.dirname(__file__) commands_dir = None recording_dir = None def prepend_to_path(dir): os.environ['PATH'] = dir + os.pathsep + os.environ['PATH'] def remove_from_path(dir): path_dirs = os.environ['PATH'].split(os.pathsep) path_dirs.remove(dir) os.environ['PATH'] = os.pathsep.join(path_dirs) _record_run = """#!{python} import os, sys import json with open({recording_file!r}, 'a') as f: json.dump({{'env': dict(os.environ), 'argv': sys.argv, 'cwd': os.getcwd()}}, f) f.write('\\x1e') # ASCII record separator """ # TODO: Overlapping calls to the same command may interleave writes. class MockCommand(object): """Context manager to mock a system command. The mock command will be written to a directory at the front of $PATH, taking precedence over any existing command with the same name. By specifying content as a string, you can determine what running the command will do. The default content records each time the command is called and exits: you can access these records with mockcmd.get_calls(). On Windows, the specified content will be run by the Python interpreter in use. On Unix, it should start with a shebang (``#!/path/to/interpreter``). """ def __init__(self, name, content=None): global recording_dir self.name = name self.content = content if recording_dir is None: recording_dir = tempfile.mkdtemp() fd, self.recording_file = tempfile.mkstemp(dir=recording_dir, prefix=name, suffix='.json') os.close(fd) def _copy_exe(self): bitness = '32' if (sys.maxsize > 2**32) else '64' src = os.path.join(pkgdir, 'cli-%s.exe' % bitness) dst = os.path.join(commands_dir, self.name+'.exe') shutil.copy(src, dst) @property def _cmd_path(self): # Can only be used once commands_dir has been set p = os.path.join(commands_dir, self.name) if os.name == 'nt': p += '-script.py' return p def __enter__(self): global commands_dir if commands_dir is None: commands_dir = tempfile.mkdtemp() if os.path.isfile(self._cmd_path): raise EnvironmentError("Command %r already exists at %s" % (self.name, self._cmd_path)) if commands_dir not in os.environ['PATH'].split(os.pathsep): prepend_to_path(commands_dir) if self.content is None: self.content = _record_run.format(python=sys.executable, recording_file=self.recording_file) with open(self._cmd_path, 'w') as f: f.write(self.content) if os.name == 'nt': self._copy_exe() else: os.chmod(self._cmd_path, 0o755) # Set executable bit return self def __exit__(self, etype, evalue, tb): os.remove(self._cmd_path) if os.name == 'nt': os.remove(os.path.join(commands_dir, self.name+'.exe')) if not os.listdir(commands_dir): remove_from_path(commands_dir) def get_calls(self): """Get a list of calls made to this mocked command. This relies on the default script content, so it will return an empty list if you specified a different content parameter. For each time the command was run, the list will contain a dictionary with keys argv, env and cwd. """ if recording_dir is None: return [] if not os.path.isfile(self.recording_file): return [] with open(self.recording_file, 'r') as f: # 1E is ASCII record separator, last chunk is empty chunks = f.read().split('\x1e')[:-1] return [json.loads(c) for c in chunks] @contextlib.contextmanager def assert_calls(cmd, args=None): """Assert that a block of code runs the given command. If args is passed, also check that it was called at least once with the given arguments (not including the command name). Use as a context manager, e.g.:: with assert_calls('git'): some_function_wrapping_git() with assert_calls('git', ['add', myfile]): some_other_function() """ with MockCommand(cmd) as mc: yield calls = mc.get_calls() assert calls != [], "Command %r was not called" % cmd if args is not None: if not any(args == c['argv'][1:] for c in calls): msg = ["Command %r was not called with specified args (%r)" % (cmd, args), "It was called with these arguments: "] for c in calls: msg.append(' %r' % c['argv'][1:]) raise AssertionError('\n'.join(msg)) testpath-0.3.1/testpath/env.py000066400000000000000000000045021311130627200163420ustar00rootroot00000000000000import contextlib import os @contextlib.contextmanager def temporary_env(newenv): """Completely replace the environment variables with the specified dict. Use as a context manager:: with temporary_env({'PATH': my_path}): ... """ orig_env = os.environ.copy() os.environ.clear() os.environ.update(newenv) try: yield finally: os.environ.clear() os.environ.update(orig_env) @contextlib.contextmanager def modified_env(changes, snapshot=True): """Temporarily modify environment variables. Specify the changes as a dictionary mapping names to new values, using None as the value for names that should be deleted. Example use:: with modified_env({'SHELL': 'bash', 'PYTHONPATH': None}): ... When the context exits, there are two possible ways to restore the environment. If *snapshot* is True, the default, it will reset the whole environment to its state when the context was entered. If *snapshot* is False, it will restore only the specific variables it modified, leaving any changes made to other environment variables in the context. """ def update_del(changes): for k, v in changes.items(): if v is None: os.environ.pop(k, None) else: os.environ[k] = v if snapshot: saved_variables = os.environ.copy() else: saved_variables = {} for k,v in changes.items(): saved_variables[k] = os.environ.get(k, None) update_del(changes) try: yield finally: if snapshot: os.environ.clear() os.environ.update(saved_variables) else: update_del(saved_variables) def make_env_restorer(): """Snapshot the current environment, return a function to restore that. This is intended to produce cleanup functions for tests. For example, using the :class:`unittest.TestCase` API:: def setUp(self): self.addCleanup(testpath.make_env_restorer()) Any changes a test makes to the environment variables will be wiped out before the next test is run. """ orig_env = os.environ.copy() def restore(): os.environ.clear() os.environ.update(orig_env) return restore testpath-0.3.1/testpath/tempdir.py000066400000000000000000000121751311130627200172230ustar00rootroot00000000000000"""TemporaryDirectory class, copied from Python 3 NamedFileInTemporaryDirectory and TemporaryWorkingDirectory from IPython, which uses the 3-clause BSD license. """ from __future__ import print_function import os as _os import warnings as _warnings import sys as _sys # This code should only be used in Python versions < 3.2, since after that we # can rely on the stdlib itself. try: from tempfile import TemporaryDirectory except ImportError: from tempfile import mkdtemp, template class TemporaryDirectory(object): """Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: with TemporaryDirectory() as tmpdir: ... Upon exiting the context, the directory and everthing contained in it are removed. """ def __init__(self, suffix="", prefix=template, dir=None): self.name = mkdtemp(suffix, prefix, dir) self._closed = False def __enter__(self): return self.name def cleanup(self, _warn=False): if self.name and not self._closed: try: self._rmtree(self.name) except (TypeError, AttributeError) as ex: # Issue #10188: Emit a warning on stderr # if the directory could not be cleaned # up due to missing globals if "None" not in str(ex): raise print("ERROR: {!r} while cleaning up {!r}".format(ex, self,), file=_sys.stderr) return self._closed = True if _warn: self._warn("Implicitly cleaning up {!r}".format(self), Warning) def __exit__(self, exc, value, tb): self.cleanup() def __del__(self): # Issue a ResourceWarning if implicit cleanup needed self.cleanup(_warn=True) # XXX (ncoghlan): The following code attempts to make # this class tolerant of the module nulling out process # that happens during CPython interpreter shutdown # Alas, it doesn't actually manage it. See issue #10188 _listdir = staticmethod(_os.listdir) _path_join = staticmethod(_os.path.join) _isdir = staticmethod(_os.path.isdir) _remove = staticmethod(_os.remove) _rmdir = staticmethod(_os.rmdir) _os_error = _os.error _warn = _warnings.warn def _rmtree(self, path): # Essentially a stripped down version of shutil.rmtree. We can't # use globals because they may be None'ed out at shutdown. for name in self._listdir(path): fullname = self._path_join(path, name) try: isdir = self._isdir(fullname) except self._os_error: isdir = False if isdir: self._rmtree(fullname) else: try: self._remove(fullname) except self._os_error: pass try: self._rmdir(path) except self._os_error: pass class NamedFileInTemporaryDirectory(object): """Open a file named `filename` in a temporary directory. This context manager is preferred over :class:`tempfile.NamedTemporaryFile` when one needs to reopen the file, because on Windows only one handle on a file can be open at a time. You can close the returned handle explicitly inside the context without deleting the file, and the context manager will delete the whole directory when it exits. Arguments `mode` and `bufsize` are passed to `open`. Rest of the arguments are passed to `TemporaryDirectory`. Usage example:: with NamedFileInTemporaryDirectory('myfile', 'wb') as f: f.write('stuff') f.close() # You can now pass f.name to things that will re-open the file """ def __init__(self, filename, mode='w+b', bufsize=-1, **kwds): self._tmpdir = TemporaryDirectory(**kwds) path = _os.path.join(self._tmpdir.name, filename) self.file = open(path, mode, bufsize) def cleanup(self): self.file.close() self._tmpdir.cleanup() __del__ = cleanup def __enter__(self): return self.file def __exit__(self, type, value, traceback): self.cleanup() class TemporaryWorkingDirectory(TemporaryDirectory): """ Creates a temporary directory and sets the cwd to that directory. Automatically reverts to previous cwd upon cleanup. Usage example:: with TemporaryWorkingDirectory() as tmpdir: ... """ def __enter__(self): self.old_wd = _os.getcwd() _os.chdir(self.name) return super(TemporaryWorkingDirectory, self).__enter__() def __exit__(self, exc, value, tb): _os.chdir(self.old_wd) return super(TemporaryWorkingDirectory, self).__exit__(exc, value, tb) testpath-0.3.1/tests/000077500000000000000000000000001311130627200145055ustar00rootroot00000000000000testpath-0.3.1/tests/__init__.py000066400000000000000000000000001311130627200166040ustar00rootroot00000000000000testpath-0.3.1/tests/test_asserts.py000066400000000000000000000062421311130627200176060ustar00rootroot00000000000000import os import unittest try: import pathlib except ImportError: # Python 2 backport import pathlib2 as pathlib from testpath.asserts import * from testpath.tempdir import TemporaryDirectory class TestAssertFunctions(unittest.TestCase): def setUp(self): self.td = TemporaryDirectory() self.addCleanup(self.td.cleanup) self.file_path = os.path.join(self.td.name, 'afile') with open(self.file_path, 'w') as f: f.write('Blah') self.dir_path = os.path.join(self.td.name, 'adir') os.mkdir(self.dir_path) self.link_path = os.path.join(self.td.name, 'alink') if os.name == 'posix': # Symlinks are rarely usable on Windows, because a special # permission is needed to create them. os.symlink(self.file_path, self.link_path) self.nonexistant_path = os.path.join(self.td.name, 'doesntexist') def test_exists(self): assert_path_exists(self.file_path) assert_path_exists(pathlib.Path(self.file_path)) assert_not_path_exists(self.nonexistant_path) with self.assertRaises(AssertionError): assert_path_exists(self.nonexistant_path) with self.assertRaises(AssertionError): assert_not_path_exists(self.file_path) def test_isfile(self): assert_isfile(self.file_path) assert_not_isfile(self.dir_path) with self.assertRaises(AssertionError): assert_isfile(self.dir_path) with self.assertRaises(AssertionError): assert_not_isfile(self.file_path) def test_isfile_symlink(self): if os.name == 'nt': raise unittest.SkipTest('symlink') assert_isfile(self.link_path) # Follows the link by default assert_not_isfile(self.link_path, follow_symlinks=False) with self.assertRaises(AssertionError): assert_isfile(self.link_path, follow_symlinks=False) with self.assertRaises(AssertionError): assert_not_isfile(self.link_path) def test_isdir(self): assert_isdir(self.dir_path) assert_isdir(pathlib.Path(self.dir_path)) assert_not_isdir(self.file_path) with self.assertRaises(AssertionError): assert_isdir(self.file_path) with self.assertRaises(AssertionError): assert_not_isdir(self.dir_path) def test_islink(self): if os.name == 'nt': raise unittest.SkipTest('symlink') assert_islink(self.link_path, to=self.file_path) assert_islink(pathlib.Path(self.link_path), to=pathlib.Path(self.file_path)) assert_not_islink(self.file_path) with self.assertRaises(AssertionError) as c: assert_islink(self.file_path) self.assertIn('not a symlink', str(c.exception)) with self.assertRaises(AssertionError) as c: assert_islink(self.link_path, to=self.dir_path) self.assertIn('target of', str(c.exception)) with self.assertRaises(AssertionError): assert_not_islink(self.link_path) testpath-0.3.1/tests/test_commands.py000066400000000000000000000020601311130627200177150ustar00rootroot00000000000000import os from subprocess import call import unittest from testpath.commands import * class CommandsTests(unittest.TestCase): def test_assert_calls(self): initial_path = os.environ['PATH'] with assert_calls('foobar'): call(['foobar']) with self.assertRaises(AssertionError): with assert_calls('foo'): pass # The context manager should clean up $PATH again self.assertEqual(os.environ['PATH'], initial_path) def test_assert_calls_with_args(self): with assert_calls('foo', ['bar', 'baz']): call(['foo', 'bar', 'baz']) with self.assertRaises(AssertionError): with assert_calls('cheese', ['crackers']): call(['cheese', 'biscuits']) call(['cheese', 'wine']) def test_assert_calls_twice(self): with assert_calls('git'): call(['git']) with self.assertRaises(AssertionError): with assert_calls('git'): pass testpath-0.3.1/tests/test_env.py000066400000000000000000000041411311130627200167060ustar00rootroot00000000000000import os import unittest import testpath class EnvironmentUtilsTests(unittest.TestCase): def setUp(self): # We're actually using this for its specified purpose, rather than # explicitly testing it. self.addCleanup(testpath.make_env_restorer()) def test_temporary_env(self): os.environ['abc123'] = '4' os.environ['def567'] = '8' with testpath.temporary_env({'abc123': '9'}): self.assertEqual(os.environ['abc123'], '9') self.assertNotIn('def567', os.environ) os.environ['foo951'] = 'bar' self.assertEqual(os.environ['abc123'], '4') self.assertEqual(os.environ['def567'], '8') self.assertNotIn('foo951', os.environ) def test_modified_env(self): os.environ['abc123'] = '4' os.environ['def567'] = '8' os.environ['ghi789'] = '10' os.environ.pop('foo951', None) with testpath.modified_env({'abc123': '9', 'def567': None}): self.assertEqual(os.environ['abc123'], '9') self.assertNotIn('def567', os.environ) self.assertEqual(os.environ['ghi789'], '10') # Not affected os.environ['foo951'] = 'bar' self.assertEqual(os.environ['abc123'], '4') self.assertEqual(os.environ['def567'], '8') self.assertEqual(os.environ['ghi789'], '10') # Not affected self.assertNotIn('foo951', os.environ) def test_modified_env_nosnapshot(self): os.environ['abc123'] = '4' os.environ['def567'] = '8' os.environ['ghi789'] = '10' os.environ.pop('foo951', None) with testpath.modified_env({'abc123': '9', 'def567': None}, snapshot=False): self.assertEqual(os.environ['abc123'], '9') self.assertNotIn('def567', os.environ) self.assertEqual(os.environ['ghi789'], '10') # Not affected os.environ['foo951'] = 'bar' self.assertEqual(os.environ['abc123'], '4') self.assertEqual(os.environ['def567'], '8') self.assertEqual(os.environ['ghi789'], '10') self.assertEqual(os.environ['foo951'], 'bar') # Not reset