o 6aH@sVdZddlmZddlZddlZddlmZddlmZddl Z ddl Z ddl Z ddl m Z ddl mZddl mZddlZddlZdd lmZdd lmZddlZddlZddlZdd lmZdd lmZdd lmZddlmZddlm Z ddl!m"Z#ddl$m%Z%ddl$m&Z&dd l'mZ(ddl)m*Z*z ddl+Z+e,de-Wne.yddlm+Z+YnwGddde*j/Z0ddZ1ddZ2ddZ3ddZ4d d!Z5d"d#Z6d$d%Z7d&d'Z8dHd)d*Z9dId,d-Z: + dJd.d/Z;d0d1Zd6d7Z?d8d9Z@d:d;ZAGdd?d?eCZDd@dAZEdBdCZFdDdEZGdFdGZHdS)LzTest utilities.)reloadN)Event)Process)Iterable)List)Optional)default_backend) serialization) configuration)util) constants)lock)storage)obj) filesystem)os)commonzThe external mock module is being used for backwards compatibility since it is available, however, future versions of Certbot's tests will use unittest.mock. Be sure to update your code accordingly.)mockc @seZdZdZdeefddZdedededed edd f d d Zd"ded edee edd fddZ de efddZ d#deede dd fddZ d$ddZd$ddZeddZd$ddZdefd d!Zd S)%DummyInstallerz(Dummy installer plugin for test purpose.returncCdSNselfrr4/usr/lib/python3/dist-packages/certbot/tests/util.py get_all_names2zDummyInstaller.get_all_namesdomain cert_pathkey_path chain_pathfullchain_pathNcCrrr)rrrr r!r"rrr deploy_cert5zDummyInstaller.deploy_cert enhancementoptionscCrrr)rrr%r&rrrenhance9rzDummyInstaller.enhancecCrrrrrrrsupported_enhancements<rz%DummyInstaller.supported_enhancementsFtitle temporarycCrrr)rr)r*rrrsave?rzDummyInstaller.savecCrrrrrrr config_testBrzDummyInstaller.config_testcCrrrrrrrrestartErzDummyInstaller.restartcCrrr)clsaddrrradd_parser_argumentsHr$z#DummyInstaller.add_parser_argumentscCrrrrrrrprepareLrzDummyInstaller.preparecCrrrrrrr more_infoOrzDummyInstaller.more_infor)NF)rN)__name__ __module__ __qualname____doc__rstrrr#rrr'r(boolr+r,r- classmethodr0r1r2rrrrr0s" $    rcGstttjjdg|RS)zPath to a test vector.testdata) pkg_resourcesresource_filenamer3rpathjoinnamesrrr vector_pathSsrAcGsJtttjjdg|R}z |ddWSt y$|YSw)zLoad contents of a test vector.r:z  ) r;resource_stringr3rr=r>decodereplaceencode ValueError)r@datarrr load_vectorYs rIcCs8tj|\}}|dkr|S|dkr|Std)Nz.pemz.derz1Loader could not be recognized based on extension)rr=splitextlowerrG)filename loader_pem loader_der_extrrr _guess_loadergs   rQcG*t|dtjjtjj}tj|t|S)zLoad certificate.)rQOpenSSLcrypto FILETYPE_PEM FILETYPE_ASN1load_certificaterIr@loaderrrr load_certpr[cGrR)zLoad certificate request.rS)rQrTrUrVrWload_certificate_requestrIrYrrrload_csrwr\r^cGstt|S)z(Load ComparableX509 certificate request.)joseComparableX509r^r?rrrload_comparable_csr~racGs.t|dtjtj}t|t|dtdS)zLoad RSA private key.rSN)passwordbackend)rQr load_pem_private_keyload_der_private_keyr_ComparableRSAKeyrIrrYrrrload_rsa_private_keys  rhcGrR)zLoad pyOpenSSL private key.rS)rQrTrUrVrWload_privatekeyrIrYrrrload_pyopenssl_private_keyr\rjFc s~|dtd }tjtj}tjtj|}tjtj|}|||fD] }tj|s5t |q(t d |r=dnd}t |D]} ttj|| tj|| qFtjD]} ttj|d | tj|d | q\tj||} tt |2} t| d} | fd d | DWdn1swYWd| SWd| S1swY| S) apCreates a lineage defined by testfile. This creates the archive, live, and renewal directories if necessary and creates a simple lineage. :param str config_dir: path to the configuration directory :param str testfile: configuration file to base the lineage on :returns: path to the renewal conf file for the created lineage :rtype: str Nz.confzsample-archive{}z-ecz{0}1.pemz{0}.pemwc3s|] }|dVqdS)MAGICDIRN)rE).0line config_dirrr s  zmake_lineage..)lenrr=r>r RENEWAL_CONFIGS_DIR ARCHIVE_DIRLIVE_DIRexistsrmakedirsrAformatlistdirshutilcopyfilerALL_FOURsymlinkopen writelines) rqtestfileec lineage_nameconf_dir archive_dirlive_dir directorysample_archivekind conf_pathsrcdstrrpr make_lineagesJ         rzope.component.getUtilitycCstdtj|tdS)zDeprecated, patch certbot.display.util directly or use patch_display_util instead. :param str target: path to patch :returns: mock zope.component.getUtility :rtype: mock.MagicMock zDecorator certbot.tests.util.patch_get_utility is deprecated. You should now patch certbot.display.util yourself directly or use certbot.tests.util.patch_display_util as a temporary workaround. new_callable)warningswarnrpatch_create_display_util_mock)targetrrrpatch_get_utilitys rcCs0td|r |nt}t|}tj||dS)aEDeprecated, patch certbot.display.util directly or use patch_display_util_with_stdout instead. :param str target: path to patch :param object stdout: object to write standard output to; it is expected to have a `write` method :returns: mock zope.component.getUtility :rtype: mock.MagicMock zDecorator certbot.tests.util.patch_get_utility_with_stdout is deprecated. You should now patch certbot.display.util yourself directly or use use certbot.tests.util.patch_display_util_with_stdout as a temporary workaround.new)rrioStringIO%_create_display_util_mock_with_stdoutrr)rstdoutfreezable_mockrrrpatch_get_utility_with_stdouts rcCstjdtdS)aPatch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals so this can be used like the old patch_get_utility function. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: unittest.mock._patch )certbot._internal.display.obj.get_displayr)rrrrrrrpatch_display_utilsrcCs"|r|nt}tjdt|dS)a]Patch certbot.display.util to use a special mock display utility. The mock display utility works like a regular mock object, except it also asserts that methods are called with valid arguments. The mock created by this patch mocks out Certbot internals so this can be used like the old patch_get_utility function. That is, the mock object will be called by the certbot.display.util functions and the mock returned by that call will be used as the display utility. This was done to simplify the transition from zope.component and mocking certbot.display.util functions directly in test code should be preferred over using this function in the future. See https://github.com/certbot/certbot/issues/8948 The `message` argument passed to the display utility methods is passed to stdout's write method. :param object stdout: object to write standard output to; it is expected to have a `write` method :returns: patch on the function used internally by certbot.display.util to get a display utility instance :rtype: unittest.mock._patch rr)rrrrrrrrrpatch_display_util_with_stdoutsrc@sDeZdZdZddejjfddZddZdd Z d d Z d d Z dS) FreezableMockaMock object with the ability to freeze attributes. This class works like a regular mock.MagicMock object, except attributes and behavior set before the object is frozen cannot be changed during tests. If a func argument is provided to the constructor, this function is called first when an instance of FreezableMock is called, followed by the usual behavior defined by MagicMock. The return value of func is ignored. FNcCs>|rtndh|_||_t|_|tjjkr||_||_ dS)Nfreeze) set _frozen_set_funcr MagicMock_mocksentinelDEFAULT return_value_frozen)rfrozenfuncrrrr__init__)s    zFreezableMock.__init__cCs d|_dS)z)Freeze object preventing further changes.TN)rrrrrr1s zFreezableMock.freezecOs*|jdur |j|i||j|i|Sr)rr)rargskwargsrrr__call__5s zFreezableMock.__call__cCsv|dkrzt||WStyYdSw|dvr#tt|d|S|dks,||jvr2t||Stt|d|S)NrFr side_effectrr)object__getattribute__AttributeErrorgetattrr)rnamerrrr:s  zFreezableMock.__getattribute__cCsb|jr||jvrtd|t|j||S|dkr|j||dvr*t|j||St|||S)a Before it is frozen, attributes are set on the FreezableMock instance and added to the _frozen_set. Attributes in the _frozen_set cannot be changed after the FreezableMock is frozen. In this case, they are set on the underlying _mock. In cases of return_value and side_effect, these attributes are always passed through to the instance's _mock and added to the _frozen_set before the object is frozen. zCannot change frozen attribute rr)rrrsetattrrr/r __setattr__)rrvaluerrrrGs   zFreezableMock.__setattr__) r3r4r5r6rrrrrrrrrrrrrs  rcCsXt}ddttjD}|D]}|dkr!tdtd}t|||q|td|dS)NcS*g|]}tttj|r|ds|qS__callabler display_obj FileDisplay startswithrnrrrr c  z-_create_display_util_mock.. notificationTrrrr)rdirrr_assert_valid_callrr)display method_listmethod frozen_mockrrrr`s   rcs~fddfdd}t}ddttjD}|D]}|dkr(tdd }ntd|d }t|||q|td|d S) Ncs|r |dSdS)z$Write to message to stdout. N)write)message unused_args unused_kwargsrrr _write_msgosz9_create_display_util_mock_with_stdout.._write_msgcst|||i|dS)z< Mock function for display utility methods. N)r)rr)rrr mock_methodus z:_create_display_util_mock_with_stdout..mock_methodcSrrrrrrrr~rz9_create_display_util_mock_with_stdout..rTrr)rrrrrr)rrrrrrr)rrrrns   rcOs^|r|dn|dg}i}|dd|d<|dd|d<|dd|d<tj|i|dS)Nrrdefaultcli_flagforce_interactiveF)get display_utilassert_valid_call)rr assert_args assert_kwargsrrrrs rc@s eZdZdZddZddZdS)TempDirTestCasezBBase test class which sets up and tears down a temporary directorycCst|_dS)zExecute before testN)tempfilemkdtemptempdirrrrrsetUprbzTempDirTestCase.setUpcCs*tgt_tt|jdS)zExecute after testN) loggingshutdown getLoggerhandlersr _release_locksr{rmtreerrrrrtearDowns zTempDirTestCase.tearDownN)r3r4r5r6rrrrrrrs rcs eZdZdZfddZZS)ConfigTestCasez2Test class which sets up a NamespaceConfig object.cstttjditj|_d|jj _ t j |jd|jj _t j |jd|jj _t j |jd|jj _tjd|jj _tjd|jj _tjd|jj _d|jj _dS) Ncertonlyconfigworklogsauth_cert_pathauth_chain_pathzhttps://example.comr)superrr NamespaceConfigrrr CLI_DEFAULTSr namespaceverbrr=r>rrqwork_dirlogs_dirrr"r!serverr __class__rrrs  zConfigTestCase.setUp)r3r4r5r6r __classcell__rrrrrsrcCsXtj|r t|}nt|}z||jdds JdW|dS|w)a Acquire a file lock on given path, then wait to release it. This worker is coordinated using events to signal when the lock should be acquired and released. :param multiprocessing.Event event_in: event object to signal when to release the lock :param multiprocessing.Event event_out: event object to signal when the lock is acquired :param path: the path to lock timeoutz*Timeout while waiting to release the lock.N) rr=isdirr lock_dirLockFilerwaitrelease)event_in event_outr=my_lockrrr _handle_locks   r cCsnttt}t}tt|||fd}||jdds!Jd|||jdd|j dks5JdS)z Grab a lock on path_to_lock from a foreign process then execute the callback. :param callable callback: object to call after acquiring the lock :param str path_to_lock: path to file or directory to lock )rr rz*Timeout while waiting to acquire the lock.rN) reload_moduler rrr startrrr>exitcode)callback path_to_lock emit_event receive_eventprocessrrr lock_and_calls rcsfdd}|S)zFDecorator to skip permanently a test on Windows. A reason is required.csttjdk|S)zWrapped versionwin32)unittestskipIfsysplatform)functionreasonrrwrappersz skip_on_windows..wrapperr)rrrrrskip_on_windowss rcCstjt|S)z Return the given path joined to the tempdir path for the current platform Eg.: 'cert' => /tmp/cert (Linux) or 'C:\Users\currentuser\AppData\Temp\cert' (Windows) )rr=r>r gettempdir)r=rrr temp_joinsr)F)r)rNr)Ir6 importlibrr rrmultiprocessingrrr{rrtypingrrrrrcryptography.hazmat.backendsrcryptography.hazmat.primitivesr josepyr_rTr;certbotr r certbot._internalr r rcertbot._internal.displayrrcertbot.compatrrcertbot.displayrcertbot.pluginsrrrPendingDeprecationWarning ImportError InstallerrrArIrQr[r^rarhrjrrrrrrrrrTestCaserrr rrrrrrrs                   #   ,   D