示例#1
0
 def inner():
     l = Loklak()
     tweets = l.search('fossasia')
     # for tweet in tweets['statuses']:
     #     time.sleep(1)                           # Don't need this just shows the text streaming
     #     yield tweet.text
     for i in range(0, 10000):
         yield i
示例#2
0
 def inner():
     l = Loklak()
     tweets = l.search('fossasia')
     # for tweet in tweets['statuses']:
     #     time.sleep(1)                           # Don't need this just shows the text streaming
     #     yield tweet.text
     for i in range(0,10000):
     	yield i
示例#3
0
def ajaxwall(query=None):
	q = query
	l = Loklak()
	tweets = l.search(q)
	for tweet in tweets['statuses']:
		try:
			imageUrl = tweet['user']['profile_image_url_https']
			newUrl = imageUrl.split('_bigger')
			updatedUrl = newUrl[0]+newUrl[1]
			tweet['user']['profile_image_url_https'] = updatedUrl
		except:
			pass
	return json_response(tweets)
示例#4
0
def wall(query=None):
	q = query
	l = Loklak()
	tweets = l.search(q)
	for tweet in tweets['statuses']:
		try:
			imageUrl = tweet['user']['profile_image_url_https']
			newUrl = imageUrl.split('_bigger')
			updatedUrl = newUrl[0]+newUrl[1]
			tweet['user']['profile_image_url_https'] = updatedUrl
		except:
			pass
	return render_template('index.html', name=q, tweets=tweets, BASE_URL=BASE_URL)
示例#5
0
def ajaxwall(query=None):
    q = query
    l = Loklak()
    tweets = l.search(q)
    for tweet in tweets['statuses']:
        try:
            imageUrl = tweet['user']['profile_image_url_https']
            newUrl = imageUrl.split('_bigger')
            updatedUrl = newUrl[0] + newUrl[1]
            tweet['user']['profile_image_url_https'] = updatedUrl
        except:
            pass
    return json_response(tweets)
示例#6
0
class TestLoklak(unittest.TestCase):
    def setUp(self):
        self.loklak = Loklak()
    
    def test_hello(self):
        result = self.loklak.hello()
        self.assertEqual(result, {u'status': u'ok'})
    
    def test_peers(self):
        result = self.loklak.peers()
        self.assertTrue('peers' in result)
        self.assertTrue(type(result['peers']) == list)
        self.assertTrue(len(result['peers']) >= 1)
        self.assertEqual(len(result['peers']), result['count'])
示例#7
0
def visualize():
	q = request.form['q']
	l = Loklak()	
	data = l.search(q)
	statuses = data['statuses']
	if(len(statuses) == 0):
		return render_template('404.html')
	emotions = []
	languages = []
	countries = []
	for status in statuses:
		try:
			emotion = status['classifier_emotion']
			language = status['classifier_language']
			place = status['place_country']
			emotions.append(emotion)
			languages.append(language)
			countries.append(place)
		except:
			pass
	pprint(emotions)
	pprint(languages)
	pprint(countries)
	try:
		languageDict = dict(list(Counter(languages).items()))
		pprint(languageDict)
	except:
		pass
	try:
		emotionDict = dict(list(Counter(emotions).items()))
		pprint(emotionDict)
	except:
		pass
	try:
		countryDict = dict(list(Counter(countries).items()))
		pprint(countryDict)
	except:
		pass
	languageInfo = {}
	emotionInfo = {}
	countryInfo = {}
	for key, value in languageDict.iteritems():
		languageInfo[str(key)] = value
	for key, value in emotionDict.iteritems():
		emotionInfo[str(key)] = value
	for key, value in countryDict.iteritems():
		countryInfo[str(key)] = value
	return render_template('result.html', q=q, languages=languageInfo, emotions=emotionInfo, country=countryInfo, statuses=statuses)
