Esempio n. 1
0
 def test_environment_options(self):
     """DocuSignClient uses DOCUSIGN_* environment variables."""
     environ_options = {
         'DOCUSIGN_ROOT_URL': 'http://other.example.com',
         'DOCUSIGN_USERNAME': '******',
         'DOCUSIGN_PASSWORD': '******',
         'DOCUSIGN_INTEGRATOR_KEY': 'not-an-integator-key',
         'DOCUSIGN_ACCOUNT_ID': 'not-an-uuid',
         'DOCUSIGN_APP_TOKEN': 'not-a-token',
         'DOCUSIGN_TIMEOUT': '200.123',
     }
     environ_backup = dict(os.environ).copy()
     try:
         # Alter environment.
         for key, value in environ_options.items():
             os.environ[key] = value
         # Instanciate client.
         client = pydocusign.DocuSignClient()
         # Check environment variables have been used.
         for key, value in environ_options.items():
             attribute = key.lower()[len('DOCUSIGN_'):]
             if attribute == 'timeout':
                 value = float(value)
             self.assertEqual(getattr(client, attribute), value)
     finally:
         # Restore os.environ.
         for key, value in environ_backup.items():
             os.environ[key] = value
Esempio n. 2
0
 def test_options_priority(self):
     """Explicit arguments to DocuSignClient have priority over env vars."""
     explicit_options = {
         'root_url': 'http://example.com',
         'username': '******',
         'password': '******',
         'integrator_key': 'very-secret',
         'account_id': 'some-uuid',
         'app_token': 'some-token',
         'timeout': 300.0,
     }
     environ_options = {
         'DOCUSIGN_ROOT_URL': 'http://other.example.com',
         'DOCUSIGN_USERNAME': '******',
         'DOCUSIGN_PASSWORD': '******',
         'DOCUSIGN_INTEGRATOR_KEY': 'not-an-integator-key',
         'DOCUSIGN_ACCOUNT_ID': 'not-an-uuid',
         'DOCUSIGN_APP_TOKEN': 'not-a-token',
         'DOCUSIGN_TIMEOUT': '200.123',
     }
     environ_backup = dict(os.environ).copy()
     try:
         # Alter environment.
         for key, value in environ_options.items():
             os.environ[key] = value
         # Instanciate client with explicit options.
         client = pydocusign.DocuSignClient(**explicit_options)
         # Check.
         for key, value in explicit_options.items():
             self.assertEqual(getattr(client, key), value)
     finally:
         # Restore os.environ.
         for key, value in environ_backup.items():
             os.environ[key] = value
Esempio n. 3
0
    def test_sobo_with_regular_auth(self):
        client = pydocusign.DocuSignClient()

        sobo_email = '*****@*****.**'

        headers = client.base_headers(sobo_email)

        auth_header = json.loads(headers['X-DocuSign-Authentication'])

        self.assertIn('SendOnBehalfOf', auth_header)
        self.assertEqual(auth_header['SendOnBehalfOf'], sobo_email)
Esempio n. 4
0
    def test_sobo_with_oauth2(self):
        client = pydocusign.DocuSignClient(root_url='http://example.com',
                                           account_id='some-uuid',
                                           oauth2_token='some-oauth2-token')

        sobo_email = '*****@*****.**'

        headers = client.base_headers(sobo_email)

        self.assertIn('X-DocuSign-Act-As-User', headers)
        self.assertEqual(headers['X-DocuSign-Act-As-User'], sobo_email)
Esempio n. 5
0
 def test_explicit_options(self):
     """DocuSignClient() uses explicit arguments."""
     explicit_options = {
         'root_url': 'http://example.com',
         'username': '******',
         'password': '******',
         'integrator_key': 'very-secret',
         'account_id': 'some-uuid',
         'app_token': 'some-token',
         'timeout': 300.0,
     }
     client = pydocusign.DocuSignClient(**explicit_options)
     for key, value in explicit_options.items():
         self.assertEqual(getattr(client, key), value)
