def test_apicache(self, mock_open, mock_unlink, mock_mkdir, mock_isdir): fs = MockFilesystem() mock_isdir.side_effect = fs.isdir mock_mkdir.side_effect = fs.mkdir mock_unlink.side_effect = fs.unlink mock_open.side_effect = fs.open # Just because pragma: no cover is ugly cache = pycrest.eve.APICache() self.assertRaises(NotImplementedError, lambda: cache.get("foo")) self.assertRaises(NotImplementedError, lambda: cache.put("foo", "bar")) self.assertRaises(NotImplementedError, lambda: cache.invalidate("foo")) # Test default DictCache crest = pycrest.EVE() self.assertEqual(type(crest.cache).__name__, "DictCache") crest.cache.invalidate('nxkey') self.assertEqual(crest.cache.get('nxkey'), None) crest.cache.put('key', 'value') self.assertEqual(crest.cache.get('key'), 'value') # with mkdir needed crest = pycrest.EVE(cache_dir="/cachedir") # without mkdir now crest = pycrest.EVE(cache_dir="/cachedir") # cache created? self.assertEqual(type(crest.cache).__name__, "FileCache") # invalidate non-existing key crest.cache.invalidate('nxkey') # get non-existing key self.assertEqual(crest.cache.get('nxkey'), None) # cache (key, value) pair and retrieve it crest.cache.put('key', 'value') self.assertEqual(crest.cache.get('key'), 'value') # retrieve from disk crest = pycrest.EVE(cache_dir="/cachedir") self.assertEqual(crest.cache.get('key'), 'value') # invalidate key and check it's removed crest.cache.invalidate('key') self.assertEqual(crest.cache.get('key'), None) # dirname == filename tests # Use _getpath for platform independence fs.mkdir(crest.cache._getpath('key')) self.assertRaises(OSError, lambda: crest.cache.invalidate('key')) self.assertRaises(IOError, lambda: crest.cache.get('key'))
def update_credentials(self, implicit, client_id, client_secret): client_id = client_id.encode('ascii', 'ignore') client_secret = client_secret.encode('ascii', 'ignore') if implicit: self.eve = pycrest.EVE(client_id=Crest.SERVER_CLIENT_ID, api_key=None, redirect_uri=self.client_callback, testing=False) else: self.eve = pycrest.EVE(client_id=client_id, api_key=client_secret, redirect_uri=self.client_callback, testing=False)
def test_user_agent(self): @httmock.all_requests def default_useragent(url, request): self.assertEqual(request.headers["User-Agent"], "PyCrest/{0}".format(pycrest.version)) @httmock.all_requests def custom_useragent(url, request): self.assertEqual(request.headers["User-Agent"], "Testing 123") with httmock.HTTMock(default_useragent): eve = pycrest.EVE() eve() with httmock.HTTMock(custom_useragent): eve = pycrest.EVE(user_agent="Testing 123") eve()
def refresh_token(token, capsuler): auth_data = cache.get(token, None) if not auth_data: raise exceptions.AuthenticationFailed('Token has expired.') eve_sso = pycrest.EVE(client_id=settings.CREST_CLIENTID, api_key=settings.CREST_SECRET_KEY) cache.delete(token) # If we're using authentication only and no crest scopes, # the refresh token will be empty. Generate a new non-crest # token instead. if auth_data['refresh_token'] is None: new_token = hashlib.sha1(os.urandom(256)).hexdigest() expires = datetime.now(tz=pytz.UTC) + timedelta(minutes=20) cache.set(new_token, { 'username': auth_data['username'], 'refresh_token': None, 'expires': None }, timeout=(expires - datetime.now(tz=pytz.UTC) ).total_seconds()) # Use 20 minutes, same as crest expires = time.mktime(expires.timetuple()) else: auth_con = eve_sso.refr_authorize(auth_data['refresh_token']) new_token = _set_crest_data(auth_con, capsuler) expires = auth_con.expires log.debug(" ".join( ('Refreshed token for', auth_data['username'], new_token))) return new_token, expires
def test_params(self): @httmock.all_requests def no_params(url, request): self.assertEqual(url.query, "") return {"status_code": 200, "content": {}} @httmock.all_requests def with_custom_params(url, request): self.assertNotEqual(url.query, "") return {"status_code": 200, "content": {}} with httmock.HTTMock(no_params): eve = pycrest.EVE() eve.get("http://example.com") with httmock.HTTMock(with_custom_params): eve = pycrest.EVE() eve.get("http://example.com", params={"Foo": "Bar"})
def test_headers(self): _self = self @httmock.all_requests def custom_header(url, request): _self.assertIn("X-PyCrest-Testing", request.headers) _self.assertEqual(request.headers["X-PyCrest-Testing"], "True") @httmock.all_requests def no_custom_header(url, request): self.assertNotIn("X-PyCrest-Testing", request.headers) with httmock.HTTMock(no_custom_header): eve = pycrest.EVE() eve() with httmock.HTTMock(custom_header): eve = pycrest.EVE(additional_headers={"X-PyCrest-Testing": "True"}) eve()
def get_authed_crest_context(self): """fetch some market data from authenticated CREST""" # here we rudely fumble some of PyCrest's private parts # since we already completed the authentication process via python-social-auth authed_crest = pycrest.eve.AuthedConnection( res=self.request.user._get_crest_tokens(), endpoint=pycrest.EVE()._authed_endpoint, oauth_endpoint=pycrest.EVE()._oauth_endpoint, client_id=settings.SOCIAL_AUTH_EVEONLINE_KEY, api_key=settings.SOCIAL_AUTH_EVEONLINE_SECRET) authed_crest() # for demo purposes only: shortcut to market URL endpoint = pycrest.EVE()._authed_endpoint type_id = 34 # Tritanium, the "Hello World" of EVE Items... region_id = 10000002 # The Forge type_url = "{0}types/{1}/".format(endpoint, type_id) buy_orders_url = "{0}market/{1}/orders/buy/?type={2}".format( endpoint, region_id, type_url) sell_orders_url = "{0}market/{1}/orders/sell/?type={2}".format( endpoint, region_id, type_url) sell_orders = authed_crest.get(sell_orders_url)['items'] buy_orders = authed_crest.get(buy_orders_url)['items'] # sort by price up/down sell_orders = sorted(sell_orders, key=lambda k: k['price']) buy_orders = sorted(buy_orders, key=lambda k: k['price'], reverse=True) # truncate to Top <limit> orders limit = 5 if len(sell_orders) > limit: sell_orders = sell_orders[0:limit] if len(buy_orders) > limit: buy_orders = buy_orders[0:limit] name = authed_crest.whoami()['CharacterName'] return { 'sell_orders': sell_orders, 'buy_orders': buy_orders, 'name': name, }
def index(request): context = {} if not request.user.is_authenticated(): return HttpResponse("You're not logged in. How'd you get here?") authed_crest = pycrest.eve.AuthedConnection( res=request.user._get_crest_tokens(), endpoint=pycrest.EVE()._authed_endpoint, oauth_endpoint=pycrest.EVE()._oauth_endpoint, client_id=settings.SOCIAL_AUTH_EVEONLINE_KEY, api_key=settings.SOCIAL_AUTH_EVEONLINE_SECRET) try: authed_crest() context["tq"] = "" except: context["tq"] = "Cannot connect to TQ" char = Character.objects.filter(name=request.user.get_full_name()) if char: context["points"] = char[0].points #get starting system, create/store it return render(request, 'map/index.html', context=context)
def get_type_id(item): eve = pycrest.EVE() eve() itemType = {} items = getAllItems(eve.itemTypes) for _ in items: d = _._dict itemType[d['id_str']] = d['name'] for k, v in itemType.items(): if fuzz.ratio(v.lower(), item.lower()) > 85: print(v, item) return k, v
def get_public_crest_context(self): """fetch some example stuff from public CREST""" # use anonymous PyCrest as documented at http://pycrest.readthedocs.org/ public_crest = pycrest.EVE() public_crest() tranquility_user_count = public_crest.userCounts.eve # fetch incursions and make them usable inside a Django template incursions = [] for thing_that_looks_like_a_dict_but_isnt in public_crest.incursions( ).items: incursion = {} for key, value in thing_that_looks_like_a_dict_but_isnt._dict.iteritems( ): incursion[key] = value._dict if hasattr(value, '_dict') else value incursions.append(incursion) return { 'user_count': tranquility_user_count, 'incursions': incursions, }
def logincallback(): callback = url_for('logincallback', _external=True) code = request.args.get('code') eve = pycrest.EVE(client_id=app.config['EVESSO_CLIENT_ID'], api_key=app.config['EVESSO_SECRET_KEY'], redirect_uri=callback) con = eve.authorize(code) con() character = con.whoami() user = User.query.filter_by(id=character['CharacterID']).first() if not user: user = User(id=character['CharacterID'], name=character['CharacterName']) db.session.add(user) db.session.commit() login_user(user) update_character_info.delay(user.id) return redirect(url_for('home'))
def register_crest(): current_app.eve = pycrest.EVE( client_id=os.environ['CLIENT_ID'], api_key=os.environ['CLIENT_SECRET'], redirect_uri=url_for('login', _external=True))
def kspace_gen(request): import csv import os eve = pycrest.EVE() eve() crest_dict = eve.get("https://public-crest.eveonline.com/solarsystems/") system_dict = {} """ #get our systems loaded count = 5000 for sys in crest_dict["items"][5000:]: system_dict[sys["id_str"]] = sys constellation = eve.get(eve.get("https://public-crest.eveonline.com/solarsystems/%s/" % (sys["id_str"]))["constellation"]['href'])['name'] if(constellation[1] == '-' and len(constellation) == 8): #if wh system c = constellation[0]; classdict= {"A":"c1","B":"c2","C":"c3","D":"c4","E":"c5","F":"c6","G":"Thera","H":"c13",}; sec = classdict.get(c,"c13"); else: sec = math.ceil(eve.get(sys['href'])["securityStatus"] * 10)/10.0 if sec < 0.0: sec = 0.0 sec = str(abs(sec)) sec = ("k" + sec.translate(None,'.'))[:3] if (sec == "k-0"): print "ERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\nERROR\n" #check if system exists sys_obj = System.objects.filter(sysid = sys["id_str"]) if not sys_obj: count = count+1 print "Making system object " + str(count) sys_obj = System(name=sys["name"], sysid=sys["id_str"], color_code=sec) sys_obj.save() print sys_obj else: count = count+1 print "Skipping system object " + str(count) print sys_obj """ count = 0 with open( os.path.abspath( '/usr/share/nginx/backend/whturk/map/mapSolarSystemJumps.csv'), 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',') firstline = True for row in reader: if firstline: firstline = False continue A = System.objects.filter(sysid=row[2])[0] B = System.objects.filter(sysid=row[3])[0] if A.name > B.name: temp = A A = B B = temp con_obj = Connection.objects.filter(system_A=A, system_B=B) if not con_obj: count = count + 1 print "Making connection object " + str(count) con_obj = Connection(system_A=A, system_B=B, last_updated=timezone.now(), verification_count=1) con_obj.save() return HttpResponse("populating systems and connections")
import os, sys import itertools import zkill import settings import pycrest import database as db from sqlalchemy.sql.expression import or_, and_ import pdb crest = pycrest.EVE() crest() def getByAttrVal(objlist, attr, val): return getByAttrVals(objlist, attr, [val]) def getByAttrVals(objlist, attr, vals): ''' Searches list of dicts for a dict with dict[attr] == val ''' # matches = [getattr(obj, attr) in vals for obj in objlist] matches = filter(lambda obj: getattr(obj, attr) in vals, objlist) # index = matches.index(True) # find first match, raise ValueError if not found return matches def getAllItems(page): ''' Fetch data from all pages ''' ret = page().items
def test_authorize(self): client_id = "bar" api_key = "foo" code = "foobar" access_token = "123asd" refresh_token = "asd123" mock_resp = mock.MagicMock(requests.Response) def _get(href, *args, **kwargs): if href == "https://crest-tq.eveonline.com/": body = {"marketData": {"href": "getMarketData"}} res = mock_resp() res.status_code = 200 res.json.return_value = body return res elif href == "getMarketData": self.assertIn('headers', kwargs) self.assertEqual(kwargs['headers']['Authorization'], "Bearer %s" % access_token) body = {"totalCount": 2, "foo": {"foo": "Bar"}} res = mock_resp() res.status_code = 200 res.json.return_value = body return res elif href == "https://login.eveonline.com/oauth/verify": body = {"CharacterName": "Foobar"} res = mock_resp() res.status_code = 200 res.json.return_value = body return res else: res = mock_resp() res.status_code = 404 res.json.return_value = {} return res def _post(href, *args, **kwargs): if href == "https://login.eveonline.com/oauth/token": self.assertIn('headers', kwargs) if kwargs['params']['grant_type'] == 'authorization_code': auth = text_( base64.b64encode(bytes_("%s:%s" % (client_id, api_key)))) self.assertEqual(kwargs['headers']['Authorization'], "Basic %s" % auth) if kwargs['params']['code'] == code: body = { "access_token": access_token, "refresh_token": refresh_token, "expires_in": 1200 } res = mock_resp() res.status_code = 200 res.json.return_value = body return res else: res = mock_resp() res.status_code = 403 return res elif kwargs['params']['grant_type'] == 'refresh_token': auth = text_( base64.b64encode(bytes_("%s:%s" % (client_id, api_key)))) self.assertEqual(kwargs['headers']['Authorization'], "Basic %s" % auth) if kwargs['params']['refresh_token'] == refresh_token: body = { "access_token": access_token, "refresh_token": refresh_token, "expires_in": 1200 } res = mock_resp() res.status_code = 200 res.json.return_value = body return res else: res = mock_resp() res.status_code = 403 return res else: res = mock_resp() res.status_code = 403 res.json.return_value = {} return res else: res = mock_resp() res.status_code = 404 res.json.return_value = {} return res with mock.patch('requests.get', side_effect=_get): with mock.patch('requests.post', side_effect=_post): eve = pycrest.EVE(api_key=api_key, client_id=client_id, redirect_uri="http://foo.bar") auth_uri = "%s/authorize?response_type=code&redirect_uri=%s&client_id=%s&scope=publicData" % ( eve._oauth_endpoint, quote("http://foo.bar", safe=''), client_id, ) self.assertEqual(eve.auth_uri(scopes=["publicData"]), auth_uri) con = eve.authorize(code) self.assertRaises(APIException, lambda: eve.authorize("notcode")) r = con.refresh() self.assertRaises(AttributeError, con.__getattr__, 'marketData') con() self.assertEqual(con.marketData.href, "getMarketData") self.assertEqual(con.marketData().totalCount, 2) self.assertEqual(con.marketData().foo.foo, "Bar") info = con.whoami() self.assertEqual(info['CharacterName'], 'Foobar') info = con.whoami() self.assertEqual(info['CharacterName'], con._cache['whoami']['CharacterName']) info = r.whoami() self.assertEqual(info['CharacterName'], 'Foobar') r.refresh_token = "notright" self.assertRaises(APIException, lambda: r.refresh()) eve = pycrest.EVE(api_key=api_key, client_id=client_id, cache_time=0) con = eve.authorize(code) self.assertEqual(con().marketData().totalCount, 2) self.assertEqual(con().marketData().totalCount, 2)
def test_cache_control(self): @httmock.all_requests def root_m(url, request): body = { "shouldCache": { "href": "https://foo.bar/shouldCache/" }, "shouldNotCache": { "href": "https://foo.bar/shouldNotCache/" }, "noCache": { "href": "https://foo.bar/noCache/" }, "noStore": { "href": "https://foo.bar/noStore/" }, "brokenInt": { "href": "https://foo.bar/brokenInt" } } return {"status_code": 200, "content": body} @httmock.urlmatch(path=r'^/shouldCache/?$') def shouldCache(url, request): return { "status_code": 200, "content": { "href": "shouldCache" }, "headers": { "Cache-Control": "private, max-age=300" } } @httmock.urlmatch(path=r'^/shouldNotCache/?$') def shouldNotCache(url, request): return {"status_code": 200, "content": {"href": "shouldNotCache"}} @httmock.urlmatch(path=r'^/noCache/?$') def noCache(url, request): return { "status_code": 200, "content": { "href": "noCache" }, "headers": { "Cache-Control": "no-cache, max-age=300" } } @httmock.urlmatch(path=r'^/noStore/?$') def noStore(url, request): return { "status_code": 200, "content": { "href": "noStore" }, "headers": { "Cache-Control": "no-store, max-age=300" } } @httmock.urlmatch(path=r'^/brokenInt/?$') def brokenInt(url, request): return { "status_code": 200, "content": { "href": "brokenInt" }, "headers": { "Cache-Control": "private, max-age=asd" } } with httmock.HTTMock(shouldCache, shouldNotCache, noCache, noStore, brokenInt, root_m) as fake_http: eve = pycrest.EVE() eve() call_count = fake_http.call_count eve.shouldCache() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.shouldCache() self.assertEqual(fake_http.call_count, call_count) call_count = fake_http.call_count eve.shouldNotCache() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.shouldNotCache() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.noCache() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.noCache() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.noStore() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.noStore() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.brokenInt() self.assertEqual(fake_http.call_count, call_count + 1) call_count = fake_http.call_count eve.brokenInt() self.assertEqual(fake_http.call_count, call_count + 1) eve = pycrest.EVE() eve() with mock.patch('time.time') as mock_time: mock_time.return_value = 0 eve.shouldCache() self.assertEqual( list(eve.cache._dict.items())[0][1]['expires'], 300)
def login(): callback = url_for('logincallback', _external=True) eve = pycrest.EVE(client_id=app.config['EVESSO_CLIENT_ID'], api_key=app.config['EVESSO_SECRET_KEY'], redirect_uri=callback) return redirect(eve.auth_uri())
def test_public_api(self, mock_get): mock_resp = mock.MagicMock(requests.Response) def _get(href, *args, **kwargs): if href == "https://public-crest.eveonline.com/": body = { "marketData": { "href": "getMarketData" }, "incursions": { "href": "getIncursions" }, "status": { "eve": "online" } } res = mock_resp() res.status_code = 200 res.json.return_value = body return res elif href == "getMarketData": body = { "totalCount": 2, "items": [{ "avg_price": 100, "type": { "href": "getPunisher", "name": "Punisher", "id": 597 } }, { "avg_price": 101, "type": { "href": "getRifter", "name": "Rifter", "id": 587 } }, ["foo", "bar"], "baz"] } res = mock_resp() res.status_code = 200 res.json.return_value = body return res elif href == "getIncursions": body = {} res = mock_resp() res.status_code = 404 res.json.return_value = body return res else: res = mock_resp() res.status_code = 404 res.json.return_value = {} return res mock_get.side_effect = _get eve = pycrest.EVE() self.assertRaises(AttributeError, eve.__getattr__, 'marketData') eve() self.assertEqual(eve().marketData.href, "getMarketData") self.assertEqual(eve.marketData().totalCount, 2) self.assertEqual(eve.marketData().items[0].avg_price, 100) self.assertEqual(eve.marketData().items[2][0], "foo") self.assertEqual(eve.marketData().items[3], "baz") self.assertEqual(eve().status().eve, "online") self.assertRaises( APIException, lambda: eve.incursions()) # Scala's notation would be nice testing = pycrest.EVE(testing=True) self.assertEqual(testing._public_endpoint, "http://public-crest-sisi.testeveonline.com/")
def get_authorized_connection(code): eve_sso = pycrest.EVE(client_id=settings.CREST_CLIENTID, api_key=settings.CREST_SECRET_KEY) return eve_sso.authorize(code)
def test_public_api(self, mock_open, mock_listdir, mock_unlink, mock_mkdir, mock_isdir): fs = MockFilesystem() mock_isdir.side_effect = fs.isdir mock_mkdir.side_effect = fs.mkdir mock_unlink.side_effect = fs.unlink mock_listdir.side_effect = fs.listdir mock_open.side_effect = fs.open @httmock.urlmatch(scheme="https", netloc=r"^public-crest.eveonline.com$", path=r"^/queryString/?$") def test_qs(url, request): self.assertEqual(url.query, "query=string") return {"status_code": 200, "content": {}} @httmock.urlmatch(scheme="https", netloc=r"^public-crest.eveonline.com$", path=r"^/getPage/?$") def test_pagination(url, request): self.assertEqual(url.query, "page=2") return {"status_code": 200, "content": {}} with httmock.HTTMock(test_qs, test_pagination, *all_mocks): eve = pycrest.EVE() eve().queryString(query="string") eve.paginatedData() with httmock.HTTMock(*all_mocks): eve = pycrest.EVE() self.assertRaises(AttributeError, eve.__getattr__, 'marketData') eve() self.assertEqual( eve().marketData.href, "https://public-crest.eveonline.com/market/prices/") self.assertEqual(eve.marketData().totalCount, 2) self.assertEqual(eve.marketData().items[0].avg_price, 100) self.assertEqual(eve.marketData().items[2][0], "foo") self.assertEqual(eve.marketData().items[3], "baz") self.assertEqual(eve().status().eve, "online") self.assertRaises( APIException, lambda: eve.incursions()) # Scala's notation would be nice # cache miss eve = pycrest.EVE(cache_dir='/cachedir') eve() # cache hit eve = pycrest.EVE(cache_dir='/cachedir') eve() # stale cache hit ls = list(os.listdir('/cachedir')) self.assertEquals(len(ls), 1) path = os.path.join('/cachedir', ls[0]) recf = open(path, 'r') rec = pickle.loads(zlib.decompress(recf.read())) recf.close() rec['expires'] = 1 recf = open(path, 'w') recf.write(zlib.compress(pickle.dumps(rec))) recf.close() eve = pycrest.EVE(cache_dir='/cachedir') eve() testing = pycrest.EVE(testing=True) self.assertEqual(testing._public_endpoint, "http://public-crest-sisi.testeveonline.com/")
def test_authorize(self, mock_open, mock_listdir, mock_unlink, mock_mkdir, mock_isdir): client_id = "bar" api_key = "foo" code = "foobar" access_token = "123asd" refresh_token = "asd123" fs = MockFilesystem() mock_isdir.side_effect = fs.isdir mock_mkdir.side_effect = fs.mkdir mock_unlink.side_effect = fs.unlink mock_listdir.side_effect = fs.listdir mock_open.side_effect = fs.open @httmock.urlmatch(scheme="https", netloc=r"^login.eveonline.com$", path=r"^/oauth/token/?$", method="POST") def token_mock(url, request): params = parse_qs(url.query) if params['grant_type'][0] == 'authorization_code': auth = text_( base64.b64encode(bytes_("%s:%s" % (client_id, api_key)))) self.assertEqual(request.headers['Authorization'], "Basic %s" % auth) if params['code'][0] == code: body = { "access_token": access_token, "refresh_token": refresh_token, "expires_in": 1200 } return {"status_code": 200, "content": body} elif params['grant_type'][0] == 'refresh_token': auth = text_( base64.b64encode(bytes_("%s:%s" % (client_id, api_key)))) self.assertEqual(request.headers['Authorization'], "Basic %s" % auth) if params['refresh_token'][0] == refresh_token: body = { "access_token": access_token, "refresh_token": refresh_token, "expires_in": 1200 } return {"status_code": 200, "content": body} return {"status_code": 403, "content": {}} with httmock.HTTMock(token_mock, *all_mocks) as fake_http: eve = pycrest.EVE(api_key=api_key, client_id=client_id, redirect_uri="http://foo.bar") auth_uri = "%s/authorize?response_type=code&redirect_uri=%s&client_id=%s&scope=publicData" % ( eve._oauth_endpoint, quote("http://foo.bar", safe=''), client_id, ) self.assertEqual(eve.auth_uri(scopes=["publicData"]), auth_uri) con = eve.authorize(code) self.assertRaises(APIException, lambda: eve.authorize("notcode")) r = con.refresh() self.assertRaises(AttributeError, con.__getattr__, 'marketData') con() self.assertEqual( con.marketData.href, "https://public-crest.eveonline.com/market/prices/") self.assertEqual(con.marketData().totalCount, 2) self.assertEqual(con.marketData().items[1].type.name, "Rifter") info = con.whoami() self.assertEqual(info['CharacterName'], 'Foobar') info = con.whoami() self.assertEqual(info['CharacterName'], con._cache['whoami']['CharacterName']) info = r.whoami() self.assertEqual(info['CharacterName'], 'Foobar') r.refresh_token = "notright" self.assertRaises(APIException, lambda: r.refresh()) eve = pycrest.EVE(api_key=api_key, client_id=client_id) con = eve.authorize(code) self.assertEqual(con().marketData().totalCount, 2) self.assertEqual(con().marketData().totalCount, 2) # auth with refresh token con = eve.refr_authorize(con.refresh_token) self.assertRaises(AttributeError, con.__getattr__, 'marketData') con() self.assertEqual( con.marketData.href, "https://public-crest.eveonline.com/market/prices/") self.assertEqual(con.marketData().totalCount, 2) self.assertEqual(con.marketData().items[1].type.name, "Rifter") # fail auth with refresh token self.assertRaises(APIException, lambda: eve.refr_authorize('notright')) # auth with temp token con = eve.temptoken_authorize(con.token, con.expires - time.time(), con.refresh_token) self.assertRaises(AttributeError, con.__getattr__, 'marketData') con() self.assertEqual( con.marketData.href, "https://public-crest.eveonline.com/market/prices/") self.assertEqual(con.marketData().totalCount, 2) self.assertEqual(con.marketData().items[1].type.name, "Rifter") # test auto-refresh of expired token con = eve.temptoken_authorize(access_token, -1, refresh_token) con().marketData() self.assertGreater(con.expires, time.time()) # test cache miss eve = pycrest.EVE(api_key=api_key, client_id=client_id, cache_dir='/cachedir') con = eve.authorize(code) times_get = fake_http.call_count con() self.assertEqual(fake_http.call_count, times_get + 1) # test cache hit times_get = fake_http.call_count con() self.assertEqual(fake_http.call_count, times_get) # test cache stale ls = list(os.listdir('/cachedir')) self.assertEquals(len(ls), 1) path = os.path.join('/cachedir', ls[0]) recf = open(path, 'r') rec = pickle.loads(zlib.decompress(recf.read())) recf.close() rec['expires'] = 1 recf = open(path, 'w') recf.write(zlib.compress(pickle.dumps(rec))) recf.close() times_get = fake_http.call_count con().marketData() self.assertEqual(times_get + 1, fake_http.call_count)
def index(request): kspace_debug=False; context={} if not request.user.is_authenticated(): return HttpResponse("You're not logged in. How'd you get here?") authed_crest = pycrest.eve.AuthedConnection( res=request.user._get_crest_tokens(), endpoint=pycrest.EVE()._authed_endpoint, oauth_endpoint=pycrest.EVE()._oauth_endpoint, client_id=settings.SOCIAL_AUTH_EVEONLINE_KEY, api_key=settings.SOCIAL_AUTH_EVEONLINE_SECRET ) authed_crest() #get character name, create/store it name = request.user.get_full_name() char_obj = Character.objects.filter(name=name) print char_obj #get starting system, create/store it print "Ajax? " + str(request.is_ajax()) sec = "" try: if request.is_ajax(): points = 0 connection = "INVALID" prev_system = str(char_obj[0].location) prev_sys_obj = char_obj[0].location system_root = authed_crest.decode().character().location() system = system_root.solarSystem.name sid = system_root.solarSystem.id constellation = authed_crest.get(authed_crest.get("https://public-crest.eveonline.com/solarsystems/%s/" % (sid,))["constellation"]['href'])['name'] print constellation if(constellation[1] == '-'): #if wh system c = constellation[0]; classdict= {"A":"c1","B":"c2","C":"c3","D":"c4","E":"c5","F":"c6","G":"Thera","H":"c13",}; sec = classdict[c]; else: sec = str(math.ceil(authed_crest.get(system_root.solarSystem.href)["securityStatus"] * 10)/10.0) sec = ("k" + sec.translate(None,'.'))[:3] sys_obj = System.objects.filter(name=system) if not sys_obj: print "Making system object" sys_obj = System(name=system, sysid=sid, color_code=sec) sys_obj.save() else: print sys_obj sys_obj = sys_obj[0] print sys_obj else: system = None sys_obj= None except AttributeError as e: system = None sys_obj = None print e if not char_obj: print "Making character object" char_obj = Character(name=name,location=sys_obj) char_obj.save() else: char_obj.update(location=sys_obj) char_obj = char_obj[0] #get starting ship, create/store it #can't do this yet if request.is_ajax(): print "kspace_debug:" print kspace_debug if ((prev_system != "None" and system != "None") and prev_system != system and ((prev_system[0] == 'J' and prev_system[1:].isdigit()) or (system[0] == 'J' and system[1:].isdigit()) or kspace_debug == True or prev_system == "Thera" or system == "Thera") ): print "Wormhole connection found" print type(prev_system) print system #make connection system_A = prev_system system_A_obj = prev_sys_obj system_B = system system_B_obj = sys_obj #get systems in alphabetical order if system_A > system_B: system_B = prev_system system_B_obj = prev_sys_obj system_A = system system_A_obj = sys_obj print "system A is " + system_A print "system B is " + system_B #see if the connection exists con_obj = Connection.objects.filter(system_A=system_A_obj, system_B=system_B_obj) #doesn't exist, create and assign 1 point if not con_obj: con_obj = Connection(system_A=system_A_obj, system_B=system_B_obj,last_updated=timezone.now(),verification_count=1, can_timeout=True) con_obj.save() points = 1 #does exist, update and assign scaled points else: last_updated = con_obj[0].last_updated now = timezone.now() elapsed = now - last_updated if elapsed.total_seconds() <= 14400: #four hours to recharge point value points = (elapsed.total_seconds())/(14400) else: points = 1 con_obj.update(last_updated=now,verification_count=con_obj[0].verification_count+1) con_obj = con_obj[0] connection = str(con_obj) print connection char_obj.points += points; char_obj.save() if system == None or system == "None": system = "Unknown system or character offline..." jsonObj = json.dumps({"update": { "system" :{ "name": system, "sec": sec, }, "points" : str(char_obj.points), "connection" :{ "system_A": system, "system_B": prev_system, "name": connection} } }, separators=(',',': ')) return HttpResponse( jsonObj, content_type="application/json" ) else: context["points"] = char_obj.points return render(request, 'tracker/index.html', context=context)