示例#8
0
def wall(query=None):
    q = query
    l = Loklak()
    tweets = l.search(q)
    for tweet in tweets['statuses']:
        try:
            imageUrl = tweet['user']['profile_image_url_https']
            newUrl = imageUrl.split('_bigger')
            updatedUrl = newUrl[0] + newUrl[1]
            tweet['user']['profile_image_url_https'] = updatedUrl
        except:
            pass
    return render_template('index3.html',
                           name=q,
                           tweets=tweets,
                           BASE_URL=BASE_URL)
示例#9
0
def get_tweets(hashtag, since=0, count=100):
    """
    Fetches all tweets to a given hashtag
    :param hashtag: (str) keyword
    :param since: (str) Y-M-D
    :param count: (int) count
    :return: (list, int, int) 1. Content, 2.
    """

    l = Loklak()
    since = datetime.datetime.now() + datetime.timedelta(days=-since)
    since = datetime.datetime.strftime(since, "%Y-%m-%d")
    tweet_list = []
    for t in l.search(hashtag, since=since, count=count)["statuses"]:
        tweet_list.append(t["text"])

    return tweet_list  #, len(tweet_list), since
示例#10
0
class TestLoklak(unittest.TestCase):
    def setUp(self):
        self.loklak = Loklak()
    
    def test_hello(self):
        result = self.loklak.hello()
        self.assertEqual(result, {u'status': u'ok'})
    
    def test_peers(self):
        result = self.loklak.peers()
        self.assertTrue('peers' in result)
        self.assertTrue(type(result['peers']) == list)
        self.assertTrue(len(result['peers']) >= 1)
        self.assertEqual(len(result['peers']), result['count'])

    def test_search(self):
        result = self.loklak.search('doctor who')
        self.assertTrue('error' in self.loklak.search())
        self.assertTrue('statuses' in result)
        self.assertTrue(type(result['statuses']) == list)
        self.assertTrue(len(result['statuses']) >= 1)
        self.assertEqual(len(result['statuses']), int(result['search_metadata']['count']))

    def test_status(self):
        result = self.loklak.status()
        self.assertTrue('index_sizes' in result)
        self.assertTrue('messages' in result['index_sizes'])
        self.assertTrue('mps' in result['index_sizes'])
        self.assertTrue('users' in result['index_sizes'])
        self.assertTrue('queries' in result['index_sizes'])
        self.assertTrue('accounts' in result['index_sizes'])
        self.assertTrue('user' in result['index_sizes'])
        self.assertTrue('followers' in result['index_sizes'])
        self.assertTrue('following' in result['index_sizes'])
        self.assertTrue('client_info' in result)
        self.assertTrue('RemoteHost' in result['client_info'])
        self.assertTrue('IsLocalhost' in result['client_info'])
        self.assertTrue('If-Modified-Since' in result['client_info'])
        self.assertTrue('Host' in result['client_info'])
        self.assertTrue('Accept-Encoding' in result['client_info'])
        self.assertTrue('X-Forwarded-For' in result['client_info'])
        self.assertTrue('X-Real-IP' in result['client_info'])
        self.assertTrue('Via' in result['client_info'])
        self.assertTrue('User-Agent' in result['client_info'])
        self.assertTrue('Accept' in result['client_info'])
        self.assertTrue('Connection' in result['client_info'])
        self.assertTrue('Cache-Control' in result['client_info'])


    def test_user(self):
        result = self.loklak.user('dhruvRamani98')
        self.assertTrue('error' in self.loklak.user())
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        self.assertTrue('screen_name' in result['user'])
示例#11
0
import time
import sys
import pprint
import uuid
from uuid import getnode as get_mac
from loklak import Loklak
import string
import random

# Global loklak object
loklakConnectionObject = Loklak()