Esempio n. 6
0
 def test_create_envelope_from_document_request(self):
     """Request for creating envelope for document has expected format."""
     docusign = pydocusign.DocuSignClient()
     docusign.login_information()
     with open(os.path.join(pydocusign.test.fixtures_dir(), 'test.pdf'),
               'rb') as pdf_file:
         envelope = pydocusign.Envelope(emailSubject='This is the subject',
                                        emailBlurb='This is the body',
                                        status=models.ENVELOPE_STATUS_SENT,
                                        documents=[
                                            pydocusign.Document(
                                                name='document.pdf',
                                                documentId=1,
                                                data=pdf_file,
                                            ),
                                        ],
                                        recipients=[
                                            pydocusign.Signer(
                                                email='*****@*****.**',
                                                name='Zorro',
                                                recipientId=1,
                                                tabs=[
                                                    pydocusign.SignHereTab(
                                                        documentId=1,
                                                        pageNumber=1,
                                                        xPosition=100,
                                                        yPosition=100,
                                                    ),
                                                    pydocusign.ApproveTab(
                                                        documentId=1,
                                                        pageNumber=1,
                                                        xPosition=100,
                                                        yPosition=200,
                                                    ),
                                                ],
                                                accessCode='0000',
                                            ),
                                        ])
         parts = docusign._create_envelope_from_document_request(envelope)
     self.assertTrue(parts['url'].startswith(docusign.account_url))
     self.assertTrue(parts['url'].endswith('/envelopes'))
     self.assertEqual(parts['headers']['Content-Type'],
                      'multipart/form-data; boundary=myboundary')
     self.assertTrue(parts['body'].strip().startswith(
         '--myboundary\r\n'
         'Content-Type: application/json; charset=UTF-8\r\n'
         'Content-Disposition: form-data\r\n'
         '\r\n'))
Esempio n. 7
0
    def __init__(self, name='DocuSign', code='docusign',
                 url_namespace='anysign', **kwargs):
        """Setup.

        Additional ``kwargs`` are proxied to
        :class:`pydocusign.DocuSignClient`.

        """
        super(DocuSignBackend, self).__init__(
            name=name,
            code=code,
            url_namespace=url_namespace,
        )
        client_kwargs = self.get_client_kwargs(**kwargs)
        #: Instance of :class:`~pydocusign.client.DocuSignClient`
        self.docusign_client = pydocusign.DocuSignClient(**client_kwargs)
Esempio n. 8
0
 def test_login_information(self):
     """DocuSignClient.login_information() populates account information."""
     docusign = pydocusign.DocuSignClient()
     result = docusign.login_information()
     self.assertIn('loginAccounts', result)
     self.assertEqual(len(result['loginAccounts']), 1)
     self.assertIn('userName', result['loginAccounts'][0])
     self.assertIn('name', result['loginAccounts'][0])
     self.assertIn('siteDescription', result['loginAccounts'][0])
     self.assertIn('userId', result['loginAccounts'][0])
     self.assertIn('baseUrl', result['loginAccounts'][0])
     self.assertIn('email', result['loginAccounts'][0])
     self.assertIn('isDefault', result['loginAccounts'][0])
     self.assertIn('accountId', result['loginAccounts'][0])
     self.assertEqual(docusign.account_id,
                      result['loginAccounts'][0]['accountId'])
     self.assertNotEqual(docusign.account_url, '')
Esempio n. 9
0
    def test_token(self):
        token = pydocusign.DocuSignClient.oauth2_token_request(
            self.root_url, self.username, self.password, self.integrator_key)

        os.environ['DOCUSIGN_OAUTH2_TOKEN'] = token

        docusign = pydocusign.DocuSignClient(root_url=self.root_url)
        result = docusign.login_information()
        self.assertIn('loginAccounts', result)
        self.assertEqual(len(result['loginAccounts']), 1)
        self.assertIn('userName', result['loginAccounts'][0])
        self.assertIn('name', result['loginAccounts'][0])
        self.assertIn('siteDescription', result['loginAccounts'][0])
        self.assertIn('userId', result['loginAccounts'][0])
        self.assertIn('baseUrl', result['loginAccounts'][0])
        self.assertIn('email', result['loginAccounts'][0])
        self.assertIn('isDefault', result['loginAccounts'][0])
        self.assertIn('accountId', result['loginAccounts'][0])
        self.assertEqual(docusign.account_id,
                         result['loginAccounts'][0]['accountId'])
        self.assertNotEqual(docusign.account_url, '')

        pydocusign.DocuSignClient.oauth2_token_revoke(self.root_url, token)
Esempio n. 10
0

# Get configuration from environment or prompt the user...
root_url = prompt('DOCUSIGN_ROOT_URL', 'DocuSign API URL',
                  'https://demo.docusign.net/restapi/v2')
username = prompt('DOCUSIGN_USERNAME', 'DocuSign API username', '')
password = prompt('DOCUSIGN_PASSWORD', 'DocuSign API password', '')
integrator_key = prompt('DOCUSIGN_INTEGRATOR_KEY',
                        'DocuSign API integrator key', '')
signer_return_url = prompt('DOCUSIGN_TEST_SIGNER_RETURN_URL',
                           'Signer return URL', '')

# Create a client.
client = pydocusign.DocuSignClient(
    root_url=root_url,
    username=username,
    password=password,
    integrator_key=integrator_key,
)

