Пример #1
0
 def test_get_response_headers_preflight_with_cache(self):
     cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400)
     assert_equal(cors.get_response_headers(preflight=True),
                  [('Access-Control-Allow-Origin', '*'),
                   ('Access-Control-Allow-Methods', 'GET, PUT'),
                   ('Access-Control-Allow-Headers', 'accept'),
                   ('Access-Control-Max-Age', '86400')])
Пример #2
0
 def test_post_add_artifacts_too_large(self, add_artifacts):
     def on_post(chunk, **kw):
         if len(chunk) > 1:
             e = pymongo.errors.InvalidDocument(
                 "BSON document too large (16906035 bytes) - the connected server supports BSON document sizes up to 16777216 bytes.")
             # ming injects a 2nd arg with the document, so we do too
             e.args = e.args + ("doc:  {'task_name': 'allura.tasks.index_tasks.add_artifacts', ........",)
             raise e
     add_artifacts.post.side_effect = on_post
     cmd = show_models.ReindexCommand('reindex')
     cmd.options, args = cmd.parser.parse_args([])
     cmd._post_add_artifacts(range(5))
     kw = {'update_solr': cmd.options.solr, 'update_refs': cmd.options.refs}
     expected = [
         call([0, 1, 2, 3, 4], **kw),
         call([0, 1], **kw),
         call([0], **kw),
         call([1], **kw),
         call([2, 3, 4], **kw),
         call([2], **kw),
         call([3, 4], **kw),
         call([3], **kw),
         call([4], **kw)
     ]
     assert_equal(expected, add_artifacts.post.call_args_list)
Пример #3
0
 def test_retry(self):
     exit_code = taskd.TaskCommand('task').run([
         test_config, 'retry',
         '--filter-name-prefix', 'allura.tasks.index_tasks.',
         '--filter-result-regex', 'pysolr',
     ])
     assert_equal(exit_code, 0)
Пример #4
0
    def test_cohort(self):
        expected = self.generate_data()
        plan = {
            'kronos_url': 'http://localhost:9191',
            'cohort': {
                'stream': CohortTestCase.EMAIL_STREAM,
                'start': CohortTestCase.START_DATETIME,
                'cohorts': len(CohortTestCase.EMAIL_WEEKS),
                'unit': DateUnit.WEEKS,
                'grouping_key': 'user'
            },
            'action': {
                'stream': CohortTestCase.FRONTPAGE_STREAM,
                'repetitions': CohortTestCase.ACTION_REPETITION_DAYS,
                'unit': DateUnit.DAYS,
                'grouping_key': 'user_id'
            }
        }
        metis_plan = cohort_queryplan(plan)
        events = self.query(metis_plan)
        cohort = cohort_response(plan, events)

        # Same set of cohorts.
        self.assertEqual(set(expected), set(cohort))
        # Action dates match for all cohorts.
        cohorts = expected.keys()
        for cohort_name in cohorts:
            self.assertEqual(set(expected[cohort_name]['action_dates']),
                             set(cohort[cohort_name]['action_dates']))
            assert_equal(dict(expected[cohort_name]['action_dates']),
                         dict(cohort[cohort_name]['action_dates']))
Пример #5
0
 def test_request_token_valid(self, Request, Server):
     M.OAuthConsumerToken.consumer = mock.Mock()
     user = M.User.by_username('test-user')
     consumer_token = M.OAuthConsumerToken(
         api_key='api_key',
         user_id=user._id,
     )
     ThreadLocalORMSession.flush_all()
     req = Request.from_request.return_value = {
         'oauth_consumer_key': 'api_key'
     }
     r = self.app.post('/rest/oauth/request_token', params={'key': 'value'})
     Request.from_request.assert_called_once_with(
         'POST',
         'http://localhost/rest/oauth/request_token',
         headers={
             'Host':
             'localhost:80',
             'Content-Type':
             'application/x-www-form-urlencoded; charset="utf-8"'
         },
         parameters={'key': 'value'},
         query_string='')
     Server().verify_request.assert_called_once_with(
         req, consumer_token.consumer, None)
     request_token = M.OAuthRequestToken.query.get(
         consumer_token_id=consumer_token._id)
     assert_is_not_none(request_token)
     assert_equal(r.body, request_token.to_string())
Пример #6
0
 def test_interactive(self, Request, Server):
     M.OAuthConsumerToken.consumer = mock.Mock()
     user = M.User.by_username('test-admin')
     consumer_token = M.OAuthConsumerToken(
         api_key='api_key',
         user_id=user._id,
         description='ctok_desc',
     )
     ThreadLocalORMSession.flush_all()
     req = Request.from_request.return_value = {
         'oauth_consumer_key': 'api_key',
         'oauth_callback': 'http://my.domain.com/callback',
     }
     r = self.app.post('/rest/oauth/request_token', params={})
     rtok = parse_qs(r.body)['oauth_token'][0]
     r = self.app.post('/rest/oauth/authorize',
                       params={'oauth_token': rtok})
     r = r.forms[0].submit('yes')
     assert r.location.startswith('http://my.domain.com/callback')
     pin = parse_qs(urlparse(r.location).query)['oauth_verifier'][0]
     #pin = r.html.find(text=re.compile('^PIN: ')).split()[1]
     req = Request.from_request.return_value = {
         'oauth_consumer_key': 'api_key',
         'oauth_token': rtok,
         'oauth_verifier': pin,
     }
     r = self.app.get('/rest/oauth/access_token')
     atok = parse_qs(r.body)
     assert_equal(len(atok['oauth_token']), 1)
     assert_equal(len(atok['oauth_token_secret']), 1)
Пример #7
0
    def test_verify(self, req):
        req.post.return_value.json.return_value = {
            'request_id': 'test-req-id',
            'status': '0',
        }
        data = json.dumps({
            'number': '1234567890',
            'api_key': 'test-api-key',
            'api_secret': 'test-api-secret',
            'brand': 'Very loooooooooong',
        }, sort_keys=True)
        headers = {'Content-Type': 'application/json'}

        resp = self.phone.verify('1234567890')
        expected = {'status': 'ok', 'request_id': 'test-req-id'}
        assert_equal(expected, resp)
        req.post.assert_called_once_with(
            'https://api.nexmo.com/verify/json',
            data=data,
            headers=headers)

        req.post.reset_mock()
        req.post.return_value.json.return_value = {
            'status': '3',
            'error_text': 'Something went wrong',
        }
        resp = self.phone.verify('1234567890')
        expected = {'status': 'error', 'error': 'Something went wrong'}
        assert_equal(expected, resp)
        req.post.assert_called_once_with(
            'https://api.nexmo.com/verify/json',
            data=data,
            headers=headers)
def _test_fixture_object(fixture_name):
    
    x = getattr(fixtures, fixture_name)
    ser = serializer_for_object(x)
    assert ser
    verifyObject(ISerializer, ser)

    s = ser.dumps(x)
    assert s

    x1 = ser.loads(s)
    assert x1

    # Compare flattened dicts
    
    d = x.to_dict(flat=True)
    d1 = x1.to_dict(flat=True)
    
    keys = set(d.keys())
    keys1 = set(d1.keys())

    assert keys == keys1
    for k in keys:
        assert d[k] == d1[k] 
    
    # Compare nested dicts

    d = x.to_dict(flat=False)
    d1 = x1.to_dict(flat=False)

    assert_equal(d, d1)
