def test_get_backend(self): backend = get_backend(( 'social.backends.github.GithubOAuth2', 'social.backends.facebook.FacebookOAuth2', 'social.backends.flickr.FlickrOAuth' ), 'github') expect(backend).to.equal(GithubOAuth2)
def test_find_archive_with_unknown_properties(self): archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71') httpretty.register_uri(httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format(self.api_key, archive_id), body=textwrap.dedent(u("""\ { "createdAt" : 1395187836000, "duration" : 62, "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 8347554, "status" : "expired", "url" : null, "hasAudio": true, "hasVideo": true, "notarealproperty" : "not a real value" }""")), status=200, content_type=u('application/json')) archive = self.opentok.get_archive(archive_id) expect(archive).to.be.an(Archive)
def test_markment_finds_2nd_level_headers(): "Markment should find and index 2nd level headers" MD = MARKDOWN(""" # Installation chuck norris ## Through PIP ## Compiling manually """) mm = Markment(MD) expect(mm.index()).to.equal([ {"text": "Installation", "anchor": "#installation", "level": 1, "child": [ {"text": "Through PIP", "level": 2, "anchor": "#through-pip"}, {"text": "Compiling manually", "level": 2, "anchor": "#compiling-manually"}, ]}, ])
def test_get_missing_backend(self): backend = get_backend(( 'social.backends.github.GithubOAuth2', 'social.backends.facebook.FacebookOAuth2', 'social.backends.flickr.FlickrOAuth' ), 'foobar') expect(backend).to.equal(None)
def test_callback_response(now): ("HTTPretty should call a callback function and set its return value as the body of the response" " requests") def request_callback(request, uri, headers): return [200, headers, "The {} response from {}".format(decode_utf8(request.method), uri)] HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", body=request_callback) response = requests.get('https://api.yahoo.com/test') expect(response.text).to.equal("The GET response from https://api.yahoo.com/test") HTTPretty.register_uri( HTTPretty.POST, "https://api.yahoo.com/test_post", body=request_callback) response = requests.post( "https://api.yahoo.com/test_post", {"username": "******"} ) expect(response.text).to.equal("The POST response from https://api.yahoo.com/test_post")
def test_fake_socket_passes_through_shutdown(): import socket HTTPretty.enable() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.truesock = MagicMock() expect(s.shutdown).called_with(socket.SHUT_RD).should_not.throw(AttributeError) s.truesock.shutdown.assert_called_with(socket.SHUT_RD)
def test_httpretty_should_allow_adding_and_overwritting_by_kwargs_u2(now): u"HTTPretty should allow adding and overwritting headers by keyword args " \ "with httplib2" HTTPretty.register_uri(HTTPretty.GET, "http://github.com/foo", body="this is supposed to be the response", server='Apache', content_length='27', content_type='application/json') headers, _ = httplib2.Http().request('http://github.com/foo', 'GET') expect(dict(headers)).to.equal({ 'content-type': 'application/json', 'content-location': 'http://github.com/foo', # httplib2 FORCES # content-location # even if the # server does not # provide it 'connection': 'close', 'content-length': '27', 'status': '200', 'server': 'Apache', 'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'), })
def test_py3kobject_implements_valid__repr__based_on__str__(): class MyObject(BaseClass): def __str__(self): return 'hi' myobj = MyObject() expect(repr(myobj)).to.be.equal('hi')
def test_fake_socket_passes_through_gettimeout(): import socket HTTPretty.enable() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.truesock = MagicMock() expect(s.gettimeout).called_with().should_not.throw(AttributeError) s.truesock.gettimeout.assert_called_with()
def test_inactive_user(self): self.strategy.set_settings({ 'SOCIAL_AUTH_INACTIVE_USER_URL': '/inactive' }) User.set_active(False) redirect = self.do_login(after_complete_checks=False) expect(redirect.url).to.equal('/inactive')
def test_equal_with_repr_of_complex_types_and_unicode(): (u"test usage of repr() inside expect(complex1).to.equal(complex2)") class Y(object): def __init__(self, x): self.x = x def __repr__(self): if PY3: # PY3K should return the regular (unicode) string return self.x else: return self.x.encode('utf-8') def __eq__(self, other): return self.x == other.x y1 = dict( a=2, b=Y(u'Gabriel Falcão'), c='Foo', ) expect(y1).to.equal(dict( a=2, b=Y(u'Gabriel Falcão'), c='Foo', ))
def test_get_not_unauthorized(self): unauthorized = '{"type": "unauthorized","status": 401,"message": "Unauthorized"}' httpretty.register_uri(httpretty.GET, path('/users/user_id'), status=401, body=unauthorized) client = ICMClient.create('my-access-token') response = client.users('user_id').GET() expect(response.status_code).should.equal(401) expect(response.text).should.equal(unauthorized)
def test_list_can_full_page_of_data(self): empty_page = json.dumps({'total': 1, 'next': None, 'previous': None, 'data': [USER]}) httpretty.register_uri(httpretty.GET, path('/users'), body=empty_page) client = ICMClient.create('my-access-token') users = client.users().LIST() expect(users.next()).should.equal(USER) users.next.when.called_with().should.throw(StopIteration)
def test_put_unauthorized(self): unauthorized = '{"type": "unauthorized","status": 401,"message": "Unauthorized"}' httpretty.register_uri(httpretty.PUT, path('/users/user_id'), status=401, body=unauthorized) client = ICMClient.create('my-access-token') response = client.users('user_id').PUT(params={'name': 'Craig Smith', 'email': '*****@*****.**'}) expect(response.status_code).should.equal(401) expect(response.text).should.equal(unauthorized)
def test_get_not_found(self): not_found = '{"status": 404,"message": "Not Found"}' httpretty.register_uri(httpretty.GET, path('/users/user_id'), status=404, body=not_found) client = ICMClient.create('my-access-token') response = client.users('user_id').GET() expect(response.status_code).should.equal(404) expect(response.text).should.equal(not_found)
def test_uri_info_eq_ignores_case(): """Test that URIInfo.__eq__ method ignores case for hostname matching. """ uri_info_uppercase = URIInfo( username='******', password='******', hostname=b'GOOGLE.COM', port=80, path=b'/', query=b'foo=bar&baz=test', fragment='', scheme='', ) uri_info_lowercase = URIInfo( username='******', password='******', hostname=b'google.com', port=80, path=b'/', query=b'foo=bar&baz=test', fragment='', scheme='', ) expect(uri_info_uppercase).to.equal(uri_info_lowercase)
def test_HTTPrettyRequest_queryparam(): """ A content-type of x-www-form-urlencoded with a valid queryparam body should return parsed content """ header = TEST_HEADER % {'content_type': 'application/x-www-form-urlencoded'} valid_queryparam = u"hello=world&this=isavalidquerystring" valid_results = {'hello': ['world'], 'this': ['isavalidquerystring']} request = HTTPrettyRequest(header, valid_queryparam) expect(request.parsed_body).to.equal(valid_results)
def test_httpretty_debugs_socket_recvfrom_into(context): "HTTPretty should debug socket.recvfrom_into" expect(context.sock.recvfrom_into).when.called.to.throw( RuntimeError, "HTTPretty intercepted and unexpected socket method call." )
def test_no_args(self): context = self.check_render( template="""{% get_tweets for "jresig" as tweets %}""", json_mock='jeresig.json', expected_kwargs={'screen_name': ['jresig']}, ) expect(context['tweets'][0]['text']).to.equal("This is not John Resig - you should be following @jeresig instead!!!")
def test_request_api_for_authentication(context): "SleepyHollow supports requests-based authentication" sl = SleepyHollow() response = sl.get(context.route_to("/auth/simple"), auth=('lincoln', 'gabriel')) response.status_code.should.equal(200) expect('Very Simple').to.be.within(response.text)
def test_js_confirms_doesnt_disrupt(context): "SleepyHollow will not block sleepy hollow" sl = SleepyHollow() response = sl.get(context.route_to("/jsconfirm")) response.status_code.should.equal(200) expect("Confirmation dialogs don't block").to.be.within(response.html)
def test_callback_response(now): (u"HTTPretty should all a callback function to be set as the body with" " requests") def request_callback(method, uri, headers): return "The {0} response from {1}".format(method, uri) HTTPretty.register_uri( HTTPretty.GET, "https://api.yahoo.com/test", body=request_callback) response = requests.get('https://api.yahoo.com/test') expect(response.text).to.equal('The GET response from https://api.yahoo.com/test') HTTPretty.register_uri( HTTPretty.POST, "https://api.yahoo.com/test_post", body=request_callback) response = requests.post( "https://api.yahoo.com/test_post", {"username": "******"} ) expect(response.text).to.equal("The POST response from https://api.yahoo.com/test_post")
def test_get_email_list_should_not_update_session_id_when_not_included_in_response(self, **kwargs): self.setup_mocks(**kwargs) self.mock_client.get_email_list.return_value = {'list': []} self.session.session_id = 1 self.session.email_timestamp = current_timestamp() self.session.get_email_list() expect(self.session.session_id).to.equal(1)
def test_get_list_filter_by_user(): # Delete all items UserItem.objects.all().delete() APIKey.objects.all().delete() User.objects.all().delete() user = User.objects.create(username='******', password='******') user2 = User.objects.create(username='******', password='******') # Create 30 items for x in range(30): UserItem.objects.create( name="my name is {}".format(x), user=[user, user2][x % 2], is_active=x % 2) apikey = APIKey.objects.create(user=user) response = client.get(reverse('by_user_authorized_item_list'), data={'apikey': apikey.token}, content_type='application/json') all_items = [ { "id": x + 1, "name": "my name is {}".format(x), "user_id": [user.id, user2.id][x % 2], } for x in range(30)] expected_items = [item for item in all_items if item["user_id"] == user.id] expected_response_content = { "items": expected_items} expect(json.loads(response.content)).to.equal(expected_response_content) expect(response.status_code).to.equal(200)
def test_get_email_list_should_extract_response_list(self, **kwargs): self.setup_mocks(**kwargs) self.mock_client.get_email_list.return_value = {'list': []} self.session.session_id = 1 self.session.email_timestamp = current_timestamp() email_list = self.session.get_email_list() expect(email_list).to.have.length_of(0)
def test_process_valid_input(self): self.test_flow_difference.tdigest_key = Mock() self.test_flow_difference.tdigest = Mock() self.test_flow_difference.metric_sink.read = self.stub_read_metric_sink_tdigest self.test_flow_difference._read_data = self.stub_read_data states = self.test_flow_difference.process() expect(states).to.be.equal((10, {'flag': 0}))
def test_get_companies(self): data = ''' { "_total": 1, "values": [ { "companyType": { "code": "O", "name": "Self Owned" }, "id": 5470551, "logoUrl": "https://media.licdn.com/mpr/mpr/e34...Po.png", "name": "Johni Corp" } ] } ''' httpretty.register_uri(httpretty.GET, TestPyLinkedin.URL_GET_COMPANIES, body=data, content_type="application/json") basic_profile = self.linkedin.get_companies() data = json.loads(data) expect(basic_profile).to.equal(data)
def test_get_email_list_should_not_refresh_session_when_email_not_expired(self, **kwargs): self.setup_mocks(**kwargs) self.mock_client.get_email_list.return_value = {'list': []} self.session.session_id = 1 self.session.email_timestamp = current_timestamp() - 3590 self.session.get_email_list() expect(self.mock_client.get_email_address.called).to.equal(False)
def test_be(): ("this(X).should.be(X) when X is a reference to the same object") d1 = {} d2 = d1 d3 = {} assert isinstance(this(d2).should.be(d1), bool) assert this(d2).should.be(d1) assert this(d3).should_not.be(d1) def wrong_should(): return this(d3).should.be(d1) def wrong_should_not(): return this(d2).should_not.be(d1) expect(wrong_should_not).when.called.should.throw( AssertionError, '{} should not be the same object as {}, but it is', ) expect(wrong_should).when.called.should.throw( AssertionError, '{} should be the same object as {}, but it is not', )
def test_verify(self): doc = {"provider_id" : "nope", "provider": "phone", "phone_code": "4758"} with app.test_request_context('/?code=4758'): resp = self.provider.verify(doc) expect(resp).to.be.none expect(doc["status"]).to.equal("confirmed")
def test_expires_time(self): user = self.do_login() social = user.social[0] expiration = social.expiration_datetime() expect(expiration <= DELTA).to.equal(True)
def test_inactive_user(self): self.strategy.set_settings( {'SOCIAL_AUTH_INACTIVE_USER_URL': '/inactive'}) User.set_active(False) redirect = self.do_login(after_complete_checks=False) expect(redirect.url).to.equal('/inactive')
def test_new_user(self): self.strategy.set_settings( {'SOCIAL_AUTH_NEW_USER_REDIRECT_URL': '/new-user'}) redirect = self.do_login(after_complete_checks=False) expect(redirect.url).to.equal('/new-user')
def test_redirect_value(self): self.strategy.set_request_data({'next': '/after-login'}) redirect = self.do_login(after_complete_checks=False) expect(redirect.url).to.equal('/after-login')
def test_find_step_size(self): expect(find_step_size(self.timeseries)).to.be.equal(10)
def test_extract_service_name(self): name = 'host.ip:0-0-0-0.service.count' expect(extract_service_name(name)).to.be.equal('0-0-0-0')
def test_tokens(self): user = self.do_login() expect(user.social[0].tokens).to.equal('foobar')
def test_len(self): mock_list_request('category.getall') expect(len(self.list)).to.equal(200) query = httpretty.last_request().querystring expect(query['count'][0]).to.equal('5')
def test_random_username(self): User(username='******') self.do_login(after_complete_checks=False) expect(self.strategy.session_get('username').startswith('foobar')) \ .to.equal(True)
def test_index_access(self): mock_list_request('category.getall') expect(self.list[0]['id']).to.equal(46535) expect(self.list[1]['id']).to.equal(46534) expect(self.list[2]['id']).to.equal(46532) expect(self.list[100]['id']).to.equal(44733)
def test_change_multiple_settings(self): dct = {"FOO": "foo", "BAR": "bar"} settings.configure(dct) expect(settings.FOO).to.equal("foo") expect(settings.BAR).to.equal("bar")
def test_multiple_accounts_with_same_email(self): user = User(username='******') user.email = '*****@*****.**' self.do_login(after_complete_checks=False) expect(self.strategy.session_get('username').startswith('foobar')) \ .to.equal(True)
def test_it_should_allow_load_resources_when_empty(self): settings.set(settings.SETTING_LANG, []) expect(should_load_resources('fr')).to.be.true
def test_overriding_a_setting(self): expect(settings.METROLOGY_PATH_PREFIX).to.equal(None) settings.put_setting("METROLOGY_PATH_PREFIX", "123") expect(settings.METROLOGY_PATH_PREFIX).to.equal("123")
#!/usr/bin/env python # -*- coding: utf-8 -*- from sure import expect from sleepyhollow import SleepyHollow http = SleepyHollow() for x in range(101): r = http.get('http://localhost:5000/heavy', {'index': x}) expect(r.url).to.equal('http://localhost:5000/heavy?index=%d' % x) print r, r.url, id(r)
def test_help_on_skill(self): self.agent.parse("what is timer skill") call = self.agent.model.on_answer.get_call(0) expected_response = "Timer skill {0} countdown time for you to make a boiled egg a success every time. Simpy ask start a timer for 3 minutes and wait ...".format( timer.version) expect(call.text).to.equal(expected_response)
def test_base_url(): expect(bucket_name_from_url("https://s3.amazonaws.com/")).should.equal(None)
def test_it_should_allow_load_resources(self): settings.set(settings.SETTING_LANG, ['en', 'it']) expect(should_load_resources('en')).to.be.true expect(should_load_resources('it')).to.be.true expect(should_load_resources('fr')).to.be.false
def do_login_with_partial_pipeline(self, before_complete=None): self.strategy.set_settings({ 'SOCIAL_AUTH_GITHUB_KEY': 'a-key', 'SOCIAL_AUTH_GITHUB_SECRET': 'a-secret-key', 'SOCIAL_AUTH_LOGIN_REDIRECT_URL': self.login_redirect_url, 'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': ( 'social.backends.github.GithubOAuth2', ), 'SOCIAL_AUTH_PIPELINE': ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.partial.save_status_to_session', 'social.tests.pipeline.ask_for_password', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.tests.pipeline.set_password', 'social.pipeline.user.user_details' ) }) start_url = do_auth(self.strategy).url target_url = self.strategy.build_absolute_uri( '/complete/github/?code=foobar' ) start_query = parse_qs(urlparse(start_url).query) location_url = target_url + ('?' in target_url and '&' or '?') + \ 'state=' + start_query['state'] location_query = parse_qs(urlparse(location_url).query) HTTPretty.register_uri(HTTPretty.GET, start_url, status=301, location=location_url) HTTPretty.register_uri(HTTPretty.GET, location_url, status=200, body='foobar') response = requests.get(start_url) expect(response.url).to.equal(location_url) expect(response.text).to.equal('foobar') HTTPretty.register_uri(HTTPretty.GET, uri=self.backend.ACCESS_TOKEN_URL, status=200, body=self.access_token_body or '', content_type='text/json') if self.user_data_url: HTTPretty.register_uri(HTTPretty.GET, self.user_data_url, body=self.user_data_body or '', content_type='text/json') self.strategy.set_request_data(location_query) def _login(strategy, user): strategy.session_set('username', user.username) redirect = do_complete(self.strategy, user=self.user, login=_login) url = self.strategy.build_absolute_uri('/password') expect(redirect.url).to.equal(url) HTTPretty.register_uri(HTTPretty.GET, redirect.url, status=200, body='foobar') HTTPretty.register_uri(HTTPretty.POST, redirect.url, status=200) password = '******' requests.get(url) requests.post(url, data={'password': password}) data = parse_qs(HTTPretty.last_request.body) expect(data['password']).to.equal(password) self.strategy.session_set('password', data['password']) if before_complete: before_complete() redirect = do_complete(self.strategy, user=self.user, login=_login) expect(self.strategy.session_get('username')).to.equal( self.expected_username ) expect(redirect.url).to.equal(self.login_redirect_url)
def test_localhost_bucket(): expect(bucket_name_from_url("https://localhost:5000/wfoobar/abc")).should.equal( "wfoobar" )
def test_find_archives_with_offset_and_count(self): httpretty.register_uri( httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format( self.api_key), body=textwrap.dedent( u("""\ { "count" : 6, "items" : [ { "createdAt" : 1395187836000, "duration" : 62, "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 8347554, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "createdAt" : 1395183243000, "duration" : 544, "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 78499758, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F30b3ebf1-ba36-4f5b-8def-6f70d9986fe9%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "createdAt" : 1394396753000, "duration" : 24, "id" : "b8f64de1-e218-4091-9544-4cbf369fc238", "name" : "showtime again", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 2227849, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fb8f64de1-e218-4091-9544-4cbf369fc238%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "createdAt" : 1394321113000, "duration" : 1294, "id" : "832641bf-5dbf-41a1-ad94-fea213e59a92", "name" : "showtime", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 42165242, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F832641bf-5dbf-41a1-ad94-fea213e59a92%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ] }""")), status=200, content_type=u('application/json')) archive_list = self.opentok.get_archives(count=4, offset=2) expect(httpretty.last_request().headers[u( 'x-tb-partner-auth')]).to.equal(self.api_key + u(':') + self.api_secret) expect(httpretty.last_request().headers[u('user-agent')]).to.contain( u('OpenTok-Python-SDK/') + __version__) expect(httpretty.last_request().headers[u('content-type')]).to.equal( u('application/json')) expect(httpretty.last_request()).to.have.property( "querystring").being.equal({ u('offset'): [u('2')], u('count'): [u('4')] }) expect(archive_list).to.be.an(ArchiveList) expect(archive_list).to.have.property(u('count')).being.equal(6) expect(list(archive_list.items)).to.have.length_of(4)
def test_localhost_without_bucket(): expect(bucket_name_from_url("https://www.localhost:5000")).should.equal(None)
def test_find_archive(self): archive_id = u('f6e7ee58-d6cf-4a59-896b-6d56b158ec71') httpretty.register_uri( httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive/{1}').format( self.api_key, archive_id), body=textwrap.dedent( u("""\ { "createdAt" : 1395187836000, "duration" : 62, "id" : "f6e7ee58-d6cf-4a59-896b-6d56b158ec71", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 8347554, "status" : "available", "hasAudio": true, "hasVideo": true, "outputMode": "composed", "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }""")), status=200, content_type=u('application/json')) archive = self.opentok.get_archive(archive_id) expect(httpretty.last_request().headers[u( 'x-tb-partner-auth')]).to.equal(self.api_key + u(':') + self.api_secret) expect(httpretty.last_request().headers[u('user-agent')]).to.contain( u('OpenTok-Python-SDK/') + __version__) expect(httpretty.last_request().headers[u('content-type')]).to.equal( u('application/json')) expect(archive).to.be.an(Archive) expect(archive).to.have.property(u('id')).being.equal(archive_id) expect(archive).to.have.property(u('name')).being.equal(u('')) expect(archive).to.have.property(u('status')).being.equal( u('available')) expect(archive).to.have.property(u('session_id')).being.equal( u('SESSIONID')) expect(archive).to.have.property(u('partner_id')).being.equal(123456) if PY2: created_at = datetime.datetime.fromtimestamp(1395187836, pytz.UTC) if PY3: created_at = datetime.datetime.fromtimestamp( 1395187836, datetime.timezone.utc) expect(archive).to.have.property( u('created_at')).being.equal(created_at) expect(archive).to.have.property(u('size')).being.equal(8347554) expect(archive).to.have.property(u('duration')).being.equal(62) expect(archive).to.have.property(u('url')).being.equal( u('http://tokbox.com.archive2.s3.amazonaws.com/123456%2Ff6e7ee58-d6cf-4a59-896b-6d56b158ec71%2Farchive.mp4?Expires=1395194362&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ))
def test_start_archive_with_name(self): httpretty.register_uri( httpretty.POST, u('https://api.opentok.com/v2/partner/{0}/archive').format( self.api_key), body=textwrap.dedent( u("""\ { "createdAt" : 1395183243556, "duration" : 0, "id" : "30b3ebf1-ba36-4f5b-8def-6f70d9986fe9", "name" : "ARCHIVE NAME", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 0, "status" : "started", "hasAudio": true, "hasVideo": true, "outputMode": "composed", "url" : null }""")), status=200, content_type=u('application/json')) archive = self.opentok.start_archive(self.session_id, name=u('ARCHIVE NAME')) expect(httpretty.last_request().headers[u( 'x-tb-partner-auth')]).to.equal(self.api_key + u(':') + self.api_secret) expect(httpretty.last_request().headers[u('user-agent')]).to.contain( u('OpenTok-Python-SDK/') + __version__) expect(httpretty.last_request().headers[u('content-type')]).to.equal( u('application/json')) # non-deterministic json encoding. have to decode to test it properly if PY2: body = json.loads(httpretty.last_request().body) if PY3: body = json.loads(httpretty.last_request().body.decode('utf-8')) expect(body).to.have.key(u('sessionId')).being.equal(u('SESSIONID')) expect(body).to.have.key(u('name')).being.equal(u('ARCHIVE NAME')) expect(archive).to.be.an(Archive) expect(archive).to.have.property(u('id')).being.equal( u('30b3ebf1-ba36-4f5b-8def-6f70d9986fe9')) expect(archive).to.have.property(u('name')).being.equal( u('ARCHIVE NAME')) expect(archive).to.have.property(u('status')).being.equal(u('started')) expect(archive).to.have.property(u('session_id')).being.equal( u('SESSIONID')) expect(archive).to.have.property(u('partner_id')).being.equal(123456) if PY2: created_at = datetime.datetime.fromtimestamp(1395183243, pytz.UTC) if PY3: created_at = datetime.datetime.fromtimestamp( 1395183243, datetime.timezone.utc) expect(archive).to.have.property( u('created_at')).being.equal(created_at) expect(archive).to.have.property(u('size')).being.equal(0) expect(archive).to.have.property(u('duration')).being.equal(0) expect(archive).to.have.property(u('url')).being.equal(None)
def test_travis_no_config(self): cover = Coveralls() expect(cover.config['service_name']).to.equal('travis-ci') expect(cover.config['service_job_id']).to.equal('777') expect(cover.config).should_not.have.key('repo_token')
def test_find_archives_with_count(self): httpretty.register_uri( httpretty.GET, u('https://api.opentok.com/v2/partner/{0}/archive').format( self.api_key), body=textwrap.dedent( u("""\ { "count" : 6, "items" : [ { "createdAt" : 1395187930000, "duration" : 22, "id" : "ef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 2909274, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2Fef546c5a-4fd7-4e59-ab3d-f1cfb4148d1d%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }, { "createdAt" : 1395187910000, "duration" : 14, "id" : "5350f06f-0166-402e-bc27-09ba54948512", "name" : "", "partnerId" : 123456, "reason" : "", "sessionId" : "SESSIONID", "size" : 1952651, "status" : "available", "hasAudio": true, "hasVideo": true, "url" : "http://tokbox.com.archive2.s3.amazonaws.com/123456%2F5350f06f-0166-402e-bc27-09ba54948512%2Farchive.mp4?Expires=1395188695&AWSAccessKeyId=AKIAI6LQCPIXYVWCQV6Q&Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ] }""")), status=200, content_type=u('application/json')) archive_list = self.opentok.get_archives(count=2) expect(httpretty.last_request().headers[u( 'x-tb-partner-auth')]).to.equal(self.api_key + u(':') + self.api_secret) expect(httpretty.last_request().headers[u('user-agent')]).to.contain( u('OpenTok-Python-SDK/') + __version__) expect(httpretty.last_request().headers[u('content-type')]).to.equal( u('application/json')) expect(httpretty.last_request()).to.have.property( "querystring").being.equal({u('count'): [u('2')]}) expect(archive_list).to.be.an(ArchiveList) expect(archive_list).to.have.property(u('count')).being.equal(6) expect(list(archive_list.items)).to.have.length_of(2)
def test_repo_token_in_not_compromised_verbose(self, mock_logger, mock_requests): self.setup_mock(mock_requests) result = Coveralls(repo_token='xxx').wear(dry_run=True) expect(mock_logger.call_args[0][0]).should_not.contain('xxx')
def test_repo_token_from_env(self): cover = Coveralls() expect(cover.config['service_name']).to.equal('travis-ci') expect(cover.config['service_job_id']).to.equal('777') expect(cover.config['repo_token']).to.equal('yyy')
def test_dry_run(self, mock_requests): self.setup_mock(mock_requests) result = Coveralls(repo_token='xxx').wear(dry_run=True) expect(result).should.be.equal({})
def test_local_with_config(self): cover = Coveralls() expect(cover.config['service_name']).to.equal('jenkins') expect(cover.config['repo_token']).to.equal('xxx') expect(cover.config).should_not.have.key('service_job_id')