# Login. Updates API URLs in client.
print("1. GET /login_information")
login_information = client.login_information()
print("   Received data: {data}".format(data=login_information))

# Prepare list of signers. Ordering matters.
signers = [
    pydocusign.Signer(
        email='*****@*****.**',
        name=u'Jean Français',
        recipientId=1,
        clientUserId=str(uuid.uuid4()),  # Something unique in your database.
Esempio n. 11
0
def getLinkFromPDF():
    try:
        raw_input
    except NameError:
        raw_input = input

    def prompt(environ_key, description, default):
        try:
            return os.environ[environ_key]
        except KeyError:
            value = raw_input('{description} (default: "{default}"): '.format(
                default=default, description=description))
            if not value:
                return default
            else:
                return value

    # Get configuration from environment or prompt the user...
    root_url = 'https://demo.docusign.net/restapi/v2'
    username = '******'
    password = '******'
    integrator_key = '886c800a-506f-45c7-8db2-a19ab7d4b0a6'
    callback_url = 'www.google.com'
    signer_return_url = 'www.google.com'

    # Create a client.
    client = pydocusign.DocuSignClient(
        root_url=root_url,
        username=username,
        password=password,
        integrator_key=integrator_key,
    )

    # Login. Updates API URLs in client.
    print("1. GET /login_information")
    login_information = client.login_information()
    print("   Received data: {data}".format(data=login_information))

    #Prepare list of signers. Ordering matters.
    signers = [
        pydocusign.Signer(
            email='*****@*****.**',
            name=u'Spencer King',
            recipientId=1,
            clientUserId=str(
                uuid.uuid4()),  # Something unique in your database.
            tabs=[
                pydocusign.SignHereTab(
                    documentId=1,
                    pageNumber=1,
                    xPosition=100,
                    yPosition=200,
                ),
            ],
            emailSubject='Test PDF Docusign Script',
            emailBody='I am testing the docusign script',
            supportedLanguage='en',
        ),
        pydocusign.Signer(
            email='*****@*****.**',
            name=u'Eduardo Lopez',
            recipientId=2,
            clientUserId=str(
                uuid.uuid4()),  # Something unique in your database.
            # tabs=[],  # No tabs means user places tabs himself in DocuSign UI.
            tabs=[
                pydocusign.SignHereTab(
                    documentId=1,
                    pageNumber=1,
                    xPosition=100,
                    yPosition=400,
                ),
            ],
            emailSubject='Well docusign is working',
            emailBody=
            'Figured out how to take a text doc, pdf it, and create and send the signing request, woohoo',
            supportedLanguage='en',
        ),
    ]

    # Create envelope with embedded signing.
    print("2. POST {account}/envelopes")
    event_notification = pydocusign.EventNotification(url=callback_url, )
    document_path = "./Client_Contracts/Final.pdf"  # os.path.join(fixtures_dir(), 'test.pdf')
    #document_2_path = "./test2.pdf"      # os.path.join(fixtures_dir(), 'test2.pdf')
    with open(document_path,
              'rb') as pdf:  #, open(document_2_path, 'rb') as pdf_2:
        envelope = pydocusign.Envelope(
            documents=[
                pydocusign.Document(
                    name='HelloWorldTest.pdf',
                    documentId=1,
                    data=pdf,
                )
            ],
            emailSubject=
            'What does this do - 1',  # Title in docusign demo/sent view
            emailBlurb='What does this do - 2',
            eventNotification=event_notification,
            status=pydocusign.Envelope.STATUS_SENT,
            recipients=signers,
        )
        client.create_envelope_from_documents(envelope)
    print("   Received envelopeId {id}".format(id=envelope.envelopeId))

    # Update recipient list of envelope: fetch envelope's ``UserId`` from DocuSign.
    print("3. GET {account}/envelopes/{envelopeId}/recipients")
    envelope.get_recipients()
    print("   Received UserId for recipient 0: {0}".format(
        envelope.recipients[0].userId))
    print("   Received UserId for recipient 1: {0}".format(
        envelope.recipients[1].userId))

    # Retrieve embedded signing for first recipient.
    print("4. Get DocuSign Recipient View")
    signing_url = envelope.post_recipient_view(envelope.recipients[0],
                                               returnUrl=signer_return_url)
    print("   Received signing URL for recipient 0: {0}".format(signing_url))
    signing_url = envelope.post_recipient_view(envelope.recipients[1],
                                               returnUrl=signer_return_url)
    print("   Received signing URL for recipient 1: {0}".format(signing_url))

    # Download signature documents.
    print("5. List signature documents.")
    document_list = envelope.get_document_list()
    print("   Received document list: {0}".format(document_list))
    print("6. Download documents from DocuSign.")
    for signed_document in document_list:
        document = envelope.get_document(signed_document['documentId'])
        document_sha = hashlib.sha1(document.read()).hexdigest()
        print("   Document SHA1: {0}".format(document_sha))
    print("7. Download signature certificate from DocuSign.")
    document = envelope.get_certificate()
    document_sha = hashlib.sha1(document.read()).hexdigest()
    print("   Certificate SHA1: {0}".format(document_sha))

    URLS = [
        envelope.post_recipient_view(  # Recipient URL 1
            envelope.recipients[0],
            returnUrl=signer_return_url),
        envelope.post_recipient_view(  # Recipient URL 2
            envelope.recipients[1],
            returnUrl=signer_return_url)
    ]

    return URLS
Esempio n. 12
0
    'DocuSign API distributor password',
    '')
callback_url = prompt(
    'DOCUSIGN_TEST_CALLBACK_URL',
    'Envelope callback URL',
    '')
signer_return_url = prompt(
    'DOCUSIGN_TEST_SIGNER_RETURN_URL',
    'Signer return URL',
    '')


# Create a client.
client = pydocusign.DocuSignClient(
    root_url=root_url,
    username=username,
    password=password,
    integrator_key=integrator_key,
)


# Login. Updates API URLs in client.
print("1. GET /login_information")
login_information = client.login_information()
print("   Received data: {data}".format(data=login_information))


# Get main account information.
print("2. GET /accounts/{accountId}".format(accountId=client.account_id))
account_information = client.get_account_information(client.account_id)
print("   Received data: {data}".format(data=account_information))
Esempio n. 13
0
 def test_get_recipients(self):
     """Envelope.get_recipients() updates recipients attribute."""
     # Setup fake envelope.
     signers = [
         models.Signer(
             email='*****@*****.**',
             name=u'Paul English',
             recipientId=32,
             clientUserId='2',
             tabs=[],
             emailSubject='Here is a subject',
             emailBody='Here is a message',
             supportedLanguage='en',
         ),
         models.Signer(
             email='*****@*****.**',
             name=u'This One Will Be Removed',
             recipientId=43,
             clientUserId='3',
             tabs=[],
             supportedLanguage='en',
         ),
     ]
     envelope = models.Envelope(recipients=signers)
     envelope.envelopeId = 'fake-envelope-id'
     # Setup response data, where signers have been updated after envelope
     # object was posted to DocuSign API.
     response_data = {
         "agents": [],
         "carbonCopies": [],
         "certifiedDeliveries": [],
         "currentRoutingOrder":
         "String content",
         "editors": [],
         "inPersonSigners": [],
         "intermediaries": [],
         "recipientCount":
         "String content",
         "signers": [
             {
                 "recipientId": "32",
                 "userId": "22",
                 "clientUserId": "2",
                 "roleName": "",
                 "routingOrder": "12",
                 "email": "*****@*****.**",
                 "name": "Paul English",
             },
             {
                 "recipientId": "31",
                 "userId": "21",
                 "clientUserId": "1",
                 "roleName": "",
                 "routingOrder": "11",
                 "email": "*****@*****.**",
                 "name": "Jean",
             },
         ],
     }
     client = pydocusign.DocuSignClient()
     client.get_envelope_recipients = mock.Mock(return_value=response_data)
     result = envelope.get_recipients(client=client)
     assert result is None
     self.assertEqual(len(envelope.recipients), 2)
     self.assertEqual(envelope.recipients[0].clientUserId, '1')
     self.assertEqual(envelope.recipients[0].routingOrder, 11)
     self.assertEqual(envelope.recipients[0].userId, '21')
     self.assertEqual(envelope.recipients[0].recipientId, '31')
     self.assertEqual(envelope.recipients[0].email, '*****@*****.**')
     self.assertEqual(envelope.recipients[0].name, 'Jean')
     self.assertEqual(envelope.recipients[1].clientUserId, '2')
     self.assertEqual(envelope.recipients[1].routingOrder, 12)
     self.assertEqual(envelope.recipients[1].userId, '22')
     self.assertEqual(envelope.recipients[1].recipientId, '32')
     self.assertEqual(envelope.recipients[1].email,
                      '*****@*****.**')
     self.assertEqual(envelope.recipients[1].name, 'Paul English')
Esempio n. 14
0
 def test_timeout(self):
     """DocuSignClient with (too small) timeout raises exception."""
     docusign = pydocusign.DocuSignClient(timeout=0.001)
     self.assertRaises(pydocusign.exceptions.DocuSignException,
                       docusign.login_information)