mockldap-0.2.5/0000755000076600000240000000000012540073641014102 5ustar psagersstaff00000000000000mockldap-0.2.5/CHANGES0000644000076600000240000000663212540073237015105 0ustar psagersstaff00000000000000v0.2.5 - June 16, 2015 - passwd_s --------------------------------- - A simple implementation of passwd_s. - Fixes for DN case-insensitive matching. v0.2.4 - January 26, 2015 - SSHA fix ------------------------------------ - Support SSHA passwords with salt of arbitrary length. v0.2.3 - October 23, 2014 - Fix for Windows ------------------------------------------- - Don't support {CRYPT} passwords if crypt can't be imported. v0.2.2 - July 21, 2014 - Password hashing ----------------------------------------- - Add support for {CRYPT} and {SSHA} passwords. Thanks to `Dmitri Bogomolov `_. v0.2.1 - May 13, 2014 - Fix for rename_s ---------------------------------------- - Raise ldap.ALREADY_EXISTS when renaming an object and the target already exists. v0.2.0 - April 9, 2014 - Experimental Python 3 support ------------------------------------------------------ - mockldap now provides experimental Python 3 support. Python 2.5 was dropped. To sum up, mockldap works with Python 2.6, 2.7, 3.3 and 3.4. Since python-ldap still isn't making progress toward Python 3, if you're using Python 3, you need to install a fork:: $ pip install git+https://github.com/rbarrois/python-ldap.git@py3 Thanks to `Aymeric Augustin `_ for making this happen. v0.1.8 - March 31, 2014 - Fixes for modify_s -------------------------------------------- - A previous fix to modify_s was erroneous. `section 4.6`_ of RFC 4511 states that modify operations will create new attributes and delete empty ones as necessary. .. _section 4.6: http://tools.ietf.org/html/rfc4511#section-4.6 .. warning:: mockldap wil no longer raise `ldap.UNDEFINED_TYPE`. mockldap has no schema support, so it assumes that all attributes are valid. v0.1.7 - March 7, 2014 - Filter string parser fix ------------------------------------------------- - Filter strings with '&', '|', and '!' in the assertion values should now be parsed correctly. v0.1.6 - March 6, 2014 - Add whoami_s ------------------------------------- - Add whoami_s() method. v0.1.5 - February 19, 2014 - Fix to modify_s -------------------------------------------- - MOD_DELETE should not remove the key from the directory. Thanks to https://bitbucket.org/jlec. v0.1.4 - September 20, 2013 - Miscellaneous fixes ------------------------------------------------- - Raise :exc:`~ldap.INVALID_DN_SYNTAX` for invalid DNs. - Raise :exc:`~ldap.FILTER_ERROR` on filter string parse errors. - Include the full method call signature in :exc:`~mockldap.SeedRequired` exceptions. v0.1.3 - September 18, 2013 - Python 2.5 support ------------------------------------------------ - mockldap is now compatible with Python 2.5. Since python-ldap doesn't seem to be making progress toward Python 3, there's no need to drop Python 2.5 support here yet. v0.1.2 - September 17, 2013 - Fix simple_bind_s exception --------------------------------------------------------- - simple_bind_s now raises :exc:`~ldap.INVALID_CREDENTIALS` instead of :exc:`~ldap.NO_SUCH_OBJECT` if the DN does not exist. This is consistent with the behavior of python-ldap. v0.1.1 - September 8, 2013 - Setup fixes ---------------------------------------- Minor fixes for packaging, installation, and testing. v0.1.0 - September 7, 2013 - Initial Release -------------------------------------------- Initial release. .. vim: ft=rst nospell tw=80 mockldap-0.2.5/docs/0000755000076600000240000000000012540073641015032 5ustar psagersstaff00000000000000mockldap-0.2.5/docs/Makefile0000644000076600000240000001535712212756306016507 0ustar psagersstaff00000000000000# 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) source # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .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/mockldap.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/mockldap.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/mockldap" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/mockldap" @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." zip: rm $(BUILDDIR)/html.zip || true cd $(BUILDDIR)/html && zip -R ../html.zip '*' -x .buildinfo -x '_sources/*' mockldap-0.2.5/docs/source/0000755000076600000240000000000012540073641016332 5ustar psagersstaff00000000000000mockldap-0.2.5/docs/source/changes.rst0000644000076600000240000000006212163135222020465 0ustar psagersstaff00000000000000Change Log ========== .. include:: ../../CHANGES mockldap-0.2.5/docs/source/conf.py0000644000076600000240000002015412540073321017626 0ustar psagersstaff00000000000000# -*- coding: utf-8 -*- # # mockldap documentation build configuration file, created by # sphinx-quickstart on Thu Jun 27 13:23:47 2013. # # 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 os.path import sys # 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('../../src')) # -- 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', 'sphinx.ext.viewcode', ] intersphinx_mapping = { 'python': ('http://docs.python.org/2/', 'http://docs.python.org/2/objects.inv'), 'ldap': ('http://python-ldap.org/doc/html/', None), 'mock': ('http://www.voidspace.org.uk/python/mock/', None), } # 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 = u'mockldap' copyright = u'2013, Peter Sagerson' # 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.1' # The full version, including alpha/beta/rc tags. release = '0.2.5' # 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 = [] # 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'] # 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 = 'mockldapdoc' # -- 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]). latex_documents = [ ('index', 'mockldap.tex', u'mockldap Documentation', u'Peter Sagerson', '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', 'mockldap', u'mockldap Documentation', [u'Peter Sagerson'], 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', 'mockldap', u'mockldap Documentation', u'Peter Sagerson', 'mockldap', '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 mockldap-0.2.5/docs/source/directories.rst0000644000076600000240000000601212212747142021377 0ustar psagersstaff00000000000000Mock Directories ================ The first step to using mockldap is to define some static LDAP content and install it as a mock :class:`~mockldap.LDAPObject`. For this, you will use :class:`mockldap.MockLdap`. Only one instance of this class should exist at a time; :meth:`~unittest.TestCase.setUpClass` is a good place to instantiate it. :class:`~mockldap.MockLdap` can mock multiple LDAP directories, identified by URI. You can provide directory content for URIs individually and you can also provide default content for connections to any unrecognized URI. If the code under test is only expected to make one LDAP connection, the simplest option is just to provide default content. If you need multiple directories, you can call :meth:`~mockldap.MockLdap.set_directory` on your :class:`~mockldap.MockLdap` instance. LDAP content takes the form of a Python dictionary. Each key is a distinguished name in string form; each value is a dictionary mapping attributes to lists of values. In other words, ``directory.items()`` should take the same form as results from :meth:`~ldap.LDAPObject.search_s`. :: directory = { 'uid=alice,ou=people,o=test': { 'uid': ['alice'], 'objectClass': ['person', 'organizationalPerson', 'inetOrgPerson', 'posixAccount'], 'userPassword': ['password'], 'uidNumber': ['1000'], 'gidNumber': ['1000'], 'givenName': ['Alice'], 'sn': ['Adams'] }, 'cn=active,ou=groups,o=test': { 'cn': ['active'], 'objectClass': ['groupOfNames'], 'member': ['uid=alice,ou=people,o=test'] }, } :class:`~mockldap.MockLdap` is stateful. The overview shows a complete :ref:`example `, but following are the enumerated steps. For some collection of tests: - Instantiate :class:`~mockldap.MockLdap`. Optionally pass in default directory contents. - :meth:`Add content ` for any additional directories. This is only necessary if the code under test will connect to multiple LDAP directories. For each test: - Just before an individual test, call :meth:`~mockldap.MockLdap.start`. This will instantiate your mock directories and patch :func:`ldap.initialize`. You may need to call this multiple times if :func:`~ldap.initialize` is accessed by multiple names. - Any time during your test, you can access an individual :class:`~mockldap.LDAPObject` as ``mockldap[uri]``. This will let you seed return values for LDAP operations and recover the record of which operations were performed. - After the test, call :meth:`~mockldap.MockLdap.stop` or :meth:`~mockldap.MockLdap.stop_all`. .. warning:: The code under test must not keep an LDAP "connection" open across individual test cases. If it does, it will be sharing a mock :class:`~mockldap.LDAPObject` across tests, so any state mutations will persist. MockLdap -------- .. autoclass:: mockldap.MockLdap :members: mockldap-0.2.5/docs/source/index.rst0000644000076600000240000000026312163135222020167 0ustar psagersstaff00000000000000mockldap ======== .. include:: ../../README .. toctree:: :maxdepth: 2 overview directories operations changes License ------- .. include:: ../../LICENSE mockldap-0.2.5/docs/source/operations.rst0000644000076600000240000000124112163412211021234 0ustar psagersstaff00000000000000LDAP Operations =============== Inside of an individual test, you will be performing some task that involves LDAP operations and then verifying the outcome. In some cases, you will need to prepare your mock :class:`~mockldap.LDAPObject` to return specific results for a given API call. LDAPObject ---------- .. autoclass:: mockldap.LDAPObject :members: Every LDAP method on :class:`~mockldap.LDAPObject` is actually an instance of :class:`~mockldap.recording.RecordedMethod`, which allows you to set return values in advance for different sets of arguments. .. autoclass:: mockldap.recording.RecordedMethod :members: .. autoexception:: mockldap.SeedRequired mockldap-0.2.5/docs/source/overview.rst0000644000076600000240000000740512212746641020743 0ustar psagersstaff00000000000000Overview ======== The goal of mockldap is to provide a mock instance of LDAPObject in response to any call to ldap.initialize. In the general case, you would register return values for all LDAPObject calls that you expect the code under test to make. Your assertions would then verify that the tested code behaved correctly given this set of return values from the LDAP APIs. As a convenience, the mock LDAPObject isn't just a dumb mock object. The typical way to use mockldap is to provide some static directory content and then let :class:`~mockldap.LDAPObject` generate real return values. This will only work for simple LDAP operations--this obviously isn't a complete Python LDAP server implementation--but those simple operations tend to cover a lot of cases. .. _example: Example ------- :: import unittest import ldap from mockldap import MockLdap class MyTestCase(unittest.TestCase): """ A simple test case showing off some of the basic features of mockldap. """ top = ('o=test', {'o': 'test'}) example = ('ou=example,o=test', {'ou': 'example'}) other = ('ou=other,o=test', {'ou': 'other'}) manager = ('cn=manager,ou=example,o=test', {'cn': 'manager', 'userPassword': ['ldaptest']}) alice = ('cn=alice,ou=example,o=test', {'cn': 'alice', 'userPassword': ['alicepw']}) bob = ('cn=bob,ou=other,o=test', {'cn': 'bob', 'userPassword': ['bobpw']}) # This is the content of our mock LDAP directory. It takes the form # {dn: {attr: [value, ...], ...}, ...}. directory = dict([top, example, other, manager, alice, bob]) @classmethod def setUpClass(cls): # We only need to create the MockLdap instance once. The content we # pass in will be used for all LDAP connections. cls.mockldap = MockLdap(cls.directory) @classmethod def tearDownClass(cls): del cls.mockldap def setUp(self): # Patch ldap.initialize self.mockldap.start() self.ldapobj = self.mockldap['ldap://localhost/'] def tearDown(self): # Stop patching ldap.initialize and reset state. self.mockldap.stop() del self.ldapobj def test_some_ldap(self): """ Some LDAP operations, including binds and simple searches, can be mimicked. """ results = _do_simple_ldap_search() self.assertEquals(self.ldapobj.methods_called(), ['initialize', 'simple_bind_s', 'search_s']) self.assertEquals(sorted(results), sorted([self.manager, self.alice])) def test_complex_search(self): """ Some LDAP operations, such as complex searches, are not implemented. If you're doing anything nontrivial, you have to set an explicit return value for a set of parameters. """ self.ldapobj.search_s.seed('o=test', ldap.SCOPE_SUBTREE, '(|(cn=b*b)(cn=a*e))')([self.alice, self.bob]) results = _do_complex_ldap_search() self.assertEquals(self.ldapobj.methods_called(), ['initialize', 'simple_bind_s', 'search_s']) self.assertEquals(sorted(results), sorted([self.alice, self.bob])) def _do_simple_ldap_search(): conn = ldap.initialize('ldap://localhost/') conn.simple_bind_s('cn=alice,ou=example,o=test', 'alicepw') results = conn.search_s('ou=example,o=test', ldap.SCOPE_ONELEVEL, '(cn=*)') return results def _do_complex_ldap_search(): conn = ldap.initialize('ldap://localhost/') conn.simple_bind_s('cn=alice,ou=example,o=test', 'alicepw') results = conn.search_s('o=test', ldap.SCOPE_SUBTREE, '(|(cn=b*b)(cn=a*e))') return results mockldap-0.2.5/LICENSE0000644000076600000240000000242112163121573015105 0ustar psagersstaff00000000000000Copyright (c) 2013, Peter Sagerson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mockldap-0.2.5/MANIFEST.in0000644000076600000240000000015012213120446015625 0ustar psagersstaff00000000000000include README LICENSE CHANGES include docs/Makefile include docs/source/*.py include docs/source/*.rst mockldap-0.2.5/PKG-INFO0000644000076600000240000000236612540073641015206 0ustar psagersstaff00000000000000Metadata-Version: 1.1 Name: mockldap Version: 0.2.5 Summary: A simple mock implementation of python-ldap. Home-page: http://bitbucket.org/psagers/mockldap/ Author: Peter Sagerson Author-email: psagers.pypi@ignorare.net License: BSD Description: This project provides a mock replacement for python-ldap. It's useful for any project that would like to write unit tests against LDAP code without relying on a running LDAP server. Keywords: mock,ldap Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: BSD License Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP Classifier: Topic :: Software Development :: Libraries :: Python Modules mockldap-0.2.5/README0000644000076600000240000000026612163120454014762 0ustar psagersstaff00000000000000This project provides a mock replacement for python-ldap. It's useful for any project that would like to write unit tests against LDAP code without relying on a running LDAP server. mockldap-0.2.5/setup.cfg0000644000076600000240000000007312540073641015723 0ustar psagersstaff00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 mockldap-0.2.5/setup.py0000755000076600000240000000332112540073262015615 0ustar psagersstaff00000000000000#!/usr/bin/env python from setuptools import setup try: import unittest.mock # noqa except ImportError: requires_mock = ['mock'] else: requires_mock = [] try: import unittest2 # noqa except ImportError: test_loader = 'unittest:TestLoader' else: test_loader = 'unittest2:TestLoader' setup( name='mockldap', version='0.2.5', description=u"A simple mock implementation of python-ldap.", long_description=open('README').read(), url='http://bitbucket.org/psagers/mockldap/', author='Peter Sagerson', author_email='psagers.pypi@ignorare.net', license='BSD', packages=['mockldap'], package_dir={'': 'src'}, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: BSD License', 'Topic :: Internet :: WWW/HTTP', 'Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords=['mock', 'ldap'], install_requires=[ 'python-ldap', 'funcparserlib==0.3.6', ] + requires_mock, extras_require={ }, setup_requires=[ 'setuptools>=0.6c11', ], test_loader=test_loader, test_suite='mockldap.tests', ) mockldap-0.2.5/src/0000755000076600000240000000000012540073641014671 5ustar psagersstaff00000000000000mockldap-0.2.5/src/mockldap/0000755000076600000240000000000012540073641016463 5ustar psagersstaff00000000000000mockldap-0.2.5/src/mockldap/__init__.py0000644000076600000240000001054312321412073020570 0ustar psagersstaff00000000000000from collections import defaultdict from ldap.cidict import cidict from .ldapobject import LDAPObject from .recording import SeedRequired # noqa URI_DEFAULT = '__default__' class MockLdap(object): """ Top-level class managing directories and patches. :param directory: Default directory contents. After calling :meth:`~mockldap.MockLdap.start`, ``mockldap[uri]`` returns an :class:`~mockldap.LDAPObject`. This is the same object that will be returned by ``ldap.initialize(uri)``, so you can use it to seed return values and discover which APIs were called. """ def __init__(self, directory=None): self.directories = {} self.ldap_objects = None self.patchers = {} if directory is not None: self.set_directory(directory) def __getitem__(self, uri): if self.ldap_objects is None: raise KeyError( "You must call start() before asking for mock LDAP objects.") return self.ldap_objects[uri] def set_directory(self, directory, uri=URI_DEFAULT): """ Set the mock LDAP content for a given URI. :param uri: The LDAP URI to associate this content with. :type uri: string If URI is not given, this will set the default content for all unknown URIs. """ if self.ldap_objects is not None: raise Exception("You can't add a directory after calling start().") self.directories[uri] = cidict(map_keys(lambda s: s.lower(), directory)) def start(self, path='ldap.initialize'): """ Patch :func:`ldap.initialize` to return mock LDAPObject instances. This calls :func:`mock.patch`, so you must have the `mock `_ library installed. :param path: The module path to ``ldap.initialize``. :type path: string If the code under test looks like:: import ldap ... ldap.initialize(uri) then you can use the default value of path. If the code reads:: from ldap import initialize ... initialize(uri) then you need to call ``start('path.to.your.mod.initialize')``. See :ref:`where-to-patch` for more. """ try: from unittest.mock import patch except ImportError: from mock import patch if path in self.patchers: raise ValueError("%r is already patched." % (path,)) if self.ldap_objects is None: ldap_objects = map_values(LDAPObject, self.directories) self.ldap_objects = defaultdict(self._new_ldap_object, ldap_objects) patcher = patch(path, new_callable=lambda: self.initialize) patcher.start() self.patchers[path] = patcher def _new_ldap_object(self): from .ldapobject import LDAPObject try: return LDAPObject(self.directories[URI_DEFAULT]) except KeyError: raise KeyError("No default mock LDAP content provided") def stop(self, path='ldap.initialize'): """ Stop patching :func:`ldap.initialize`. Calls to :meth:`~mockldap.MockLdap.start` and :meth:`~mockldap.MockLdap.stop` must be balanced. After the final call to stop, we'll reset all :class:`~mockldap.LDAPObject` instances. """ if path not in self.patchers: raise ValueError("%r is not patched." % (path,)) self.patchers[path].stop() del self.patchers[path] if len(self.patchers) == 0: self.ldap_objects = None def stop_all(self): """ Remove all patches and reset our state. If you called :meth:`~mockldap.MockLdap.start` multiple times, this is the easiest way to reset everything. """ for patcher in self.patchers.values(): patcher.stop() self.patchers.clear() self.ldap_objects = None def initialize(self, uri, *args, **kwargs): ldap_object = self[uri] # For recording purposes only. ldap_object.initialize(uri, *args, **kwargs) return ldap_object # Map a dictionary by applying a function to each key/value. map_keys = lambda f, d: dict((f(k), v) for k, v in d.items()) map_values = lambda f, d: dict((k, f(v)) for k, v in d.items()) mockldap-0.2.5/src/mockldap/filter.py0000644000076600000240000001263112316344051020322 0ustar psagersstaff00000000000000""" Simple filter expression parser based on funcparserlib. """ from functools import partial import ldap import re from funcparserlib.parser import (a, skip, oneplus, finished, with_forward_decls, NoParseError) class UnsupportedOp(Exception): pass class Token(object): LPAREN = 1 RPAREN = 2 AND = 10 OR = 11 NOT = 12 TEST = 100 def __init__(self, code, content='', start=-1, stop=-1): self.code = code self.content = content self.start = start self.stop = stop def __eq__(self, other): return self.code == other.code def __str__(self): return "%d-%d: %s %r" % (self.start, self.stop, self.code, self.content) def __repr__(self): return "%s(%r, %r, %r, %r)" % (self.__class__.__name__, self.code, self.content, self.start, self.stop) def matches(self, dn, attrs): raise NotImplementedError() LParen = partial(Token, Token.LPAREN) RParen = partial(Token, Token.RPAREN) class And(Token): def __init__(self, *args, **kwargs): super(And, self).__init__(self.AND, *args, **kwargs) self.terms = [] def unparse(self): return u"(&%s)" % (u"".join(t.unparse() for t in self.terms),) def matches(self, dn, attrs): return all(term.matches(dn, attrs) for term in self.terms) class Or(Token): def __init__(self, *args, **kwargs): super(Or, self).__init__(self.OR, *args, **kwargs) self.terms = [] def unparse(self): return u"(|%s)" % (u"".join(t.unparse() for t in self.terms),) def matches(self, dn, attrs): return any(term.matches(dn, attrs) for term in self.terms) class Not(Token): def __init__(self, *args, **kwargs): super(Not, self).__init__(self.NOT, *args, **kwargs) self.term = None def unparse(self): return u"(!%s)" % (self.term.unparse(),) # For external consistency def _get_terms(self): return self.term def _set_terms(self, terms): self.term = terms terms = property(_get_terms, _set_terms) def matches(self, dn, attrs): return (not self.term.matches(dn, attrs)) class Test(Token): TEST_RE = re.compile(r'(.+?)([~<>]?=)(.+)') UNESCAPE_RE = re.compile(r'\\([0-9a-f]{2})', flags=re.I) # Defaults attr = None op = None value = None def __init__(self, *args, **kwargs): super(Test, self).__init__(self.TEST, *args, **kwargs) if self.content: self._parse_expression() def _parse_expression(self): match = self.TEST_RE.match(self.content) if match is None: raise ldap.FILTER_ERROR(u"Failed to parse filter item '%s' at pos %d" % (self.content, self.start)) self.attr, self.op, self.value = match.groups() if self.op != '=': raise UnsupportedOp(u"Operation '%s' is not supported" % (self.op,)) if (u'*' in self.value) and (self.value != u'*'): raise UnsupportedOp(u"Wildcard matches are not supported in '%s'" % (self.value,)) # Resolve all escaped characters self.value = self.UNESCAPE_RE.sub(lambda m: chr(int(m.group(1), 16)), self.value) def unparse(self): return u"(%s)" % (self.content,) def matches(self, dn, attrs): values = attrs.get(self.attr) if values is None: matches = False elif self.value == u'*': matches = len(values) > 0 else: matches = self.value in values return matches # Tokens to pull out. The operators contain positive lookbehind assertions to # make sure that they're only matched after left parens. _atoms = [ r'\(', # ( r'(?<=\()\&', # & r'(?<=\()\|', # | r'(?<=\()\!', # ! r'\)', # ) ] tokens_re = re.compile(r'(%s)' % r'|'.join(_atoms)) def tokenize(filterstr): substrs = tokens_re.split(filterstr) return list(gen_tokens(substrs)) def gen_tokens(substrs): pos = 0 for substr in substrs: if substr == '': continue elif substr == '(': token = LParen elif substr == '&': token = And elif substr == '|': token = Or elif substr == '!': token = Not elif substr == ')': token = RParen else: token = Test yield token(substr, pos, pos + len(substr) - 1) pos += len(substr) def parse(filterstr): try: return ldap_filter.parse(tokenize(filterstr)) except NoParseError as e: raise ldap.FILTER_ERROR(e) # # Grammar # def grammar(): lparen = skip(a(LParen())) rparen = skip(a(RParen())) def collapse(t): t[0].terms = t[1] return t[0] @with_forward_decls def ldap_filter(): return (ldap_and | ldap_or | ldap_not | ldap_test) ldap_and = (lparen + a(And()) + oneplus(ldap_filter) + rparen) >> collapse ldap_or = (lparen + a(Or()) + oneplus(ldap_filter) + rparen) >> collapse ldap_not = (lparen + a(Not()) + ldap_filter + rparen) >> collapse ldap_test = lparen + a(Test()) + rparen return ldap_filter + skip(finished) ldap_filter = grammar() # # Call this module with filter strings to test the parsing. # if __name__ == '__main__': from pprint import pprint import sys for filterstr in sys.argv[1:]: pprint(tokenize(filterstr)) print(parse(filterstr).unparse()) mockldap-0.2.5/src/mockldap/ldapobject.py0000644000076600000240000002703312540073103021142 0ustar psagersstaff00000000000000from __future__ import absolute_import import base64 from copy import deepcopy try: from crypt import crypt except ImportError: crypt = None import hashlib import re import ldap from ldap.cidict import cidict import ldap.dn from .recording import SeedRequired, RecordableMethods, recorded class LDAPObject(RecordableMethods): """ :param directory: The initial content of this LDAP connection. :type directory: :class:`ldap.cidict.cidict`: ``{dn: {attr: [values]}}`` Our mock replacement for :class:`ldap.LDAPObject`. This exports selected LDAP operations and allows you to set return values in advance as well as discover which methods were called after the fact. All of these methods take the same arguments as their python-ldap counterparts. Some are self-explanatory; those that are only partially implemented are documented as such. Ignore the *static* annotations; that's just a Sphinx artifact. .. attribute:: options *dict*: Options that have been set by :meth:`~mockldap.LDAPObject.set_option`. .. attribute:: tls_enabled *bool*: True if :meth:`~mockldap.LDAPObject.start_tls_s` was called. .. attribute:: bound_as *string*: DN of the last successful bind. None if unbound. """ def __init__(self, directory): if not isinstance(directory, ldap.cidict.cidict): from . import map_keys directory = cidict(map_keys(lambda s: s.lower(), directory)) self.directory = deepcopy(directory) self.async_results = [] self.options = {} self.tls_enabled = False self.bound_as = None def _check_valid_dn(self, dn): try: ldap.dn.str2dn(dn) except ldap.DECODING_ERROR: raise ldap.INVALID_DN_SYNTAX # # Begin LDAP methods # @recorded def initialize(self, *args, **kwargs): """ This only exists for recording purposes. """ pass @recorded def get_option(self, option): """ """ return self.options[option] @recorded def set_option(self, option, invalue): """ """ self.options[option] = invalue @recorded def simple_bind_s(self, who='', cred=''): """ """ success = False try: if(who == '' and cred == ''): success = True elif self._compare_s(who, 'userPassword', cred): success = True except ldap.NO_SUCH_OBJECT: pass if success: self.bound_as = who return (97, []) else: raise ldap.INVALID_CREDENTIALS('%s:%s' % (who, cred)) @recorded def search(self, base, scope, filterstr='(objectClass=*)', attrlist=None, attrsonly=0): """ See :meth:`~mockldap.LDAPObject.search_s`. """ value = self._search_s(base, scope, filterstr, attrlist, attrsonly) return self._add_async_result(value) @recorded def result(self, msgid, all=1, timeout=None): """ """ return ldap.RES_SEARCH_RESULT, self._pop_async_result(msgid) @recorded def search_s(self, base, scope, filterstr='(objectClass=*)', attrlist=None, attrsonly=0): """ Supports many, but not all, filter strings. Tests of the form ``'(foo=bar)'`` and ``'(foo=\*)'`` are supported, as are the &, \|, and ! operators. attrlist and attrsonly are also supported. Beyond that, this method must be seeded. """ return self._search_s(base, scope, filterstr, attrlist, attrsonly) @recorded def start_tls_s(self): """ """ self.tls_enabled = True @recorded def compare_s(self, dn, attr, value): """ """ return self._compare_s(dn, attr, value) @recorded def modify_s(self, dn, mod_attrs): """ """ return self._modify_s(dn, mod_attrs) @recorded def add_s(self, dn, record): """ """ return self._add_s(dn, record) @recorded def rename_s(self, dn, newrdn, newsuperior=None): """ """ return self._rename_s(dn, newrdn, newsuperior) @recorded def delete_s(self, dn): """ """ return self._delete_s(dn) @recorded def unbind(self): """ """ self.bound_as = None @recorded def unbind_s(self): """ """ self.bound_as = None @recorded def whoami_s(self): """ """ return "dn:" + self.bound_as @recorded def passwd_s(self, user, oldpw, newpw, serverctrls=None, clientctrls=None): """ """ return self._passwd_s(user, oldpw, newpw, serverctrls, clientctrls) # # Internal implementations # def _compare_s(self, dn, attr, value): self._check_valid_dn(dn) try: values = self.directory[dn].get(attr, []) except KeyError: raise ldap.NO_SUCH_OBJECT if attr == 'userPassword': result = 1 if any(self._compare_password(value, candidate) for candidate in values) else 0 else: result = (1 if (value in values) else 0) return result PASSWORD_RE = re.compile(r'^{(.*?)}(.*)') def _compare_password(self, password, value): """ Compare a password to a (possibly hashed) attribute value. This returns True iff ``password`` matches the given attribute value. A limited set of LDAP password hashing schemes is supported; feel free to add more if you need them. """ match = self.PASSWORD_RE.match(value) if match is not None: scheme, raw = match.groups() if crypt is not None and scheme == 'CRYPT': matches = (crypt(password, raw[:4]) == raw) elif scheme == 'SSHA': decoded = base64.b64decode(raw) h = hashlib.sha1(password.encode('utf-8')) h.update(decoded[h.digest_size:]) matches = (h.digest() == decoded[:h.digest_size]) else: matches = False else: matches = (value == password) return matches def _search_s(self, base, scope, filterstr, attrlist, attrsonly): from .filter import parse, UnsupportedOp self._check_valid_dn(base) if base not in self.directory: raise ldap.NO_SUCH_OBJECT # Find directory entries within the requested scope base_parts = ldap.dn.explode_dn(base.lower()) base_len = len(base_parts) dn_parts = dict((dn, ldap.dn.explode_dn(dn.lower())) for dn in self.directory.keys()) if scope == ldap.SCOPE_BASE: dns = (dn for dn, parts in dn_parts.items() if parts == base_parts) elif scope == ldap.SCOPE_ONELEVEL: dns = (dn for dn, parts in dn_parts.items() if parts[1:] == base_parts) elif scope == ldap.SCOPE_SUBTREE: dns = (dn for dn, parts in dn_parts.items() if parts[-base_len:] == base_parts) else: raise ValueError(u"Unrecognized scope: {0}".format(scope)) # Apply the filter expression try: filter_expr = parse(filterstr) except UnsupportedOp as e: raise SeedRequired(e) results = ((dn, self.directory[dn]) for dn in dns if filter_expr.matches(dn, self.directory[dn])) # Apply attribute filtering, if any if attrlist is not None: results = ((dn, dict((attr, values) for attr, values in attrs.items() if attr in attrlist)) for dn, attrs in results) if attrsonly: results = ((dn, dict((attr, []) for attr in attrs.keys())) for dn, attrs in results) return list(results) def _modify_s(self, dn, mod_attrs): self._check_valid_dn(dn) for item in mod_attrs: op, key, value = item try: entry = self.directory[dn] except KeyError: raise ldap.NO_SUCH_OBJECT if value is None: value = [] elif type(value) is str: value = [value] if op == ldap.MOD_ADD: if value == []: raise ldap.PROTOCOL_ERROR if key not in entry: entry[key] = value else: for subvalue in value: if subvalue not in entry[key]: entry[key].append(subvalue) elif op == ldap.MOD_DELETE: if key not in entry: pass elif value == []: del entry[key] else: entry[key] = [v for v in entry[key] if v not in value] if entry[key] == []: del entry[key] elif op == ldap.MOD_REPLACE: if value == []: if key in entry: del entry[key] else: entry[key] = value return (103, []) def _add_s(self, dn, record): self._check_valid_dn(dn) entry = {} dn = str(dn) for item in record: entry[item[0]] = list(item[1]) try: self.directory[dn] raise ldap.ALREADY_EXISTS except KeyError: self.directory[dn.lower()] = entry return (105, [], len(self.methods_called()), []) def _rename_s(self, dn, newrdn, newsuperior): self._check_valid_dn(dn) self._check_valid_dn(newrdn) if newsuperior: self._check_valid_dn(newsuperior) try: entry = self.directory[dn] except KeyError: raise ldap.NO_SUCH_OBJECT if newsuperior: superior = newsuperior else: superior = ','.join(dn.split(',')[1:]) newfulldn = '%s,%s' % (newrdn, superior) if newfulldn in self.directory: raise ldap.ALREADY_EXISTS oldattr, oldvalue = dn.split(',')[0].split('=') newattr, newvalue = newrdn.split('=') try: if newvalue not in entry[newattr]: entry[newattr].append(newvalue) except KeyError: entry[newattr] = [newvalue] if oldattr == newattr or len(entry[oldattr]) > 1: entry[oldattr].remove(oldvalue) else: del entry[oldattr] self.directory[newfulldn] = entry del self.directory[dn] return (109, []) def _delete_s(self, dn): self._check_valid_dn(dn) try: del self.directory[dn] except KeyError: raise ldap.NO_SUCH_OBJECT return (107, []) def _passwd_s(self, user, oldpw, newpw, serverctrls=None, clientctrls=None): self._check_valid_dn(user) entry = self.directory.get(user) if entry is None: raise ldap.NO_SUCH_OBJECT if oldpw is not None: if entry['userPassword'][0] == oldpw: entry['userPassword'] = [newpw] else: entry['userPassword'] = [newpw] # # Async # def _add_async_result(self, value): self.async_results.append(value) return len(self.async_results) - 1 def _pop_async_result(self, msgid): if msgid in range(len(self.async_results)): value = self.async_results[msgid] self.async_results[msgid] = None else: value = None return value mockldap-0.2.5/src/mockldap/recording.py0000644000076600000240000001272212316344051021012 0ustar psagersstaff00000000000000""" Tools for recording method calls and seeding return values. """ from collections import defaultdict from copy import deepcopy from functools import partial class SeedRequired(Exception): """ An API call must be seeded with a return value. This is raised by :class:`~mockldap.LDAPObject` methods when they can't satisfy a request internally. The messsage will contain a representation of the method call that triggered it, including all arguments. """ pass class RecordableMethods(object): """ This is a mixin class to be used as a companion with recorded, below. Any class that wants to use the recordable decorator must inherit from this. """ def methods_called(self, with_args=False): if with_args: calls = deepcopy(self._recorded_calls) else: calls = [call[0] for call in self._recorded_calls] return calls @property def _recorded_calls(self): if not hasattr(self, '_recorded_calls_internal'): self._recorded_calls_internal = [] return self._recorded_calls_internal @property def _seeded_calls(self): if not hasattr(self, '_seeded_calls_internal'): self._seeded_calls_internal = defaultdict(list) return self._seeded_calls_internal class recorded(object): """ >>> class C(RecordableMethods): ... @recorded ... def plus1(self, n): ... return n + 1 >>> >>> c = C() >>> c.plus1(5) 6 >>> c.plus1.seed(5)(7) >>> c.plus1(5) 7 >>> c.plus1(4) 5 >>> c.methods_called() ['plus1', 'plus1', 'plus1'] >>> c.methods_called(with_args=True) [('plus1', (5,), {}), ('plus1', (5,), {}), ('plus1', (4,), {})] >>> c = C() >>> c.plus1.seed(n=5)(8) >>> c.plus1(5) 6 >>> c.plus1(n=5) 8 >>> c.methods_called(with_args=True) [('plus1', (5,), {}), ('plus1', (), {'n': 5})] >>> c = C() >>> c.plus1.seed(5)(9) >>> c.plus1.seed(5)(10) >>> c.plus1(5) 10 >>> c.plus1.seed(5)(ValueError()) >>> c.plus1(5) Traceback (most recent call last): ... ValueError >>> c.plus1.seed(5)(ValueError) >>> c.plus1(5) Traceback (most recent call last): ... ValueError """ def __init__(self, func): self.func = func def __get__(self, instance, owner): func = self.func if instance is not None: func = RecordedMethod(self.func, instance) return func class RecordedMethod(object): def __init__(self, func, instance): self.func = func self.instance = instance def __call__(self, *args, **kwargs): self._record(args, kwargs) try: value = next(iter(self._seeded_values(args, kwargs)))[1] except StopIteration: try: value = self.func(self.instance, *args, **kwargs) except SeedRequired as e: raise SeedRequired("Seed required for %s: %s" % (self._call_repr(*args, **kwargs), e)) else: if self._is_exception(value): raise value return deepcopy(value) def seed(self, *args, **kwargs): """ A convenience wrapper for :meth:`~mockldap.recording.RecordedMethod.set_return_value`. ``method.seed(arg1, arg2=True)(value)`` is equivalent to ``method.set_return_value([arg1], {'arg2': True}, value)``. """ return partial(self.set_return_value, args, kwargs) def set_return_value(self, args, kwargs, value): """ Set a method's return value for a set of arguments. Subsequent calls to this method will check for a matching set of arguments and return the assoiated value. If the value is an exception class or instance, it will be raised instead. .. warning:: When the method is called, the arguments must be passed in exactly the same form. We don't automatically match equivalent positional and keyword arguments. If no preset return value is found, the underlying method will be called normally. If that method can not handle the request, it may raise :exc:`mockldap.SeedRequired`, indicating that the method must be seeded with a return value for these arguments. """ args = deepcopy(args) kwargs = deepcopy(kwargs) value = deepcopy(value) self._seeded_calls.insert(0, ((args, kwargs), value)) def _record(self, args, kwargs): self._recorded_calls.append((self.func.__name__, args, kwargs)) def _seeded_values(self, args, kwargs): func = partial(self._seed_matches, args, kwargs) return filter(func, self._seeded_calls) def _seed_matches(self, args, kwargs, seed): return (seed[0] == (args, kwargs)) @property def _seeded_calls(self): return self.instance._seeded_calls[self.func.__name__] @property def _recorded_calls(self): return self.instance._recorded_calls def _call_repr(self, *args, **kwargs): arglist = [repr(arg) for arg in args] arglist.extend('%s=%r' % item for item in kwargs.items()) return "%s(%s)" % (self.func.__name__, ", ".join(arglist)) def _is_exception(self, value): if isinstance(value, Exception): return True if (isinstance(value, type) and issubclass(value, Exception)): return True return False mockldap-0.2.5/src/mockldap/tests.py0000644000076600000240000006074412540073540020210 0ustar psagersstaff00000000000000from __future__ import absolute_import, with_statement from copy import copy from doctest import DocTestSuite try: import unittest2 as unittest except ImportError: import unittest import ldap import ldap.modlist import ldap.filter from . import MockLdap from .recording import SeedRequired test = ("o=test", {"objectClass": ["top"]}) example = ("ou=example,o=test", {"objectClass": ["top"]}) other = ("ou=other,o=test", {"objectClass": ["top"]}) manager = ("cn=manager,ou=example,o=test", { "userPassword": ["ldaptest"], "objectClass": ["top", "posixAccount", "inetOrgPerson"]}) alice = ("cn=alice,ou=example,o=test", { "cn": ["alice"], "uid": ["alice"], "userPassword": ["alicepw"], "objectClass": ["top", "posixAccount"]}) # Passwords generated with slappasswd theo = ("cn=theo,ou=example,o=test", {"userPassword": [ "{CRYPT}Q7BT9BT8qXW/k", "{SSHA}ecL6T4anvrFI2ixn2XnrE0roM5TeoLLE", "{SSHA}/WoozYVlR2BXTCDCWpZG8+IqnF1GWhJbbCSVXQ=="], "objectClass": ["top", "posixAccount"]}) john = ("cn=john,ou=example,o=test", {"objectClass": ["top"]}) bob = ("cn=bob,ou=other,o=test", { "userPassword": ["bobpw", "bobpw2"], "objectClass": ["top"]}) directory = dict([test, example, other, manager, alice, theo, john, bob]) def load_tests(loader, tests, pattern): suite = unittest.TestSuite() suite.addTests(tests) suite.addTest(DocTestSuite('mockldap.recording')) return suite class TestLDAPObject(unittest.TestCase): @classmethod def setUpClass(cls): cls.mockldap = MockLdap(directory) @classmethod def tearDownClass(cls): del cls.mockldap def setUp(self): self.mockldap.start() self.ldapobj = self.mockldap['ldap://localhost'] def tearDown(self): self.mockldap.stop() def test_manual_ldapobject(self): from .ldapobject import LDAPObject ldapobj = LDAPObject(directory) self.assertIsInstance(ldapobj.directory, ldap.cidict.cidict) def test_set_option(self): self.ldapobj.set_option(ldap.OPT_X_TLS_DEMAND, True) self.assertEqual(self.ldapobj.get_option(ldap.OPT_X_TLS_DEMAND), True) def test_simple_bind_s_success(self): result = self.ldapobj.simple_bind_s("cn=alice,ou=example,o=test", "alicepw") self.assertEqual(result, (97, [])) def test_simple_bind_s_success_case_insensitive(self): result = self.ldapobj.simple_bind_s("cn=manager,ou=Example,o=test", "ldaptest") self.assertEqual(result, (97, [])) def test_simple_bind_s_anon_user(self): result = self.ldapobj.simple_bind_s() self.assertEqual(result, (97, [])) def test_simple_bind_s_fail_login_with_invalid_username(self): with self.assertRaises(ldap.INVALID_CREDENTIALS): self.ldapobj.simple_bind_s("cn=blah,o=test", "password") def test_simple_bind_s_fail_login(self): with self.assertRaises(ldap.INVALID_CREDENTIALS): self.ldapobj.simple_bind_s("cn=alice,ou=example,o=test", "wrong") def test_simple_bind_s_secondary_password(self): result = self.ldapobj.simple_bind_s("cn=bob,ou=other,o=test", "bobpw2") self.assertEqual(result, (97, [])) def test_simple_bind_s_success_crypt_password(self): result = self.ldapobj.simple_bind_s("cn=theo,ou=example,o=test", "theopw") self.assertEqual(result, (97, [])) def test_simple_bind_s_success_crypt_secondary_password(self): result = self.ldapobj.simple_bind_s("cn=theo,ou=example,o=test", "theopw2") self.assertEqual(result, (97, [])) def test_simple_bind_s_success_crypt_tertiary_password(self): result = self.ldapobj.simple_bind_s("cn=theo,ou=example,o=test", "12345") self.assertEqual(result, (97, [])) def test_simple_bind_s_fail_crypt_password(self): with self.assertRaises(ldap.INVALID_CREDENTIALS): self.ldapobj.simple_bind_s("cn=theo,ou=example,o=test", "theopw3") def test_simple_bind_s_invalid_dn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.simple_bind_s('invalid', 'invalid') def test_search_s_get_directory_items_with_scope_onelevel(self): results = self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL) self.assertEqual(sorted(results), sorted([manager, alice, theo, john])) def test_search_s_get_all_directory_items_with_scope_subtree(self): results = self.ldapobj.search_s("o=test", ldap.SCOPE_SUBTREE) self.assertEqual(sorted(results), sorted(directory.items())) def test_search_s_get_specific_item_with_scope_base(self): results = self.ldapobj.search_s("cn=alice,ou=example,o=test", ldap.SCOPE_BASE) self.assertEqual(results, [alice]) def test_search_s_base_case_insensitive(self): results = self.ldapobj.search_s('cn=ALICE,ou=Example,o=TEST', ldap.SCOPE_BASE) self.assertEquals(results, [alice]) def test_search_s_get_specific_attr(self): results = self.ldapobj.search_s("cn=alice,ou=example,o=test", ldap.SCOPE_BASE, attrlist=["userPassword"]) self.assertEqual(results, [(alice[0], {'userPassword': alice[1]['userPassword']})]) def test_search_s_use_attrsonly(self): results = self.ldapobj.search_s("cn=alice,ou=example,o=test", ldap.SCOPE_BASE, attrlist=["userPassword"], attrsonly=1) self.assertEqual(results, [(alice[0], {'userPassword': []})]) def test_search_s_specific_attr_in_filterstr(self): results = self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(userPassword=alicepw)') self.assertEqual(results, [alice]) def test_search_s_escaped(self): escaped = ldap.filter.escape_filter_chars('alicepw', 2) results = self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(userPassword=%s)' % (escaped,)) self.assertEqual(results, [alice]) def test_search_s_unparsable_filterstr(self): with self.assertRaises(ldap.FILTER_ERROR): self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, 'invalid=*') def test_search_s_unparsable_filterstr_test(self): with self.assertRaises(ldap.FILTER_ERROR): self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(invalid=)') def test_search_s_filterstr_wildcard(self): with self.assertRaises(SeedRequired): self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(invalid=foo*bar)') def test_search_s_invalid_filterstr(self): results = self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(invalid=*)') self.assertEqual(results, []) def test_search_s_invalid_filterstr_op(self): with self.assertRaises(SeedRequired): self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(invalid~=bogus)') def test_search_async(self): msgid = self.ldapobj.search("cn=alice,ou=example,o=test", ldap.SCOPE_BASE) results = self.ldapobj.result(msgid) self.assertEqual(results, (ldap.RES_SEARCH_RESULT, [alice])) def test_useful_seed_required_message(self): filterstr = '(invalid~=bogus)' try: self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, filterstr, attrlist=['ou']) except SeedRequired as e: self.assertIn("search_s('ou=example,o=test', 1, '(invalid~=bogus)', attrlist=['ou']", str(e)) else: self.fail("Expected SeedRequired exception") def test_search_s_mixed_case_dn(self): dn = "cn=Edward,ou=example,o=test" attrs = { "objectClass": ["top"], "cn": ["Edward"], } ldif = ldap.modlist.addModlist(attrs) self.ldapobj.add_s(dn, ldif) results = self.ldapobj.search_s(dn.lower(), ldap.SCOPE_BASE) self.assertEqual(results, [(dn.lower(), attrs)]) def test_search_s_get_items_that_have_userpassword_set(self): results = self.ldapobj.search_s( "ou=example,o=test", ldap.SCOPE_ONELEVEL, '(userPassword=*)') self.assertEqual(sorted(results), sorted([alice, manager, theo])) def test_search_s_filterstr_with_not(self): results = self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_SUBTREE, "(!(userPassword=alicepw))") self.assertEqual(sorted(results), sorted([example, manager, theo, john])) def test_search_s_mutliple_filterstr_items_with_and(self): results = self.ldapobj.search_s( "ou=example,o=test", ldap.SCOPE_SUBTREE, "(&(objectClass=top)(objectClass=posixAccount)(userPassword=*))" ) self.assertEqual(sorted(results), sorted([alice, manager, theo])) def test_search_s_mutliple_filterstr_items_one_invalid_with_and(self): results = self.ldapobj.search_s( "ou=example,o=test", ldap.SCOPE_SUBTREE, "(&(objectClass=top)(invalid=yo)(objectClass=posixAccount))" ) self.assertEqual(results, []) def test_search_s_multiple_filterstr_items_with_or(self): results = self.ldapobj.search_s( "ou=example,o=test", ldap.SCOPE_SUBTREE, "(|(objectClass=inetOrgPerson)(userPassword=alicepw))" ) self.assertEqual(sorted(results), sorted([alice, manager])) def test_search_s_multiple_filterstr_items_one_invalid_with_or(self): results = self.ldapobj.search_s( "ou=example,o=test", ldap.SCOPE_SUBTREE, "(|(objectClass=inetOrgPerson)(invalid=yo)(userPassword=alicepw))" ) self.assertEqual(sorted(results), sorted([alice, manager])) def test_search_s_filterstr_with_token_chars(self): """ Make sure we can parse special chars in a filter string. """ self.ldapobj.search_s( "ou=example,o=test", ldap.SCOPE_SUBTREE, "(objectClass=a & b | c ! d)" ) def test_search_s_scope_base_no_such_object(self): with self.assertRaises(ldap.NO_SUCH_OBJECT): self.ldapobj.search_s("cn=blah,ou=example,o=test", ldap.SCOPE_BASE) def test_search_s_no_results(self): results = self.ldapobj.search_s("ou=example,o=test", ldap.SCOPE_ONELEVEL, '(uid=blah)') self.assertEqual(results, []) def test_search_s_invalid_dn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.search_s("invalid", ldap.SCOPE_SUBTREE) def test_start_tls_s_disabled_by_default(self): self.assertEqual(self.ldapobj.tls_enabled, False) def test_start_tls_s_enabled(self): self.ldapobj.start_tls_s() self.assertEqual(self.ldapobj.tls_enabled, True) def test_compare_s_no_such_object(self): with self.assertRaises(ldap.NO_SUCH_OBJECT): self.ldapobj.compare_s('cn=blah,ou=example,o=test', 'objectClass', 'top') def test_compare_s_true(self): result = self.ldapobj.compare_s('cn=Manager,ou=example,o=test', 'objectClass', 'top') self.assertEqual(result, 1) def test_compare_s_false(self): result = self.ldapobj.compare_s('cn=Manager,ou=example,o=test', 'objectClass', 'invalid') self.assertEqual(result, 0) def test_compare_s_invalid_dn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.compare_s('invalid', 'invalid', 'invalid') def test_add_s_success_code(self): dn = 'cn=mike,ou=example,o=test' attrs = { 'objectClass': ['top', 'organizationalRole'], 'cn': ['mike'], 'userPassword': ['mikepw'], } ldif = ldap.modlist.addModlist(attrs) result = self.ldapobj.add_s(dn, ldif) self.assertEqual(result, (105, [], 1, [])) def test_add_s_successfully_add_object(self): dn = 'cn=mike,ou=example,o=test' attrs = { 'objectClass': ['top', 'organizationalRole'], 'cn': ['mike'], 'userPassword': ['mikepw'], } ldif = ldap.modlist.addModlist(attrs) self.ldapobj.add_s(dn, ldif) self.assertEqual(self.ldapobj.directory[dn], attrs) def test_add_s_already_exists(self): attrs = {'cn': ['mike']} ldif = ldap.modlist.addModlist(attrs) with self.assertRaises(ldap.ALREADY_EXISTS): self.ldapobj.add_s(alice[0], ldif) self.assertNotEqual(self.ldapobj.directory[alice[0]], attrs) def test_add_s_invalid_dn(self): dn = 'invalid' attrs = { 'objectClass': ['top', 'organizationalRole'], 'cn': ['mike'], 'userPassword': ['mikepw'], } ldif = ldap.modlist.addModlist(attrs) with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.add_s(dn, ldif) def test_modify_s_no_such_object(self): mod_list = [(ldap.MOD_REPLACE, 'userPassword', 'test')] with self.assertRaises(ldap.NO_SUCH_OBJECT): self.ldapobj.modify_s('ou=invalid,o=test', mod_list) def test_modify_s_success_code(self): new_pw = ['alice', 'alicepw2'] mod_list = [(ldap.MOD_REPLACE, 'userPassword', new_pw)] result = self.ldapobj.modify_s(alice[0], mod_list) self.assertEqual(result, (103, [])) def test_modify_s_replace_value_of_attribute_with_multiple_others(self): new_pw = ['alice', 'alicepw2'] mod_list = [(ldap.MOD_REPLACE, 'userPassword', new_pw)] self.ldapobj.modify_s(alice[0], mod_list) self.assertEqual(self.ldapobj.directory[alice[0]]['userPassword'], new_pw) def test_modify_s_replace_value_of_attribute_with_another_single(self): new_pw = 'alice' mod_list = [(ldap.MOD_REPLACE, 'userPassword', new_pw)] self.ldapobj.modify_s(alice[0], mod_list) self.assertEqual(self.ldapobj.directory[alice[0]]['userPassword'], [new_pw]) def test_modify_s_replace_with_none(self): mod_list = [(ldap.MOD_REPLACE, 'objectClass', None)] self.ldapobj.modify_s(manager[0], mod_list) self.assertNotIn('objectClass', self.ldapobj.directory[manager[0]].keys()) def test_modify_s_add_single_value_to_attribute(self): old_pw = copy(self.ldapobj.directory[alice[0]]['userPassword']) new_pw = 'test' mod_list = [(ldap.MOD_ADD, 'userPassword', new_pw)] self.ldapobj.modify_s(alice[0], mod_list) self.assertEqual(set(old_pw) | set([new_pw]), set(self.ldapobj.directory[alice[0]]['userPassword'])) def test_modify_s_add_multiple_values_to_attribute(self): old_pw = copy(self.ldapobj.directory[alice[0]]['userPassword']) new_pw = ['test1', 'test2'] mod_list = [(ldap.MOD_ADD, 'userPassword', new_pw)] self.ldapobj.modify_s(alice[0], mod_list) self.assertEqual(set(old_pw) | set(new_pw), set(self.ldapobj.directory[alice[0]]['userPassword'])) def test_modify_s_create_on_add(self): """ Create an attribute by adding the first value. """ self.ldapobj.modify_s(alice[0], [(ldap.MOD_ADD, 'someAttr', 'value')]) self.assertEqual(self.ldapobj.directory[alice[0]]['someAttr'], ['value']) def test_modify_s_add_none_value_raises_protocol_error(self): mod_list = [(ldap.MOD_ADD, 'userPassword', None)] with self.assertRaises(ldap.PROTOCOL_ERROR): self.ldapobj.modify_s(bob[0], mod_list) def test_modify_s_dont_add_already_existing_value(self): old_pw = copy(self.ldapobj.directory[bob[0]]['userPassword']) mod_list = [(ldap.MOD_ADD, 'userPassword', 'bobpw')] self.ldapobj.modify_s(bob[0], mod_list) self.assertEqual(self.ldapobj.directory[bob[0]]['userPassword'], old_pw) def test_modify_s_delete_single_value_from_attribute(self): mod_list = [(ldap.MOD_DELETE, 'userPassword', 'bobpw')] self.ldapobj.modify_s(bob[0], mod_list) self.assertEqual(self.ldapobj.directory[bob[0]]['userPassword'], ['bobpw2']) def test_modify_s_delete_multiple_values_from_attribute(self): mod_list = [(ldap.MOD_DELETE, 'objectClass', ['top', 'inetOrgPerson'])] self.ldapobj.modify_s(manager[0], mod_list) self.assertEqual(self.ldapobj.directory[manager[0]]['objectClass'], ['posixAccount']) def test_modify_s_delete_all_values_from_attribute(self): mod_list = [(ldap.MOD_DELETE, 'objectClass', None)] self.ldapobj.modify_s(manager[0], mod_list) self.assertTrue('objectClass' not in self.ldapobj.directory[manager[0]]) def test_modify_s_delete_every_from_attribute(self): """ Delete all values explicitly, which deletes the attributes. """ mod_list = [(ldap.MOD_DELETE, 'objectClass', manager[1]['objectClass'])] self.ldapobj.modify_s(manager[0], mod_list) self.assertTrue('objectClass' not in self.ldapobj.directory[manager[0]]) def test_modify_s_invalid_dn(self): mod_list = [(ldap.MOD_DELETE, 'objectClass', None)] with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.modify_s('invalid', mod_list) def test_rename_s_successful_code(self): result = self.ldapobj.rename_s('cn=alice,ou=example,o=test', 'uid=alice1') self.assertEqual(result, (109, [])) def test_rename_s_only_rdn_check_dn(self): self.ldapobj.rename_s(alice[0], 'uid=alice1') self.assertIn('uid=alice1,ou=example,o=test', self.ldapobj.directory.keys()) def test_rename_s_only_rdn_append_value_to_existing_attr(self): self.ldapobj.rename_s(alice[0], 'uid=alice1') self.assertEquals( self.ldapobj.directory['uid=alice1,ou=example,o=test']['uid'], ['alice', 'alice1'] ) def test_rename_s_only_rdn_create_new_attr(self): self.ldapobj.rename_s(alice[0], 'sn=alice1') self.assertIn('sn', self.ldapobj.directory['sn=alice1,ou=example,o=test']) self.assertEquals(self.ldapobj.directory['sn=alice1,ou=example,o=test']['sn'], ['alice1']) def test_rename_s_removes_old_dn(self): self.ldapobj.rename_s(alice[0], 'uid=alice1') self.assertNotIn(alice[0], self.ldapobj.directory.keys()) def test_rename_s_removes_old_attr(self): self.ldapobj.rename_s(alice[0], 'uid=alice1') self.assertNotIn('cn', self.ldapobj.directory['uid=alice1,ou=example,o=test']) def test_rename_s_does_not_remove_multivalued_old_attr(self): self.ldapobj.directory[alice[0]]['cn'].append('alice1') self.ldapobj.rename_s(alice[0], 'uid=alice1') self.assertIn('cn', self.ldapobj.directory['uid=alice1,ou=example,o=test']) self.assertIn('alice1', self.ldapobj.directory['uid=alice1,ou=example,o=test']['cn']) self.assertNotIn('alice', self.ldapobj.directory['uid=alice1,ou=example,o=test']['cn']) def test_rename_s_newsuperior_check_dn(self): self.ldapobj.rename_s(alice[0], 'uid=alice1', 'ou=new,o=test') self.assertIn('uid=alice1,ou=new,o=test', self.ldapobj.directory) def test_rename_s_no_such_object(self): self.assertRaises(ldap.NO_SUCH_OBJECT, self.ldapobj.rename_s, 'uid=invalid,ou=example,o=test', 'uid=invalid2') def test_rename_s_already_exists(self): with self.assertRaises(ldap.ALREADY_EXISTS): self.ldapobj.rename_s(alice[0], "cn=manager") def test_rename_s_invalid_dn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.rename_s('invalid', 'uid=blah') def test_rename_s_invalid_newrdn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.rename_s('uid=something,ou=example,o=test', 'invalid') def test_rename_s_invalid_newsuperior(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.rename_s('uid=alice,ou=example,o=test', 'cn=alice', 'invalid') def test_delete_s_success_code(self): self.assertEqual(self.ldapobj.delete_s(alice[0]), (107, [])) def test_delete_s_successful_removal(self): self.ldapobj.delete_s(alice[0]) self.assertNotIn(alice[0], self.ldapobj.directory) def test_delete_s_no_such_object(self): with self.assertRaises(ldap.NO_SUCH_OBJECT): self.ldapobj.delete_s('uid=invalid,ou=example,o=test') def test_delete_s_invalid_dn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.delete_s('invalid') def test_unbind(self): self.ldapobj.simple_bind_s(alice[0], 'alicepw') self.ldapobj.unbind() self.assertEqual(self.ldapobj.bound_as, None) def test_unbind_s(self): self.ldapobj.simple_bind_s(alice[0], 'alicepw') self.ldapobj.unbind_s() self.assertEqual(self.ldapobj.bound_as, None) def test_whoami_s(self): self.ldapobj.simple_bind_s(alice[0], 'alicepw') self.assertEqual(self.ldapobj.whoami_s(), 'dn:cn=alice,ou=example,o=test') def test_passwd_s_no_such_object(self): with self.assertRaises(ldap.NO_SUCH_OBJECT): self.ldapobj.passwd_s('uid=invalid,ou=example,o=test', '1', '2') def test_passwd_s_invalid_dn(self): with self.assertRaises(ldap.INVALID_DN_SYNTAX): self.ldapobj.passwd_s('invalid', '1', '2') def test_passwd_s_no_old_password(self): self.ldapobj.passwd_s(alice[0], None, 'newpw') self.assertEquals(self.ldapobj.directory[alice[0]]['userPassword'], ['newpw']) def test_passwd_s_wrong_old_password(self): # In case of wrong old password do nothing self.ldapobj.passwd_s(alice[0], 'wrong', 'newpw') self.assertEquals(self.ldapobj.directory[alice[0]]['userPassword'], alice[1]['userPassword']) def initialize(*args, **kwargs): """ Dummy patch target for the tests below. """ pass class TestMockLdap(unittest.TestCase): @classmethod def setUpClass(cls): cls.mockldap = MockLdap(directory) @classmethod def tearDownClass(cls): del cls.mockldap def tearDown(self): self.mockldap.stop_all() def test_uninitialized(self): self.assertRaises(KeyError, lambda: self.mockldap['']) def test_duplicate_patch(self): self.mockldap.start() self.assertRaises(ValueError, lambda: self.mockldap.start()) def test_unbalanced_stop(self): self.assertRaises(ValueError, lambda: self.mockldap.stop()) def test_stop_penultimate(self): self.mockldap.start() self.mockldap.start('mockldap.tests.initialize') self.mockldap.stop() self.assertTrue(self.mockldap[''] is not None) def test_stop_last(self): self.mockldap.start() self.mockldap.start('mockldap.tests.initialize') self.mockldap.stop() self.mockldap.stop('mockldap.tests.initialize') self.assertRaises(KeyError, lambda: self.mockldap['']) def test_initialize(self): self.mockldap.start() conn = ldap.initialize('ldap:///') self.assertEqual(conn.methods_called(), ['initialize']) def test_specific_content(self): tmp_directory = dict([alice, bob]) self.mockldap.set_directory(tmp_directory, uri='ldap://example.com/') self.mockldap.start() conn = ldap.initialize('ldap://example.com/') self.assertEqual(conn.directory, tmp_directory) def test_no_default(self): mockldap = MockLdap() mockldap.start() self.assertRaises(KeyError, lambda: mockldap['']) def test_indepdendent_connections(self): self.mockldap.start() self.assertNotEqual(self.mockldap['foo'], self.mockldap['bar']) def test_volatile_modification(self): self.mockldap.start() conn1 = ldap.initialize('') conn1.directory['cn=alice,ou=example,o=test'][ 'userPassword'][0] = 'modified' self.mockldap.stop() self.mockldap.start() conn2 = ldap.initialize('') self.mockldap.stop() self.assertNotEqual(conn1.directory, conn2.directory) mockldap-0.2.5/src/mockldap.egg-info/0000755000076600000240000000000012540073641020155 5ustar psagersstaff00000000000000mockldap-0.2.5/src/mockldap.egg-info/dependency_links.txt0000644000076600000240000000000112540073641024223 0ustar psagersstaff00000000000000 mockldap-0.2.5/src/mockldap.egg-info/PKG-INFO0000644000076600000240000000236612540073641021261 0ustar psagersstaff00000000000000Metadata-Version: 1.1 Name: mockldap Version: 0.2.5 Summary: A simple mock implementation of python-ldap. Home-page: http://bitbucket.org/psagers/mockldap/ Author: Peter Sagerson Author-email: psagers.pypi@ignorare.net License: BSD Description: This project provides a mock replacement for python-ldap. It's useful for any project that would like to write unit tests against LDAP code without relying on a running LDAP server. Keywords: mock,ldap Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Web Environment Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: BSD License Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: System :: Systems Administration :: Authentication/Directory :: LDAP Classifier: Topic :: Software Development :: Libraries :: Python Modules mockldap-0.2.5/src/mockldap.egg-info/requires.txt0000644000076600000240000000004512540073641022554 0ustar psagersstaff00000000000000python-ldap funcparserlib==0.3.6 mockmockldap-0.2.5/src/mockldap.egg-info/SOURCES.txt0000644000076600000240000000077112540073641022046 0ustar psagersstaff00000000000000CHANGES LICENSE MANIFEST.in README setup.py docs/Makefile docs/source/changes.rst docs/source/conf.py docs/source/directories.rst docs/source/index.rst docs/source/operations.rst docs/source/overview.rst src/mockldap/__init__.py src/mockldap/filter.py src/mockldap/ldapobject.py src/mockldap/recording.py src/mockldap/tests.py src/mockldap.egg-info/PKG-INFO src/mockldap.egg-info/SOURCES.txt src/mockldap.egg-info/dependency_links.txt src/mockldap.egg-info/requires.txt src/mockldap.egg-info/top_level.txtmockldap-0.2.5/src/mockldap.egg-info/top_level.txt0000644000076600000240000000001112540073641022677 0ustar psagersstaff00000000000000mockldap