Пример #9
0
def test_load_yaml():

    data_test = ordereddict([('image', ordereddict([('repository', 'nextcloud'), ('tag', '15.0.2-apache'), ('pullPolicy', 'IfNotPresent')])), ('nameOverride', ''), ('fullnameOverride', ''), ('replicaCount', 1), ('ingress', ordereddict([('enabled', True), ('annotations', ordereddict())])), ('nextcloud', ordereddict([('host', 'nextcloud.corp.justin-tech.com'), ('username', 'admin'), ('password', 'changeme')])), ('internalDatabase', ordereddict([('enabled', True), ('name', 'nextcloud')])), ('externalDatabase', ordereddict([('enabled', False), ('host', None), ('user', 'VAULT:/secret/testdata/user'), ('password', 'VAULT:/secret/{environment}/testdata/password'), ('database', 'nextcloud')])), ('mariadb', ordereddict([('enabled', True), ('db', ordereddict([('name', 'nextcloud'), ('user', 'nextcloud'), ('password', 'changeme')])), ('persistence', ordereddict([('enabled', True), ('storageClass', 'nfs-client'), ('accessMode', 'ReadWriteOnce'), ('size', '8Gi')]))])), ('service', ordereddict([('type', 'ClusterIP'), ('port', 8080), ('loadBalancerIP', 'nil')])), ('persistence', ordereddict([('enabled', True), ('storageClass', 'nfs-client'), ('accessMode', 'ReadWriteOnce'), ('size', '8Gi')])), ('resources', ordereddict()), ('nodeSelector', ordereddict()), ('tolerations', []), ('affinity', ordereddict())])
    yaml_file = "./tests/test.yaml"
    data = vault.load_yaml(yaml_file)
    print(data)
    assert_equal(data, data_test)
Пример #10
0
 def test_html2text_escaping(self):
     ticket = self._make_ticket(self.test_issue)
     assert_equal(
         ticket.description,
         '*Originally created by:* [[email protected]](http://code.google.com/u/101557263855536553789/)\n'
         '*Originally owned by:* [[email protected]](http://code.google.com/u/101557263855536553789/)\n'
         '\n'
         'Test \\*Issue\\* for testing\n'
         '\n'
         '  1. Test List\n'
         '  2. Item\n'
         '\n'
         '\\*\\*Testing\\*\\*\n'
         '\n'
         ' \\* Test list 2\n'
         ' \\* Item\n'
         '\n'
         '\\# Test Section\n'
         '\n'
         '    p = source.test\\_issue.post\\(\\)\n'
         '    p.count = p.count \\*5 \\#\\* 6\n'
         '    if p.count > 5:\n'
         '        print "Not < 5 & \\!= 5"\n'
         '\n'
         'That\'s all')
Пример #11
0
 def test_claim_verify_oid_bad_provider2(self, Consumer):
     Consumer().begin.return_value = None
     result = self.app.get('/auth/claim_verify_oid', params=dict(
             provider='http://www.google.com/accounts/', username='******'),
                           status=302)
     flash = self.webflash(result)
     assert_equal(flash, '{"status": "error", "message": "No openid services found for <code>http://www.google.com/accounts/</code>"}')
Пример #12
0
 def test_interactive(self, Request, Server):
     M.OAuthConsumerToken.consumer = mock.Mock()
     user = M.User.by_username('test-admin')
     consumer_token = M.OAuthConsumerToken(
             api_key='api_key',
             user_id=user._id,
             description='ctok_desc',
         )
     ThreadLocalORMSession.flush_all()
     req = Request.from_request.return_value = {
             'oauth_consumer_key': 'api_key',
             'oauth_callback': 'http://my.domain.com/callback',
         }
     r = self.app.post('/rest/oauth/request_token', params={})
     rtok = parse_qs(r.body)['oauth_token'][0]
     r = self.app.post('/rest/oauth/authorize', params={'oauth_token':rtok})
     r = r.forms[0].submit('yes')
     assert r.location.startswith('http://my.domain.com/callback')
     pin = parse_qs(urlparse(r.location).query)['oauth_verifier'][0]
     #pin = r.html.find(text=re.compile('^PIN: ')).split()[1]
     req = Request.from_request.return_value = {
             'oauth_consumer_key': 'api_key',
             'oauth_token': rtok,
             'oauth_verifier': pin,
         }
     r = self.app.get('/rest/oauth/access_token')
     atok = parse_qs(r.body)
     assert_equal(len(atok['oauth_token']), 1)
     assert_equal(len(atok['oauth_token_secret']), 1)
Пример #13
0
 def test_claim_verify_oid_bad_provider(self, Consumer):
     Consumer().begin.side_effect = oid_helper.consumer.DiscoveryFailure('bad', mock.Mock('response'))
     result = self.app.get('/auth/claim_verify_oid', params=dict(
             provider='http://www.google.com/accounts/', username='******'),
                           status=302)
     flash = self.webflash(result)
     assert_equal(flash, '{"status": "error", "message": "bad"}')
Пример #14
0
 def test_del_artifacts(self, solr):
     old_shortlinks = M.Shortlink.query.find().count()
     artifacts = [_TestArtifact(_shorthand_id='ta_%s' % x)
                  for x in range(5)]
     M.artifact_orm_session.flush()
     arefs = [M.ArtifactReference.from_artifact(a) for a in artifacts]
     ref_ids = [r._id for r in arefs]
     M.artifact_orm_session.flush()
     index_tasks.add_artifacts(ref_ids)
     M.main_orm_session.flush()
     M.main_orm_session.clear()
     new_shortlinks = M.Shortlink.query.find().count()
     assert old_shortlinks + 5 == new_shortlinks, 'Shortlinks not created'
     assert solr.add.call_count == 1
     sort_key = operator.itemgetter('id')
     assert_equal(
         sorted(solr.add.call_args[0][0], key=sort_key),
         sorted([ref.artifact.solarize() for ref in arefs],
                key=sort_key))
     index_tasks.del_artifacts(ref_ids)
     M.main_orm_session.flush()
     M.main_orm_session.clear()
     new_shortlinks = M.Shortlink.query.find().count()
     assert old_shortlinks == new_shortlinks, 'Shortlinks not deleted'
     solr_query = 'id:({0})'.format(' || '.join(ref_ids))
     solr.delete.assert_called_once_with(q=solr_query)
 def test_parsing_new_style_config(self):
     s = """
     system {
         ntp {
             server 0.vyatta.pool.ntp.org
             server 1.vyatta.pool.ntp.org
             server us.pool.ntp.org {
                 prefer {
                 }
             }
             server 2.vyatta.pool.ntp.org
         }
         time-zone Europe/Moscow
         name-server 10.10.2.2
     }"""
     correct = {
         'system': {
             'ntp': {
                 'server': {
                     '0.vyatta.pool.ntp.org': {},
                     '1.vyatta.pool.ntp.org': {},
                     'us.pool.ntp.org': {
                         'prefer': {}
                     },
                     '2.vyatta.pool.ntp.org': {},
                 }
             },
             'time-zone': 'Europe/Moscow',
             'name-server': '10.10.2.2'
         }
     }
     rv = vparser.parse_conf(s)
     assert isinstance(rv, dict)
     assert_equal(correct, rv)