def generateID():
	return ''.join(random.sample(string.letters*12,12))

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3,GPIO.OUT,pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(7,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(11,GPIO.IN)
ls='OFF'

try:
	import ibmiotf.application
	import ibmiotf.device
except ImportError:
	# This part is only required to run the sample from within the samples
	# directory when the module itself is not installed.
"""This module contains an example for searching the tweets using search() function in loklak.py."""
from loklak import Loklak

myTweets = Loklak()

movieName = raw_input("What movie would you like to \
search recent tweets for? ")  #asks for what user would like to search for

index = 1
for tweet in myTweets.search(
        movieName
)["statuses"]:  #searches movie and finds "statuses" where "text" is under
    print("%d%s", index, '.')  #prints the tweet number
    print("%s\n",
          tweet["text"])  #prints the text of the tweet and makes a new line
    index += 1  #increments index
示例#13
0
 def setUp(self):
     """Test proper setup."""
     self.loklak = Loklak(self.baseUrl)
示例#14
0
 def setUp(self):
     self.loklak = Loklak()
示例#15
0
class TestLoklak(unittest.TestCase):
    """"test class"""
    def setUp(self):
        """test proper setup"""
        self.loklak = Loklak()

    def test_status(self):
        """test status"""
        result = self.loklak.status()

        self.assertTrue('index_sizes' in result)
        result_properties = [
            'messages', 'mps', 'users', 'queries',
            'accounts', 'user', 'followers', 'following'
        ]
        for prop in result_properties:
            self.assertTrue(
                prop in result['index_sizes'],
                msg='{} not found in index_sizes'.format(prop)
            )

    def test_hello(self):
        """test hello instance"""
        result = self.loklak.hello()
        self.assertEqual(result, {u'status': u'ok'})

    def test_geocode(self):
        """test geological features"""
        result = self.loklak.geocode()
        self.assertEqual(result, '{}')

        result = self.loklak.geocode(places=['Moscow'])
        self.assertTrue('locations' in result)
        self.assertTrue('Moscow' in result['locations'])
        self.assertEqual(
            'Russian Federation',
            result['locations']['Moscow']['country']
        )
        self.assertEqual(
            'Russian Federation',
            result['locations']['Moscow']['country']
        )
        self.assertTrue(
            isinstance(result['locations']['Moscow']['place'], list)
        )

    def test_get_map(self):
        """Tests the get_map method"""
        map_file = os.path.join(os.getcwd(), 'markdown.png')
        data = self.loklak.get_map(17.582729, 79.118320)
        self.assertTrue(data[:8] == '\211PNG\r\n\032\n' and
                                    (data[12:16] == 'IHDR'))
        with open(map_file, 'wb') as file_handle:
            file_handle.write(data)
        with open(map_file, 'rb') as file_handle:
            file_contents = file_handle.read()
        self.assertTrue(os.path.exists(map_file))
        self.assertEqual(data, file_contents)
        try:
            os.remove(map_file)
        except OSError as error:
            print(error)

    def test_peers(self):
        """test finding peers"""
        result = self.loklak.peers()
        self.assertTrue('peers' in result)
        self.assertTrue(isinstance(result['peers'], list))
        self.assertTrue(len(result['peers']) >= 1)
        self.assertEqual(len(result['peers']), result['count'])

    def test_user(self):
        """test user"""
        result = self.loklak.user('dhruvRamani98')
        self.assertTrue('error' in self.loklak.user())
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        self.assertTrue('screen_name' in result['user'])

    def test_search(self):
        """test search result"""
        result = self.loklak.search('doctor who')
        self.assertTrue('error' in self.loklak.search())
        self.assertTrue('statuses' in result)
        self.assertTrue(isinstance(result['statuses'], list))
        self.assertTrue(len(result['statuses']) >= 1)
        self.assertEqual(len(result['statuses']),
                         int(result['search_metadata']['count']))

    def test_aggregations(self):
        """test aggregations"""
        result = self.loklak.aggregations('sudheesh001', '2015-01-10',
                                          '2015-10-21', ['mentions',
                                                         'hashtags'], 10)
        data = result.json()
        self.assertEqual(result.status_code, 200)
        self.assertTrue('aggregations' in data)
        self.assertTrue('hashtags' in data['aggregations'])
        self.assertTrue('mentions' in data['aggregations'])
示例#16
0
 def setUp(self):
     """Test proper setup."""
     self.loklak = Loklak(self.baseUrl)
示例#17
0
#!/usr/bin/env python
# encoding: utf-8
"""This module contains an example of retrieving tweets using search() function and print them in the console."""
import sys
from loklak import Loklak

query = sys.argv[1]
l = Loklak()
print("Retrieving Tweets...")
tweets = l.search(query)

for tweet in tweets['statuses']:
	print('@'+str(tweet['screen_name'])+': '+str(tweet['text']))
from utils import get_tweet_rating, tweet_reply, user_reply, place_text_reply
from loklak import Loklak

l = Loklak()


def status():
    """Get the server status.

    Returns:
        server status.

    """
    status_reply = l.hello()['status']
    if status_reply == 'ok':
        status_reply = 'I am okay!'
    context = {'text': status_reply}
    return context


def search(query):
    """Search Loklak for a specific query.

    Args:
        query: the query to search for.
    Returns:
        tweet object for the query.

    """
    tweets = l.search(query)['statuses']
    if tweets:
示例#19
0
#!/usr/bin/env python
# encoding: utf-8
"""This module contains an example of retrieving tweets using search() function and print them in the console."""
import sys
from loklak import Loklak

query = sys.argv[1]
l = Loklak()
print("Retrieving Tweets...")
tweets = l.search(query)

for tweet in tweets['statuses']:
    print('@' + str(tweet['screen_name']) + ': ' + str(tweet['text']))
示例#20
0
 def setUp(self):
     """test proper setup"""
     self.loklak = Loklak()
from loklak import Loklak

myTweets = Loklak()

movieName = raw_input("What movie would you like to \
search recent tweets for? ") #asks for what user would like to search for

index = 1
for tweet in myTweets.search(movieName)["statuses"]: #searches movie and finds "statuses" where "text" is under
    print("%d%s", index, '.') #prints the tweet number
    print("%s\n", tweet["text"]) #prints the text of the tweet and makes a new line
    index += 1 #increments index
示例#22
0
"""This module contains an example on using every function in loklak.py and print the result in the console."""
import tempfile
from loklak import Loklak
from pprint import pprint

# Create a loklak object
l = Loklak()

### API Usage

#######################################
#		   Usage and Testings         #
#######################################
# Loklak settings API
settings = l.settings()
pprint(settings)

# Loklak Status API

status = l.status()
pprint(status)

# Loklak Hello API

hello = l.hello()
pprint(hello)

# Loklak Susi API
susi = l.susi('Hi I am Sudheesh')
pprint(susi)
示例#23
0
import tempfile
from loklak import Loklak
from pprint import pprint

# Create a loklak object
l = Loklak()

### API Usage

#######################################
#		   Usage and Testings         #
#######################################
# Loklak settings API
settings = l.settings()
pprint(settings)

# Loklak Status API

status = l.status()
pprint(status)

# Loklak Hello API

hello = l.hello()
pprint(hello)

# Loklak Susi API
susi = l.susi('Hi I am Sudheesh')
pprint(susi)

# Loklak Peers API
示例#24
0
def wall(query=None):
    q = query
    l = Loklak()
    tweets = l.search(q)
    return render_template('index.html', name=q, tweets=tweets)
示例#25
0
class TestLoklak(unittest.TestCase):
    """Test class."""

    baseUrl = 'http://api.loklak.org/'

    def setUp(self):
        """Test proper setup."""
        self.loklak = Loklak(self.baseUrl)

    def test_status(self):
        """Test status."""
        result = self.loklak.status()

        self.assertTrue('index' in result)
        result_properties = [
            'messages', 'mps', 'users', 'queries', 'accounts', 'user',
            'followers', 'following'
        ]
        for prop in result_properties:
            self.assertTrue(prop in result['index'],
                            msg='{} not found in index'.format(prop))

    def test_hello(self):
        """Test hello instance."""
        result = self.loklak.hello()
        self.assertEqual(result['status'], u'ok')

    def test_geocode(self):
        """Test geological features."""
        result = self.loklak.geocode()
        self.assertEqual(result, '{}')

        result = self.loklak.geocode(places=['Moscow'])
        self.assertTrue('locations' in result)
        self.assertTrue('Moscow' in result['locations'])
        self.assertEqual('Russian Federation',
                         result['locations']['Moscow']['country'])
        self.assertEqual('Russian Federation',
                         result['locations']['Moscow']['country'])
        self.assertTrue(
            isinstance(result['locations']['Moscow']['place'], list))

    def test_get_map(self):
        """Test the get_map method."""
        map_file = os.path.join(os.getcwd(), 'markdown.png')
        data = self.loklak.get_map(17.582729, 79.118320)
        print(data)
        self.assertFalse(data[:8] == b'\211PNG\r\n\032\n'
                         and data[12:16] == b'IHDR')
        with open(map_file, 'w+') as file_handle:
            file_handle.write(data)
        with open(map_file, 'rb') as file_handle:
            file_contents = file_handle.read()
        self.assertTrue(os.path.exists(map_file))
        # self.assertEqual(data, file_contents)
        try:
            os.remove(map_file)
        except OSError as error:
            print(error)

    def test_peers(self):
        """Test finding peers."""
        result = self.loklak.peers()
        if (len(result['peers']) == 0):
            pass
        else:
            self.assertTrue('peers' in result)
            self.assertTrue(isinstance(result['peers'], list))
            self.assertTrue(len(result['peers']) >= 1)
            self.assertEqual(len(result['peers']), result['count'])

    def test_push(self):
        """Test for push data to index."""
        data = {
            "statuses": [{
                "id_str":
                "yourmessageid_1234",
                "screen_name":
                "testuser",
                "created_at":
                "2016-07-22T07:53:24.000Z",
                "text":
                "The rain is spain stays always in the plain",
                "source_type":
                "GENERIC",
                "place_name":
                "Georgia, USA",
                "location_point": [3.058579854228782, 50.63296878274201],
                "location_radius":
                0,
                "user": {
                    "user_id": "youruserid_5678",
                    "name": "Mr. Bob",
                }
            }]
        }
        result = self.loklak.push(data)
        self.assertTrue('status' in result)

    def test_user(self):
        """Test user."""
        result = self.loklak.user('dhruvRamani98')
        self.assertTrue('error' in self.loklak.user())
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        self.assertTrue('screen_name' in result['user'])

    def test_susi(self):
        """Susi test."""
        result = self.loklak.susi('Hi I am Sudheesh')
        self.assertTrue(len(result['answers']) >= 1)

    def test_search(self):
        """Test search result."""
        result = self.loklak.search('doctor who', count=18)
        self.assertTrue('statuses' in result)
        self.assertTrue(isinstance(result['statuses'], list))
        self.assertTrue(len(result['statuses']) >= 1)
        self.assertEqual(len(result['statuses']),
                         int(result['search_metadata']['maximumRecords']))
        self.assertEqual(int(result['search_metadata']['maximumRecords']), 18)

    def test_aggregations(self):
        """Test aggregations."""
        result = self.loklak.aggregations('fossasia', '2017-01-10',
                                          '2018-01-10', 10)
        data = result.json()
        self.assertEqual(result.status_code, 200)
        self.assertTrue('aggregations' in data)
示例#26
0
class TestLoklak(unittest.TestCase):
    """Test class."""

    baseUrl = 'http://api.loklak.org/'

    def setUp(self):
        """Test proper setup."""
        self.loklak = Loklak(self.baseUrl)

    def test_status(self):
        """Test status."""
        result = self.loklak.status()

        self.assertTrue('index' in result)
        result_properties = [
            'messages', 'mps', 'users', 'queries', 'accounts', 'user',
            'followers', 'following'
        ]
        for prop in result_properties:
            self.assertTrue(prop in result['index'],
                            msg='{} not found in index'.format(prop))

        result = self.loklak.status("nonexisturl")
        self.assertEqual(result, "{}")

    def test_hello(self):
        """Test hello instance."""
        result = self.loklak.hello()
        self.assertEqual(result['status'], u'ok')

    def test_xmlToJson(self):
        """Test xmlToJson method."""
        xmlData = "<note>\n<to>Coders</to>\n<from>FOSSASIA</from>\n<heading>FOSSASIA</heading> \
                   \n<body>Let's code!!</body>\n</note>"

        expectedJSONData = '{"note": {"to": {"$": "Coders"}, "from": {"$": "FOSSASIA"}, "heading": {"$": "FOSSASIA"}, "body": {"$": "Let\'s code!!"}}}'
        result = self.loklak.xmlToJson(xmlData)
        self.assertEqual(result, expectedJSONData)
        result = self.loklak.xmlToJson()
        self.assertEqual(result, "[]")

    def test_geocode(self):
        """Test geological features."""
        result = self.loklak.geocode()
        self.assertEqual(result, '{}')

        result = self.loklak.geocode(places=['Moscow'])
        self.assertTrue('locations' in result)
        self.assertTrue('Moscow' in result['locations'])
        self.assertEqual('Russian Federation',
                         result['locations']['Moscow']['country'])
        self.assertEqual('Russian Federation',
                         result['locations']['Moscow']['country'])
        self.assertTrue(
            isinstance(result['locations']['Moscow']['place'], list))

    def test_get_map(self):
        """Test the get_map method."""
        map_file = os.path.join(os.getcwd(), 'markdown.png')
        data = self.loklak.get_map(17.582729, 79.118320)
        print(data)
        self.assertFalse(data[:8] == b'\211PNG\r\n\032\n'
                         and data[12:16] == b'IHDR')
        with open(map_file, 'w+') as file_handle:
            file_handle.write(data)
        with open(map_file, 'rb') as file_handle:
            file_contents = file_handle.read()
        self.assertTrue(os.path.exists(map_file))
        # self.assertEqual(data, file_contents)
        try:
            os.remove(map_file)
        except OSError as error:
            print(error)

    def test_peers(self):
        """Test finding peers."""
        result = self.loklak.peers()
        if (len(result['peers']) == 0):
            pass
        else:
            self.assertTrue('peers' in result)
            self.assertTrue(isinstance(result['peers'], list))
            self.assertTrue(len(result['peers']) >= 1)
            self.assertEqual(len(result['peers']), result['count'])

    def test_push(self):
        """Test for push data to index."""
        data = {
            "statuses": [{
                "id_str":
                "yourmessageid_1234",
                "screen_name":
                "testuser",
                "created_at":
                "2016-07-22T07:53:24.000Z",
                "text":
                "The rain is spain stays always in the plain",
                "source_type":
                "GENERIC",
                "place_name":
                "Georgia, USA",
                "location_point": [3.058579854228782, 50.63296878274201],
                "location_radius":
                0,
                "user": {
                    "user_id": "youruserid_5678",
                    "name": "Mr. Bob",
                }
            }]
        }
        result = self.loklak.push(data)
        self.assertTrue('status' in result)

    def test_user(self):
        """Test user."""
        result = self.loklak.user('dhruvRamani98')
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        self.assertTrue('screen_name' in result['user'])
        result = self.loklak.user("fossasia", 1500, 330)
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        result = self.loklak.user()
        self.assertTrue('error' in self.loklak.user())
        self.assertEqual(
            result,
            '{"error": "No user name given to query. Please check and try again"}'
        )

    def test_search(self):
        """Test search result."""
        result = self.loklak.search('doctor who', count=18)
        self.assertTrue('statuses' in result)
        self.assertTrue(isinstance(result['statuses'], list))
        self.assertTrue(len(result['statuses']) >= 1)
        self.assertEqual(len(result['statuses']),
                         int(result['search_metadata']['maximumRecords']))
        self.assertEqual(int(result['search_metadata']['maximumRecords']), 18)

        result = self.loklak.search('FOSSASIA',
                                    since='2000-01-01',
                                    until='2017-12-31_12:24',
                                    from_user='******',
                                    count=20)
        self.assertTrue('statuses' in result)

        result = self.loklak.search()
        self.assertEqual(
            result,
            '{"error": "No Query string has been given to query for an account"}'
        )

    def test_aggregations(self):
        """Test aggregations."""
        result = self.loklak.aggregations('fossasia', '2017-01-10',
                                          '2018-01-10', 10)
        data = result.json()
        self.assertEqual(result.status_code, 200)
        self.assertTrue('aggregations' in data)

        result = self.loklak.aggregations()
        self.assertEqual(
            result,
            '{"error": "No Query string has been given to run query for aggregations"}'
        )
示例#27
0
def ajaxwall(query=None):
    q = query
    l = Loklak()
    tweets = l.search(q)
    return json_response(tweets)
示例#28
0
class TestLoklak(unittest.TestCase):
    """"Test class."""

    baseUrl = 'http://loklak.org/'

    def setUp(self):
        """Test proper setup."""
        self.loklak = Loklak(self.baseUrl)

    def test_status(self):
        """Test status."""
        result = self.loklak.status()

        self.assertTrue('index' in result)
        result_properties = [
            'messages', 'mps', 'users', 'queries',
            'accounts', 'user', 'followers', 'following'
        ]
        for prop in result_properties:
            self.assertTrue(
                prop in result['index'],
                msg='{} not found in index'.format(prop)
            )

    def test_hello(self):
        """Test hello instance."""
        result = self.loklak.hello()
        self.assertEqual(result['status'], u'ok')

    def test_geocode(self):
        """Test geological features."""
        result = self.loklak.geocode()
        self.assertEqual(result, '{}')

        result = self.loklak.geocode(places=['Moscow'])
        self.assertTrue('locations' in result)
        self.assertTrue('Moscow' in result['locations'])
        self.assertEqual(
            'Russian Federation',
            result['locations']['Moscow']['country']
        )
        self.assertEqual(
            'Russian Federation',
            result['locations']['Moscow']['country']
        )
        self.assertTrue(
            isinstance(result['locations']['Moscow']['place'], list)
        )

    def test_get_map(self):
        """Test the get_map method."""
        map_file = os.path.join(os.getcwd(), 'markdown.png')
        data = self.loklak.get_map(17.582729, 79.118320)
        self.assertTrue(data[:8] == b'\211PNG\r\n\032\n' and
                        data[12:16] == b'IHDR')
        with open(map_file, 'wb') as file_handle:
            file_handle.write(data)
        with open(map_file, 'rb') as file_handle:
            file_contents = file_handle.read()
        self.assertTrue(os.path.exists(map_file))
        self.assertEqual(data, file_contents)
        try:
            os.remove(map_file)
        except OSError as error:
            print(error)

    def test_peers(self):
        """Test finding peers."""
        result = self.loklak.peers()
        self.assertTrue('peers' in result)
        self.assertTrue(isinstance(result['peers'], list))
        self.assertTrue(len(result['peers']) >= 1)
        self.assertEqual(len(result['peers']), result['count'])

    def test_push(self):
        """Test for push data to index."""
        data={   "statuses": [     {       "id_str": "yourmessageid_1234",       "screen_name": "testuser",       "created_at": "2016-07-22T07:53:24.000Z",       "text": "The rain is spain stays always in the plain",       "source_type": "GENERIC",       "place_name": "Georgia, USA",       "location_point": [3.058579854228782,50.63296878274201],       "location_radius": 0,       "user": {         "user_id": "youruserid_5678",         "name": "Mr. Bob",       }     }   ] }
        result = self.loklak.push(data)
        self.assertTrue('status' in result)

    def test_user(self):
        """Test user."""
        result = self.loklak.user('dhruvRamani98')
        self.assertTrue('error' in self.loklak.user())
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        self.assertTrue('screen_name' in result['user'])

    def test_susi(self):
        """Susi test."""
        result = self.loklak.susi('Hi I am Sudheesh')
        self.assertTrue(len(result['answers']) >= 1)

    def test_search(self):
        """Test search result."""
        result = self.loklak.search('doctor who', count=18)
        self.assertTrue('error' in self.loklak.search())
        self.assertTrue('statuses' in result)
        self.assertTrue(isinstance(result['statuses'], list))
        self.assertTrue(len(result['statuses']) >= 1)
        self.assertEqual(len(result['statuses']),
                         int(result['search_metadata']['count']))
        self.assertEqual(int(result['search_metadata']['count']), 18)

    def test_aggregations(self):
        """Test aggregations."""
        result = self.loklak.aggregations('sudheesh001', '2015-01-10',
                                          '2015-10-21', ['mentions',
                                                         'hashtags'], 10)
        data = result.json()
        self.assertEqual(result.status_code, 200)
        self.assertTrue('aggregations' in data)
        self.assertTrue('hashtags' in data['aggregations'])
        self.assertTrue('mentions' in data['aggregations'])
示例#29
0
import unittest
from loklak import Loklak
from pprint import pprint

# Create a loklak object
l = Loklak()

### API Usage

#######################################
#		   Usage and Testings         #
#######################################
# Loklak settings API
settings = l.settings()
pprint(settings)

# Loklak Status API

status = l.status()
pprint(status)

# Loklak Hello API

hello = l.hello()
pprint(hello)

# Loklak Peers API

peers = l.peers()
pprint(peers)
示例#30
0
class TestLoklak(unittest.TestCase):
    def setUp(self):
        self.loklak = Loklak()

    def test_hello(self):
        result = self.loklak.hello()
        self.assertEqual(result, {u'status': u'ok'})

    def test_geocode(self):
        result = self.loklak.geocode()
        self.assertEqual(result, '{}')

        result = self.loklak.geocode(places=['Moscow'])
        self.assertTrue('locations' in result)
        self.assertTrue('Moscow' in result['locations'])
        self.assertEqual(
            'Russian Federation',
            result['locations']['Moscow']['country']
        )
        self.assertEqual(
            'Russian Federation',
            result['locations']['Moscow']['country']
        )
        self.assertTrue(
            type(result['locations']['Moscow']['place']) == list
        )

    def test_peers(self):
        result = self.loklak.peers()
        self.assertTrue('peers' in result)
        self.assertTrue(type(result['peers']) == list)
        self.assertTrue(len(result['peers']) >= 1)
        self.assertEqual(len(result['peers']), result['count'])

    def test_search(self):
        result = self.loklak.search('doctor who')
        self.assertTrue('error' in self.loklak.search())
        self.assertTrue('statuses' in result)
        self.assertTrue(type(result['statuses']) == list)
        self.assertTrue(len(result['statuses']) >= 1)
        self.assertEqual(len(result['statuses']), int(result['search_metadata']['count']))

    def test_status(self):
        result = self.loklak.status()

        self.assertTrue('index_sizes' in result)
        result_properties = [
            'messages', 'mps', 'users', 'queries',
            'accounts', 'user', 'followers', 'following'
        ]
        for prop in result_properties:
            self.assertTrue(
                prop in result['index_sizes'],
                msg='{} not found in index_sizes'.format(prop)
            )

        self.assertTrue('client_info' in result)
        client_properties = [
            'RemoteHost', 'IsLocalhost', 'Host',
            'Accept-Encoding', 'X-Forwarded-For', 'X-Real-IP',
            'User-Agent', 'Accept', 'Connection',
        ]
        for prop in client_properties:
            self.assertTrue(
                prop in result['client_info'],
                msg='{} not found in client info'.format(prop)
            )

    def test_user(self):
        result = self.loklak.user('dhruvRamani98')
        self.assertTrue('error' in self.loklak.user())
        self.assertTrue('user' in result)
        self.assertTrue('name' in result['user'])
        self.assertTrue('screen_name' in result['user'])