Пример #16
0
    def test_python_requests(self):
        """To make sure that python CPE suppression works (issue#131)."""
        extracted = os.path.join(
                        os.path.dirname(
                         os.path.abspath(__file__)), '..', 'data', 'pypi', 'requests-2.5.3')
        args = {'ecosystem': 'pypi', 'name': 'requests', 'version': '2.5.3'}
        flexmock(EPVCache).should_receive('get_extracted_source_tarball').and_return(extracted)
        task = CVEcheckerTask.create_test_instance(task_name='security_issues')
        results = task.execute(arguments=args)

        assert isinstance(results, dict)
        assert set(results.keys()) == {'details', 'status', 'summary'}
        assert results['status'] == 'success'
        assert results['summary'] == ['CVE-2015-2296']
        # http://www.cvedetails.com/version/180634/Python-requests-Requests-2.5.3.html
        expected_details = [{
            "cvss": {
                "score": 6.8,
                "vector": "AV:N/AC:M/Au:?/C:P/I:P/A:P"
            },
            "description": "The resolve_redirects function in sessions.py in requests 2.1.0 "
                           "through 2.5.3 allows remote attackers to conduct session fixation "
                           "attacks via a cookie without a host value in a redirect.",
            "id": "CVE-2015-2296",
            "references": [
                "https://warehouse.python.org/project/requests/2.6.0/",
                "https://github.com/kennethreitz/requests/commit/"
                "3bd8afbff29e50b38f889b2f688785a669b9aafc",
                "http://www.openwall.com/lists/oss-security/2015/03/14/4",
                "http://www.openwall.com/lists/oss-security/2015/03/15/1",
                "http://www.ubuntu.com/usn/USN-2531-1",
                "http://advisories.mageia.org/MGASA-2015-0120.html"
            ],
            "severity": "Medium"}]
        assert_equal(results.get('details'), expected_details)
Пример #17
0
    def test_python_mako(self):
        extracted = os.path.join(
                        os.path.dirname(
                         os.path.abspath(__file__)), '..', 'data', 'pypi', 'Mako-0.3.3')
        args = {'ecosystem': 'pypi', 'name': 'mako', 'version': '0.3.3'}
        flexmock(EPVCache).should_receive('get_extracted_source_tarball').and_return(extracted)
        task = CVEcheckerTask.create_test_instance(task_name='security_issues')
        results = task.execute(arguments=args)

        assert isinstance(results, dict)
        assert set(results.keys()) == {'details', 'status', 'summary'}
        assert results['status'] == 'success'
        assert results['summary'] == ['CVE-2010-2480']
        # http://www.cvedetails.com/version/94328/Makotemplates-Mako-0.3.3.html
        expected_details = [{
            "cvss": {
                "score": 4.3,
                "vector": "AV:N/AC:M/Au:?/C:?/I:P/A:?"
            },
            "description": "Mako before 0.3.4 relies on the cgi.escape function in the Python "
                           "standard library for cross-site scripting (XSS) protection, "
                           "which makes it easier for remote attackers to conduct XSS attacks via "
                           "vectors involving single-quote characters and a JavaScript onLoad "
                           "event handler for a BODY element.",
            "id": "CVE-2010-2480",
            "references": [
                "http://www.makotemplates.org/CHANGES",
                "http://bugs.python.org/issue9061",
                "http://lists.opensuse.org/opensuse-security-announce/2010-08/msg00001.html"
            ],
            "severity": "Medium"}]
        assert_equal(results.get('details'), expected_details)
Пример #18
0
    def test_npm_geddy(self):
        args = {'ecosystem': 'npm', 'name': 'geddy', 'version': '13.0.7'}
        task = CVEcheckerTask.create_test_instance(task_name='security_issues')
        results = task.execute(args)

        assert isinstance(results, dict)
        assert set(results.keys()) == {'details', 'status', 'summary'}
        assert results['status'] == 'success'
        assert results['summary'] == ['CVE-2015-5688']
        # http://www.cvedetails.com/version/186008/Geddyjs-Geddy-13.0.7.html
        expected_details = [{
            "cvss": {
                "score": 5.0,
                "vector": "AV:N/AC:L/Au:N/C:P/I:N/A:N"
            },
            "description": "Directory traversal vulnerability in lib/app/index.js in Geddy "
                           "before 13.0.8 for Node.js allows remote attackers "
                           "to read arbitrary files via a ..%2f (dot dot encoded slash) "
                           "in the PATH_INFO to the default URI.",
            "id": "CVE-2015-5688",
            "references": [
                "http://cve.mitre.org/cgi-bin/cvename.cgi?name=2015-5688",
                "http://www.cvedetails.com/cve-details.php?t=1&cve_id=CVE-2015-5688",
                "https://github.com/geddy/geddy/commit/2de63b68b3aa6c08848f261ace550a37959ef231",
                "https://github.com/geddy/geddy/issues/697",
                "https://github.com/geddy/geddy/pull/699",
                "https://github.com/geddy/geddy/releases/tag/v13.0.8",
                "https://nodesecurity.io/advisories/geddy-directory-traversal",
                "https://web.nvd.nist.gov/view/vuln/detail?vulnId=2015-5688"
            ],
            "severity": "medium"}]
        assert_equal(results.get('details'), expected_details)
Пример #19
0
    def _collect_samples(self, file):
        '''Read records into a hash keyed on 'Cruise', typically the CTD cast 
        name. The values of the hash are a list of sample_metadata (sm) hashes
        which are then checked for consistency. For SIMZ cruises the convention
        has been to conduct one net tow per CTD cast. If data differences 
        indicate that more than one tow has been done then raise an
        exception.
        '''
        cast_hash = defaultdict(lambda: [])
        with open(self.args.subsampleFile, encoding='latin-1') as f:
            for r in csv.DictReader(f):
                sm = OrderedDict()
                sm['name'] = r.get('Name', '')
                sm['depth'] = r.get('Depth [m]', '')
                sm['sampletype'] = r.get('Sample Type', '')
                sm['volume'] = r.get('Sample Volume [mL]', '')
                if not sm['volume']:
                    sm['volume'] = r.get('Sample Volume [m^3]', '')
                sm['filterdiameter'] = r.get('Filter Diameter [mm]', '')
                try:
                    sm['filterporesize'] = float(r.get('Filter Pore Size [um]'))
                except ValueError:
                    sm['filterporesize'] = float(r.get('Filter Pore Size [um]').split()[0])
                cast_hash[r.get('Cruise')].append(sm)

        # Ensure consistency of sample metadata following SIMZ convention
        cast_hash_consistent = OrderedDict()
        for cast,sm_list in sorted(cast_hash.items()):
            for sm_hash in sm_list[1:]:
                self.logger.debug('Checking consistency of record %s', sm_hash)
                assert_equal(sm_list[0], sm_hash)

            cast_hash_consistent[cast] = sm_list[0]
                    
        return cast_hash_consistent
Пример #20
0
 def test_some_criteria(self, paged_search):
     q = 'labels:testing && status:open'
     paged_search.return_value = dict(
         tickets=[
             TM.Ticket(ticket_num=5, summary='our test ticket'),
         ],
         sort='status',
         limit=2,
         count=1,
         page=0,
         q=q,
     )
     r = self.api_get('/rest/p/test/bugs/search',
                      q=q,
                      sort='status',
                      limit='2')
     assert_equal(r.status_int, 200)
     assert_equal(
         r.json, {
             'limit': 2,
             'q': q,
             'sort': 'status',
             'count': 1,
             'page': 0,
             'tickets': [
                 {
                     'summary': 'our test ticket',
                     'ticket_num': 5
                 },
             ]
         })
Пример #21
0
    def test_email_sender_to_headers(self):
        c.user = M.User.by_username('test-admin')
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendsimplemail(
                fromaddr=str(c.user._id),
                toaddr='*****@*****.**',
                text=u'This is a test',
                reply_to=g.noreply,
                subject=u'Test subject',
                sender=u'*****@*****.**',
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('Sender: [email protected]', body)
            assert_in('To: [email protected]', body)

            _client.reset_mock()
            mail_tasks.sendmail(
                fromaddr=str(c.user._id),
                destinations=[str(c.user._id)],
                text=u'This is a test',
                reply_to=u'*****@*****.**',
                subject=u'Test subject',
                sender=u'*****@*****.**',
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('Sender: [email protected]', body)
            assert_in('To: [email protected]', body)
Пример #22
0
 def test_parsing_new_style_config(self):
     s = """
     system {
         ntp {
             server 0.vyatta.pool.ntp.org
             server 1.vyatta.pool.ntp.org
             server us.pool.ntp.org {
                 prefer {
                 }
             }
             server 2.vyatta.pool.ntp.org
         }
         time-zone Europe/Moscow
         name-server 10.10.2.2
     }"""
     correct = {
         'system': {
             'ntp': {
                 'server': {
                     '0.vyatta.pool.ntp.org': {},
                     '1.vyatta.pool.ntp.org': {},
                     'us.pool.ntp.org': {
                         'prefer': {}
                     },
                     '2.vyatta.pool.ntp.org': {},
                 }
             },
             'time-zone': 'Europe/Moscow',
             'name-server': '10.10.2.2'
         }
     }
     rv = vparser.parse_conf(s)
     assert isinstance(rv, dict)
     assert_equal(correct, rv)
Пример #23
0
    def test_email_references_header(self):
        c.user = M.User.by_username('test-admin')
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendsimplemail(fromaddr=str(c.user._id),
                                      toaddr='*****@*****.**',
                                      text=u'This is a test',
                                      reply_to=g.noreply,
                                      subject=u'Test subject',
                                      references=['a', 'b', 'c'],
                                      message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('References: <a> <b> <c>', body)

            _client.reset_mock()
            mail_tasks.sendmail(fromaddr=str(c.user._id),
                                destinations=[str(c.user._id)],
                                text=u'This is a test',
                                reply_to=g.noreply,
                                subject=u'Test subject',
                                references=u'ref',
                                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('References: <ref>', body)
Пример #24
0
    def _collect_samples(self, file):
        """Read records into a hash keyed on 'Cruise', typically the CTD cast 
        name. The values of the hash are a list of sample_metadata (sm) hashes
        which are then checked for consistency. For SIMZ cruises the convention
        has been to conduct one net tow per CTD cast. If data differences 
        indicate that more than one tow has been done then raise an
        exception.
        """
        cast_hash = defaultdict(lambda: [])
        with open(self.args.subsampleFile) as f:
            for r in csv.DictReader(f):
                sm = OrderedDict()
                sm["name"] = r.get("Name", "")
                sm["depth"] = r.get("Depth [m]", "")
                sm["sampletype"] = r.get("Sample Type", "")
                sm["volume"] = r.get("Sample Volume [mL]", "")
                if not sm["volume"]:
                    sm["volume"] = r.get("Sample Volume [m^3]", "")
                sm["filterdiameter"] = r.get("Filter Diameter [mm]", "")
                try:
                    sm["filterporesize"] = float(r.get("Filter Pore Size [um]"))
                except ValueError:
                    sm["filterporesize"] = float(r.get("Filter Pore Size [um]").split()[0])
                cast_hash[r.get("Cruise")].append(sm)

        # Ensure consistency of sample metadata following SIMZ convention
        cast_hash_consistent = OrderedDict()
        for cast, sm_list in sorted(cast_hash.items()):
            for sm_hash in sm_list[1:]:
                self.logger.debug("Checking consistency of record %s", sm_hash)
                assert_equal(sm_list[0], sm_hash)

            cast_hash_consistent[cast] = sm_list[0]

        return cast_hash_consistent
Пример #25
0
 def test_del_artifacts(self, solr):
     old_shortlinks = M.Shortlink.query.find().count()
     artifacts = [
         _TestArtifact(_shorthand_id='ta_%s' % x) for x in range(5)
     ]
     M.artifact_orm_session.flush()
     arefs = [M.ArtifactReference.from_artifact(a) for a in artifacts]
     ref_ids = [r._id for r in arefs]
     M.artifact_orm_session.flush()
     index_tasks.add_artifacts(ref_ids)
     M.main_orm_session.flush()
     M.main_orm_session.clear()
     new_shortlinks = M.Shortlink.query.find().count()
     assert old_shortlinks + 5 == new_shortlinks, 'Shortlinks not created'
     assert solr.add.call_count == 1
     sort_key = operator.itemgetter('id')
     assert_equal(
         sorted(solr.add.call_args[0][0], key=sort_key),
         sorted([ref.artifact.solarize() for ref in arefs], key=sort_key))
     index_tasks.del_artifacts(ref_ids)
     M.main_orm_session.flush()
     M.main_orm_session.clear()
     new_shortlinks = M.Shortlink.query.find().count()
     assert old_shortlinks == new_shortlinks, 'Shortlinks not deleted'
     solr_query = 'id:({0})'.format(' || '.join(ref_ids))
     solr.delete.assert_called_once_with(q=solr_query)
Пример #26
0
    def test_sendsimplemail_with_disabled_user(self):
        c.user = M.User.by_username('test-admin')
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendsimplemail(fromaddr=str(c.user._id),
                                      toaddr='*****@*****.**',
                                      text=u'This is a test',
                                      reply_to=g.noreply,
                                      subject=u'Test subject',
                                      message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)

            c.user.disabled = True
            ThreadLocalORMSession.flush_all()
            mail_tasks.sendsimplemail(fromaddr=str(c.user._id),
                                      toaddr='*****@*****.**',
                                      text=u'This is a test',
                                      reply_to=g.noreply,
                                      subject=u'Test subject',
                                      message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 2)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: %s' % g.noreply, body)
    def test_maven_commons_compress(self):
        """Tests CVE reports for selected packages from Maven ecosystem."""
        args = {
            'ecosystem': 'maven',
            'name': 'org.apache.commons:commons-compress',
            'version': '1.4'
        }
        task = CVEcheckerTask.create_test_instance(task_name='security_issues')
        results = task.execute(arguments=args)

        assert isinstance(results, dict)
        assert set(results.keys()) == {'details', 'status', 'summary'}
        expected_details = [{
            "attribution":
            "https://github.com/victims/victims-cve-db, CC BY-SA 4.0, modified",
            "cvss": {
                "score": 5.0,
                "vector": "AV:N/AC:L/Au:N/C:N/I:N/A:P"
            },
            "description":
            "Algorithmic complexity vulnerability in the sorting algorithms "
            "in bzip2 compressing stream (BZip2CompressorOutputStream) "
            "in Apache Commons Compress before 1.4.1 allows remote attackers "
            "to cause a denial of service (CPU consumption) via a file "
            "with many repeating inputs.\n",
            "id":
            "CVE-2012-2098",
            "references": ["https://nvd.nist.gov/vuln/detail/CVE-2012-2098"],
            "severity":
            "medium"
        }]
        assert_equal(results.get('details'), expected_details,
                     results.get('details'))
Пример #28
0
 def test_get_issue_basic_fields(self):
     test_issue = open(pkg_resources.resource_filename('forgeimporters', 'tests/data/google/test-issue.html')).read()
     gpe = self._make_extractor(test_issue)
     self.assertEqual(gpe.get_issue_creator().name, '*****@*****.**')
     self.assertEqual(gpe.get_issue_creator().url, 'http://code.google.com/u/101557263855536553789/')
     self.assertEqual(gpe.get_issue_owner().name, '*****@*****.**')
     self.assertEqual(gpe.get_issue_owner().url, 'http://code.google.com/u/101557263855536553789/')
     self.assertEqual(gpe.get_issue_status(), 'Started')
     self._p_soup.stop()
     self.assertEqual(gpe.get_issue_summary(), 'Test "Issue"')
     assert_equal(gpe.get_issue_description(),
             'Test *Issue* for testing\n'
             '\n'
             '  1. Test List\n'
             '  2. Item\n'
             '\n'
             '**Testing**\n'
             '\n'
             ' * Test list 2\n'
             ' * Item\n'
             '\n'
             '# Test Section\n'
             '\n'
             '    p = source.test_issue.post()\n'
             '    p.count = p.count *5 #* 6\n'
             '    if p.count &gt; 5:\n'
             '        print "Not &lt; 5 &amp; != 5"\n'
             '\n'
             'That\'s all'
         )
     self.assertEqual(gpe.get_issue_created_date(), 'Thu Aug  8 15:33:52 2013')
     self.assertEqual(gpe.get_issue_stars(), 1)
Пример #29
0
    def test_verify(self, req):
        req.post.return_value.json.return_value = {
            'request_id': 'test-req-id',
            'status': '0',
        }
        data = json.dumps(
            {
                'number': '1234567890',
                'api_key': 'test-api-key',
                'api_secret': 'test-api-secret',
                'brand': 'Very loooooooooong',
            },
            sort_keys=True)
        headers = {'Content-Type': 'application/json'}

        resp = self.phone.verify('1234567890')
        expected = {'status': 'ok', 'request_id': 'test-req-id'}
        assert_equal(expected, resp)
        req.post.assert_called_once_with('https://api.nexmo.com/verify/json',
                                         data=data,
                                         headers=headers)

        req.post.reset_mock()
        req.post.return_value.json.return_value = {
            'status': '3',
            'error_text': 'Something went wrong',
        }
        resp = self.phone.verify('1234567890')
        expected = {'status': 'error', 'error': 'Something went wrong'}
        assert_equal(expected, resp)
        req.post.assert_called_once_with('https://api.nexmo.com/verify/json',
                                         data=data,
                                         headers=headers)
Пример #30
0
    def test_error(self):
        res = self.phone.error()
        expected = {'status': 'error',
                    'error': 'Failed sending request to Nexmo'}
        assert_equal(expected, res)
        # not allowed code
        res = self.phone.error(code='2', msg='text')
        assert_equal(expected, res)
        # allowed code
        res = self.phone.error(code='15', msg='text')
        expected = {'status': 'error', 'error': 'text'}
        assert_equal(expected, res)

        # invalid format, possibly US
        res = self.phone.error(code='3', msg='Invalid value for parameter: number', number='8005551234')
        assert_equal(res['status'], 'error')
        assert_in('Invalid value for parameter: number', res['error'])
        assert_in('country code', res['error'])
        assert_in('US', res['error'])

        # invalid format, not US
        res = self.phone.error(code='3', msg='Invalid value for parameter: number', number='738005551234')
        assert_equal(res['status'], 'error')
        assert_in('Invalid value for parameter: number', res['error'])
        assert_in('country code', res['error'])
        assert_not_in('US', res['error'])
Пример #31
0
 def test_list_repos(self):
     r = self.app.get('/auth/repo_permissions',
                      params=dict(username='******'),
                      status=200)
     assert_equal(json.loads(r.text), {"allow_write": [
         '/svn/test/src',
     ]})
Пример #32
0
    def test_error(self):
        res = self.phone.error()
        expected = {
            'status': 'error',
            'error': 'Failed sending request to Nexmo'
        }
        assert_equal(expected, res)
        # not allowed code
        res = self.phone.error(code='2', msg='text')
        assert_equal(expected, res)
        # allowed code
        res = self.phone.error(code='15', msg='text')
        expected = {'status': 'error', 'error': 'text'}
        assert_equal(expected, res)

        # invalid format, possibly US
        res = self.phone.error(code='3',
                               msg='Invalid value for parameter: number',
                               number='8005551234')
        assert_equal(res['status'], 'error')
        assert_in('Invalid value for parameter: number', res['error'])
        assert_in('country code', res['error'])
        assert_in('US', res['error'])

        # invalid format, not US
        res = self.phone.error(code='3',
                               msg='Invalid value for parameter: number',
                               number='738005551234')
        assert_equal(res['status'], 'error')
        assert_in('Invalid value for parameter: number', res['error'])
        assert_in('country code', res['error'])
        assert_not_in('US', res['error'])
Пример #33
0
    def test_post_add_artifacts_too_large(self, add_artifacts):
        def on_post(chunk, **kw):
            if len(chunk) > 1:
                e = pymongo.errors.InvalidDocument(
                    "BSON document too large (16906035 bytes) - the connected server supports BSON document sizes up to 16777216 bytes."
                )
                # ming injects a 2nd arg with the document, so we do too
                e.args = e.args + (
                    "doc:  {'task_name': 'allura.tasks.index_tasks.add_artifacts', ........",
                )
                raise e

        add_artifacts.post.side_effect = on_post
        cmd = show_models.ReindexCommand('reindex')
        cmd.options, args = cmd.parser.parse_args([])
        cmd._post_add_artifacts(range(5))
        kw = {'update_solr': cmd.options.solr, 'update_refs': cmd.options.refs}
        expected = [
            call([0, 1, 2, 3, 4], **kw),
            call([0, 1], **kw),
            call([0], **kw),
            call([1], **kw),
            call([2, 3, 4], **kw),
            call([2], **kw),
            call([3, 4], **kw),
            call([3], **kw),
            call([4], **kw)
        ]
        assert_equal(expected, add_artifacts.post.call_args_list)
Пример #34
0
 def test_solr_hosts_1(self, Solr):
     cmd = show_models.ReindexCommand('reindex')
     cmd.options, args = cmd.parser.parse_args([
         '-p', 'test', '--solr', '--solr-hosts=http://blah.com/solr/forge'
     ])
     cmd._chunked_add_artifacts(list(range(10)))
     assert_equal(Solr.call_args[0][0], 'http://blah.com/solr/forge')
Пример #35
0
 def test_get_response_headers_preflight_with_cache(self):
     cors = CORSMiddleware(self.app, ['GET', 'PUT'], ['Accept'], 86400)
     assert_equal(cors.get_response_headers(preflight=True),
                  [('Access-Control-Allow-Origin', '*'),
                   ('Access-Control-Allow-Methods', 'GET, PUT'),
                   ('Access-Control-Allow-Headers', 'accept'),
                   ('Access-Control-Max-Age', '86400')])
Пример #36
0
 def test_create_export_dir(self):
     project = M.Project.query.get(shortname='test')
     export_path = project.bulk_export_path()
     export_filename = project.bulk_export_filename()
     path = export_tasks.create_export_dir(project, export_filename)
     assert_equal(path, '/tmp/bulk_export/p/test/test')
     assert os.path.exists(os.path.join(export_path, project.shortname))
Пример #37
0
    def test_message_serialization(self):
        msg_id = rand_string()
        creation_time_utc = rand_date_utc()
        expire_at_utc = rand_date_utc()
        producer = rand_string()
        topic = rand_string()

        actual = self._get_object(
            Message, {
                'msg_id': msg_id,
                'creation_time_utc': creation_time_utc,
                'expire_at_utc': expire_at_utc,
                'producer': producer,
                'topic': topic,
            })

        expected = {
            'mime_type': PUB_SUB.DEFAULT_MIME_TYPE,
            'msg_id': msg_id,
            'topic': topic,
            'expiration': PUB_SUB.DEFAULT_EXPIRATION,
            'producer': producer,
            'creation_time_utc': creation_time_utc.isoformat(),
            'priority': PUB_SUB.DEFAULT_PRIORITY,
            'expire_at_utc': expire_at_utc.isoformat()
        }

        # Dicts must be equal ..
        assert_equal(actual.to_dict(), expected)

        # .. as well as JSON.
        json = actual.to_json()
        self.assertIsInstance(json, str)
        unjsonified = loads(json)
        assert_equal(unjsonified, expected)
Пример #38
0
    def test_email_references_header(self):
        c.user = M.User.by_username('test-admin')
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendsimplemail(
                fromaddr=str(c.user._id),
                toaddr='*****@*****.**',
                text=u'This is a test',
                reply_to=g.noreply,
                subject=u'Test subject',
                references=['a', 'b', 'c'],
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('References: <a> <b> <c>', body)

            _client.reset_mock()
            mail_tasks.sendmail(
                fromaddr=str(c.user._id),
                destinations=[str(c.user._id)],
                text=u'This is a test',
                reply_to=g.noreply,
                subject=u'Test subject',
                references=u'ref',
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('References: <ref>', body)
Пример #39
0
 def test_webhooks_list(self):
     r = self.api_get(self.url)
     webhooks = [{
         '_id':
         unicode(wh._id),
         'url':
         'http://localhost/rest/adobe/adobe-1/admin'
         '/src/webhooks/repo-push/{}'.format(wh._id),
         'type':
         'repo-push',
         'hook_url':
         'http://httpbin.org/post/{}'.format(n),
         'mod_date':
         unicode(wh.mod_date),
     } for n, wh in enumerate(self.webhooks)]
     expected = {
         'webhooks': webhooks,
         'limits': {
             'repo-push': {
                 'max': 3,
                 'used': 3
             }
         },
     }
     dd.assert_equal(r.json, expected)
Пример #40
0
    def test_message_serialization(self):
        msg_id = rand_string()
        creation_time_utc = rand_date_utc()
        expire_at_utc = rand_date_utc()
        producer = rand_string()
        topic = rand_string()

        actual = self._get_object(Message, {
            'msg_id': msg_id,
            'creation_time_utc': creation_time_utc,
            'expire_at_utc': expire_at_utc,
            'producer': producer,
            'topic':topic,
        })

        expected = {
            'mime_type': PUB_SUB.DEFAULT_MIME_TYPE,
            'msg_id': msg_id,
            'topic': topic,
            'expiration': PUB_SUB.DEFAULT_EXPIRATION,
            'producer': producer,
            'creation_time_utc': creation_time_utc.isoformat(),
            'priority': PUB_SUB.DEFAULT_PRIORITY,
            'expire_at_utc': expire_at_utc.isoformat()
        }

        # Dicts must be equal ..
        assert_equal(actual.to_dict(), expected)

        # .. as well as JSON.
        json = actual.to_json()
        self.assertIsInstance(json, str)
        unjsonified = loads(json)
        assert_equal(unjsonified, expected)
Пример #41
0
 def test_create(self):
     assert_equal(M.Webhook.query.find().count(), len(self.webhooks))
     data = {u'url': u'http://hook.slack.com/abcd'}
     limit = json.dumps({'git': 10})
     with h.push_config(config, **{'webhook.repo_push.max_hooks': limit}):
         msg = 'add webhook repo-push {} {}'.format(data['url'],
                                                    self.git.config.url())
         with td.audits(msg):
             r = self.api_post(self.url + '/repo-push', status=201, **data)
     webhook = M.Webhook.query.get(hook_url=data['url'])
     assert_equal(webhook.secret, 'super-secret')  # secret generated
     expected = {
         '_id':
         unicode(webhook._id),
         'url':
         'http://localhost/rest/adobe/adobe-1/admin'
         '/src/webhooks/repo-push/{}'.format(webhook._id),
         'type':
         'repo-push',
         'hook_url':
         data['url'],
         'mod_date':
         unicode(webhook.mod_date),
     }
     dd.assert_equal(r.json, expected)
     assert_equal(M.Webhook.query.find().count(), len(self.webhooks) + 1)
Пример #42
0
    def test_add_artifacts(self):
        from allura.lib.search import find_shortlinks
        with mock.patch('allura.lib.search.find_shortlinks') as find_slinks:
            find_slinks.side_effect = lambda s: find_shortlinks(s)

            old_shortlinks = M.Shortlink.query.find().count()
            old_solr_size = len(g.solr.db)
            artifacts = [_TestArtifact() for x in range(5)]
            for i, a in enumerate(artifacts):
                a._shorthand_id = 't%d' % i
                a.text = 'This is a reference to [t3]'
            arefs = [M.ArtifactReference.from_artifact(a) for a in artifacts]
            ref_ids = [r._id for r in arefs]
            M.artifact_orm_session.flush()
            index_tasks.add_artifacts(ref_ids)
            new_shortlinks = M.Shortlink.query.find().count()
            new_solr_size = len(g.solr.db)
            assert old_shortlinks + \
                5 == new_shortlinks, 'Shortlinks not created'
            assert old_solr_size + \
                5 == new_solr_size, "Solr additions didn't happen"
            M.main_orm_session.flush()
            M.main_orm_session.clear()
            t3 = _TestArtifact.query.get(_shorthand_id='t3')
            assert len(t3.backrefs) == 5, t3.backrefs
            assert_equal(find_slinks.call_args_list,
                         [mock.call(a.index().get('text')) for a in artifacts])
Пример #43
0
    def test_add_artifacts(self):
        from allura.lib.search import find_shortlinks
        with mock.patch('allura.lib.search.find_shortlinks') as find_slinks:
            find_slinks.side_effect = lambda s: find_shortlinks(s)

            old_shortlinks = M.Shortlink.query.find().count()
            old_solr_size = len(g.solr.db)
            artifacts = [_TestArtifact() for x in range(5)]
            for i, a in enumerate(artifacts):
                a._shorthand_id = 't%d' % i
                a.text = 'This is a reference to [t3]'
            arefs = [M.ArtifactReference.from_artifact(a) for a in artifacts]
            ref_ids = [r._id for r in arefs]
            M.artifact_orm_session.flush()
            index_tasks.add_artifacts(ref_ids)
            new_shortlinks = M.Shortlink.query.find().count()
            new_solr_size = len(g.solr.db)
            assert old_shortlinks + \
                5 == new_shortlinks, 'Shortlinks not created'
            assert old_solr_size + \
                5 == new_solr_size, "Solr additions didn't happen"
            M.main_orm_session.flush()
            M.main_orm_session.clear()
            t3 = _TestArtifact.query.get(_shorthand_id='t3')
            assert len(t3.backrefs) == 5, t3.backrefs
            assert_equal(find_slinks.call_args_list,
                         [mock.call(a.index().get('text')) for a in artifacts])
Пример #44
0
    def test_send_email_nonascii(self):
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendmail(fromaddr=u'"По" <*****@*****.**>',
                                destinations=['*****@*****.**'],
                                text=u'Громады стройные теснятся',
                                reply_to=g.noreply,
                                subject=u'По оживлённым берегам',
                                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')

            assert_equal(rcpts, ['*****@*****.**'])
            assert_in('Reply-To: %s' % g.noreply, body)

            # The address portion must not be encoded, only the name portion can be.
            # Also it is apparently not necessary to have the double-quote separators present
            # when the name portion is encoded.  That is, the encoding below is
            # just По and not "По"
            assert_in('From: =?utf-8?b?0J/Qvg==?= <*****@*****.**>', body)
            assert_in(
                'Subject: =?utf-8?b?0J/QviDQvtC20LjQstC70ZHQvdC90YvQvCDQsdC10YDQtdCz0LDQvA==?=',
                body)
            assert_in('Content-Type: text/plain; charset="utf-8"', body)
            assert_in('Content-Transfer-Encoding: base64', body)
            assert_in(b64encode(u'Громады стройные теснятся'.encode('utf-8')),
                      body)
Пример #45
0
  def test_cohort(self):
    expected = self.generate_data()
    plan = {
      'source': 'kronos',
      'cohort': {'stream': CohortTestCase.EMAIL_STREAM,
                 'start': CohortTestCase.START_DATETIME,
                 'cohorts': len(CohortTestCase.EMAIL_WEEKS),
                 'unit': DateUnit.WEEKS,
                 'grouping_key': 'user'},
      'action': {'stream': CohortTestCase.FRONTPAGE_STREAM,
                 'repetitions': CohortTestCase.ACTION_REPETITION_DAYS,
                 'unit': DateUnit.DAYS,
                 'grouping_key': 'user_id'}
    }
    metis_plan = cohort_queryplan(plan)
    events = self.query(metis_plan)
    cohort = cohort_response(plan, events)

    # Same set of cohorts.
    self.assertEqual(set(expected), set(cohort))
    # Action dates match for all cohorts.
    cohorts = expected.keys()
    for cohort_name in cohorts:
      self.assertEqual(set(expected[cohort_name]['action_dates']),
                       set(cohort[cohort_name]['action_dates']))
      assert_equal(dict(expected[cohort_name]['action_dates']),
                   dict(cohort[cohort_name]['action_dates']))
Пример #46
0
    def test_email_sender_to_headers(self):
        c.user = M.User.by_username('test-admin')
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendsimplemail(fromaddr=str(c.user._id),
                                      toaddr='*****@*****.**',
                                      text=u'This is a test',
                                      reply_to=g.noreply,
                                      subject=u'Test subject',
                                      sender=u'*****@*****.**',
                                      message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('Sender: [email protected]', body)
            assert_in('To: [email protected]', body)

            _client.reset_mock()
            mail_tasks.sendmail(fromaddr=str(c.user._id),
                                destinations=[str(c.user._id)],
                                text=u'This is a test',
                                reply_to=u'*****@*****.**',
                                subject=u'Test subject',
                                sender=u'*****@*****.**',
                                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)
            assert_in('Sender: [email protected]', body)
            assert_in('To: [email protected]', body)
Пример #47
0
    def test_send_email_nonascii(self):
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendmail(
                fromaddr=u'"По" <*****@*****.**>',
                destinations=['*****@*****.**'],
                text=u'Громады стройные теснятся',
                reply_to=g.noreply,
                subject=u'По оживлённым берегам',
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')

            assert_equal(rcpts, ['*****@*****.**'])
            assert_in('Reply-To: %s' % g.noreply, body)

            # The address portion must not be encoded, only the name portion can be.
            # Also it is apparently not necessary to have the double-quote separators present
            # when the name portion is encoded.  That is, the encoding below is
            # just По and not "По"
            assert_in('From: =?utf-8?b?0J/Qvg==?= <*****@*****.**>', body)
            assert_in(
                'Subject: =?utf-8?b?0J/QviDQvtC20LjQstC70ZHQvdC90YvQvCDQsdC10YDQtdCz0LDQvA==?=', body)
            assert_in('Content-Type: text/plain; charset="utf-8"', body)
            assert_in('Content-Transfer-Encoding: base64', body)
            assert_in(
                b64encode(u'Громады стройные теснятся'.encode('utf-8')), body)
Пример #48
0
 def test_get_issue_basic_fields_html2text(self):
     test_issue = open(pkg_resources.resource_filename('forgeimporters', 'tests/data/google/test-issue.html')).read()
     gpe = self._make_extractor(test_issue)
     self.assertEqual(gpe.get_issue_creator().name, '*****@*****.**')
     self.assertEqual(gpe.get_issue_creator().url, 'http://code.google.com/u/101557263855536553789/')
     self.assertEqual(gpe.get_issue_owner().name, '*****@*****.**')
     self.assertEqual(gpe.get_issue_owner().url, 'http://code.google.com/u/101557263855536553789/')
     self.assertEqual(gpe.get_issue_status(), 'Started')
     self._p_soup.stop()
     self.assertEqual(gpe.get_issue_summary(), 'Test "Issue"')
     assert_equal(gpe.get_issue_description(),
             'Test \\*Issue\\* for testing\n'
             '\n'
             '&nbsp; 1. Test List\n'
             '&nbsp; 2. Item\n'
             '\n'
             '\\*\\*Testing\\*\\*\n'
             '\n'
             ' \\* Test list 2\n'
             ' \\* Item\n'
             '\n'
             '\\# Test Section\n'
             '\n'
             '&nbsp;&nbsp;&nbsp; p = source.test\\_issue.post\\(\\)\n'
             '&nbsp;&nbsp;&nbsp; p.count = p.count \\*5 \\#\\* 6\n'
             '&nbsp;&nbsp;&nbsp; if p.count &gt; 5:\n'
             '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "Not &lt; 5 &amp; \\!= 5"\n'
             '\n'
             'References: [issue 1](#1), [r2]\n'
             '\n'
             'That\'s all'
         )
     self.assertEqual(gpe.get_issue_created_date(), 'Thu Aug  8 15:33:52 2013')
     self.assertEqual(gpe.get_issue_stars(), 1)
Пример #49
0
    def test_sendsimplemail_with_disabled_user(self):
        c.user = M.User.by_username('test-admin')
        with mock.patch.object(mail_tasks.smtp_client, '_client') as _client:
            mail_tasks.sendsimplemail(
                fromaddr=str(c.user._id),
                toaddr='*****@*****.**',
                text=u'This is a test',
                reply_to=g.noreply,
                subject=u'Test subject',
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 1)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: "Test Admin" <*****@*****.**>', body)

            c.user.disabled = True
            ThreadLocalORMSession.flush_all()
            mail_tasks.sendsimplemail(
                fromaddr=str(c.user._id),
                toaddr='*****@*****.**',
                text=u'This is a test',
                reply_to=g.noreply,
                subject=u'Test subject',
                message_id=h.gen_message_id())
            assert_equal(_client.sendmail.call_count, 2)
            return_path, rcpts, body = _client.sendmail.call_args[0]
            body = body.split('\n')
            assert_in('From: %s' % g.noreply, body)
Пример #50
0
 def test_html2text_escaping(self):
     ticket = self._make_ticket(self.test_issue)
     assert_equal(
         ticket.description,
         "*Originally created by:* [[email protected]](http://code.google.com/u/101557263855536553789/)\n"
         "*Originally owned by:* [[email protected]](http://code.google.com/u/101557263855536553789/)\n"
         "\n"
         "Test \\*Issue\\* for testing\n"
         "\n"
         "&nbsp; 1. Test List\n"
         "&nbsp; 2. Item\n"
         "\n"
         "\\*\\*Testing\\*\\*\n"
         "\n"
         " \\* Test list 2\n"
         " \\* Item\n"
         "\n"
         "\\# Test Section\n"
         "\n"
         "&nbsp;&nbsp;&nbsp; p = source.test\\_issue.post\\(\\)\n"
         "&nbsp;&nbsp;&nbsp; p.count = p.count \\*5 \\#\\* 6\n"
         "&nbsp;&nbsp;&nbsp; if p.count &gt; 5:\n"
         '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print "Not &lt; 5 &amp; \\!= 5"\n'
         "\n"
         "References: [issue 1](#1), [r2]\n"
         "\n"
         "That's all",
     )
def _test_fixture_object(fixture_name):

    x = getattr(fixtures, fixture_name)
    ser = serializer_for_object(x)
    assert ser
    verifyObject(ISerializer, ser)

    s = ser.dumps(x)
    assert s

    x1 = ser.loads(s)
    assert x1

    # Compare flattened dicts

    d = x.to_dict(flat=True)
    d1 = x1.to_dict(flat=True)

    keys = set(d.keys())
    keys1 = set(d1.keys())

    assert keys == keys1
    for k in keys:
        assert d[k] == d1[k]

    # Compare nested dicts

    d = x.to_dict(flat=False)
    d1 = x1.to_dict(flat=False)

    assert_equal(d, d1)
Пример #52
0
 def test_claim_verify_oid_good_provider_no_redirect(self, Consumer):
     Consumer().begin().shouldSendRedirect.return_value = False
     Consumer().begin().formMarkup.return_value = "<!-- I'm a mock object! -->"
     result = self.app.get('/auth/claim_verify_oid', params=dict(
             provider='http://www.google.com/accounts/o8/id', username='******'),
             status=200)
     flash = self.webflash(result)
     assert_equal(flash, '')
Пример #53
0
 def test_invalid_args(self):
     M.MonQTask.query.remove()
     show_models.ReindexCommand.post('--invalid-option')
     with td.raises(Exception):
         M.MonQTask.run_ready()
     task = M.MonQTask.query.get(task_name=self.task_name)
     assert_equal(task.state, 'error')
     assert_in('Error parsing args', task.result)
Пример #54
0
 def test_merge(self, MR, session):
     mr = mock.Mock(_id='_id')
     MR.query.get.return_value = mr
     repo_tasks.merge(mr._id)
     mr.app.repo.merge.assert_called_once_with(mr)
     assert_equal(mr.status, 'merged')
     session.assert_called_once_with(mr)
     session.return_value.flush.assert_called_once_with(mr)
def _test_copying(x):

    o1 = getattr(fixtures, x)
    d1 = o1.to_dict()
    o2 = copy.deepcopy(o1)    
    d2 = o2.to_dict()

    assert_equal(d1, d2) 
Пример #56
0
 def test_ticket_index_noauth(self):
     tickets = self.api_get('/rest/p/test/bugs', user='******')
     assert 'TicketMonitoringEmail' not in tickets.json[
         'tracker_config']['options']
     # make sure it didn't get removed from the db too
     ticket_config = M.AppConfig.query.get(
         project_id=c.project._id, tool_name='tickets')
     assert_equal(ticket_config.options.get('TicketMonitoringEmail'),
                  'test@localhost')
Пример #57
0
    def test_move_ticket_redirect(self):
        p = M.Project.query.get(shortname='test')
        dummy_tracker = p.app_instance('dummy')
        r = self.app.post(
            '/p/test/bugs/1/move',
            params={'tracker': str(dummy_tracker.config._id)}).follow()

        ticket = self.api_get('/rest/p/test/bugs/1/')
        assert_equal(ticket.request.path, '/rest/p/test/dummy/1/')
Пример #58
0
 def test_merge(self, MR, session):
     mr = mock.Mock(_id='_id',
                    activity_name='merge req', activity_url='/fake/url', activity_extras={}, node_id=None)
     MR.query.get.return_value = mr
     repo_tasks.merge(mr._id)
     mr.app.repo.merge.assert_called_once_with(mr)
     assert_equal(mr.status, 'merged')
     session.assert_called_once_with(mr)
     session.return_value.flush.assert_called_once_with(mr)
Пример #59
0
 def test_no_criteria(self, paged_search):
     paged_search.return_value = dict(tickets=[
         TM.Ticket(ticket_num=5, summary='our test ticket'),
     ])
     r = self.api_get('/rest/p/test/bugs/search')
     assert_equal(r.status_int, 200)
     assert_equal(r.json, {'tickets':[
         {'summary': 'our test ticket', 'ticket_num': 5},
     ]})