Esempio n. 1
0
    def test_help(self):
        devices = Device.objects.all()
        contributors = Contributor.objects.all()
        nb_devices = len(devices)
        nb_contributors = len(contributors)

        contributor = Contributor(name=self.unregister_test_user_name, email=self.unregister_test_user_email, password=self.unregister_test_user_password)
        contributor.save()
        device = Device(phone_number=self.help_no, contributor=contributor)
        device.save()
                            
        receive_sms(self.help_no, "help")
        devices = Device.objects.all()
        contributors = Contributor.objects.all()
        self.assertEqual(len(devices), nb_devices + 1)
        self.assertEqual(len(contributors), nb_contributors + 1)
Esempio n. 2
0
    def setUp(self):
        super(ContributorResourceTest, self).setUp()

        # Create a user.
        self.username = u'john'
        self.password = u'doe'
        self.email = u'*****@*****.**'
        self.user = User.objects.create_user(self.username, self.email, self.password)
        self.api_key = self.user.api_key.key
        self.c = Client()
        self.post_data = {
            'name': 'james',
            'email': '*****@*****.**',
            'password': self.user.__dict__["password"],
            'language': 'DE'
        }
        self.put_data = {
            'email': '*****@*****.**',
            'language': 'DE'
        }

        # Fetch the ``Entry`` object we'll use in testing.
        # Note that we aren't using PKs because they can change depending
        # on what other tests are running.
        self.contributor_1 = Contributor(name="Tobias", email="*****@*****.**")
        self.contributor_1.set_password("tobias")
        self.contributor_1.save()

        # We also build a detail URI, since we will be using it all over.
        # DRY, baby. DRY.
        self.list_url = '/api/v1/contributors/'
        self.detail_url = '{0}{1}/'.format(self.list_url, self.contributor_1.pk)
Esempio n. 3
0
def create_unknown_user(mobile_number):
    # TODO: Really not sure about this process and how python handles the erros, what happen if an error occurs?
    try:
        contributor = Contributor(name=mobile_number, email=mobile_number + "@feowl.com", status=Contributor.UNKNOWN)
        contributor.save()
        device = Device(category="mobile", phone_number=mobile_number, contributor=contributor)
        device.save()
    except IntegrityError, e:
        msg = e.message
        if msg.find("name") != -1:
            logger.warning("Name already exist. Please use an other one")
            return
        elif msg.find("email") != -1:
            logger.warning("Email already exist. Please use an other one.")
            return
        logger.error("Unkown Error please try later to register")
        return
Esempio n. 4
0
def read_message(mobile_number, message, auto_mode=True):
    index, keyword, message_array = parse(message)

    # *ensure* that there is both a device with that number and a corresponding contributor
    devices = Device.objects.filter(phone_number=mobile_number)
    if len(devices) > 0:
        device = devices[0]
        # check if user exists; otherwise create an unknown user
        if device.contributor is None:
            logger.debug("found mobile device " + str(device) + " without a contributor")
            logger.debug("creating a new contributor")
            contributor = Contributor(name=mobile_number,
                        email=mobile_number + "@feowl.com",
                        status=Contributor.UNKNOWN)
            # if we can deduce the language from the current keyword, set
            #  contributor language
            if keyword in kw2lang:
                contributor.language = kw2lang[keyword].upper()
            contributor.save()
            device.contributor = contributor
            device.save()
        else:
            contributor = device.contributor
    else:
        logger.debug("device does not exist")
        logger.debug("creating a new device and contributor")
        # create a new user (potentially with language) and device
        (device, contributor) = create_unknown_user(mobile_number)
        if keyword in kw2lang:
            contributor.language = kw2lang[keyword].upper()
        contributor.save()
    logger.debug("associating incoming message with " + str(device) + " // " + str(contributor))

    # set the language for upcoming messages
    language = (keyword in kw2lang and kw2lang[keyword]) or contributor.language or "en"
    activate(language.lower())

    # invariant: if we arrive here, we are sure that we have a device
    #  and a contributor. now, do the processing
    if keyword in ("pc", "rep"):
        return contribute(message_array, device, auto_mode)
    if keyword in ("pcm", "repm"):
        return contribute_multiple(message_array, device, auto_mode)
    elif keyword in ("help", "aide"):
        return help(message_array, device, auto_mode)
    elif keyword in ("register", "inscription"):
        return register(message_array, device, auto_mode)
    elif keyword == "stop":
        return unregister(message_array, device, auto_mode)
    elif keyword in ("cancel", "annule"):
        return cancel(message_array, device. auto_mode)
    elif keyword in ("test"):
        return test(message_array, device, auto_mode)
    elif index == -1:  # Should send an error messages and maybe plus help
        return invalid(message_array, device, auto_mode)
Esempio n. 5
0
    def test_post_list_with_permissions_and_polled_today(self):
        """Post a single report to the API with authenticated and with add permissions"""
        add_powerreport = Permission.objects.get(codename="add_powerreport")
        self.user.user_permissions.add(add_powerreport)

        # Set enquiry to today - so that the contribution is accepted
        self.contributor_1 = Contributor(name="Marc", email="*****@*****.**")
        self.contributor_1.set_password("marc")
        self.contributor_1.enquiry = datetime.today().date()
        self.contributor_1.save()

        # Check how many there are first.
        nb = PowerReport.objects.count()
        rt = PowerReport(has_experienced_outage=True, duration=153, contributor=self.contributor_1, area=Area.objects.get(pk=1), happened_at=datetime.today().date())
        rt.save()
        # Verify that a new report has been added.
        self.assertEqual(PowerReport.objects.count(), nb + 1)
Esempio n. 6
0
class PowerReportResourceTest(ResourceTestCase):
    fixtures = ['test_data.json']

    def setUp(self):
        super(PowerReportResourceTest, self).setUp()

        # Create a user.
        self.username = u'john'
        self.password = u'doe'
        self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
        self.api_key = self.user.api_key.key
        self.c = Client()
        self.post_data = {
           "area": "/api/v1/areas/1/",
           "happened_at": "2012-06-14 12:37:50",
           "has_experienced_outage": True,
           "duration": 60
        }

        

        # Fetch the ``Entry`` object we'll use in testing.
        # Note that we aren't using PKs because they can change depending
        # on what other tests are running.
        self.power_report_1 = PowerReport.objects.get(duration=121)

        # We also build a detail URI, since we will be using it all over.
        # DRY, baby. DRY.
        self.detail_url = '/api/v1/reports/{0}/'.format(self.power_report_1.pk)

    def get_credentials(self):
        return {"username": self.username, "api_key": self.api_key}

    def test_get_list_unauthorizied(self):
        """Get reports from the API without authenticated"""
        self.assertHttpUnauthorized(self.c.get('/api/v1/reports/'))

    def test_get_list_json(self):
        """Get reports from the API with authenticated. With checks if all keys are available"""
        resp = self.c.get('/api/v1/reports/', self.get_credentials())
        self.assertValidJSONResponse(resp)
        nb = PowerReport.objects.count()

        # Scope out the data for correctness.
        self.assertEqual(len(self.deserialize(resp)['objects']), nb)
        # Here we're checking an entire structure for the expected data.
        self.assertKeys(self.deserialize(resp)['objects'][0], {
            'area': '/api/v1/areas/1/',
            'happened_at': '2012-06-13T12:37:50+00:00',
            'has_experienced_outage': True,
            'location': None,
            'duration': 240,
            'quality': '1.00',
            'resource_uri': '/api/v1/reports/2/',
            'contributor': None,
            'device': None
        })

    def test_header_auth(self):
        resp = self.c.get(self.detail_url, **{'HTTP_AUTHORIZATION': 'ApiKey ' + self.username + ':' + self.api_key})
        self.assertValidJSONResponse(resp)

        # We use ``assertKeys`` here to just verify the keys, not all the data.
        #self.assertKeys(self.deserialize(resp), ['area', 'device', 'happened_at', 'has_experienced_outage', 'contributor', 'location', 'duration', 'quality'])
        self.assertEqual(self.deserialize(resp)['duration'], 121)

    def test_get_detail_unauthenticated(self):
        """Try to Get a single report from the API without authenticated"""
        self.assertHttpUnauthorized(self.c.get(self.detail_url))

    def test_get_detail_json(self):
        """Get a single report from the API with authenticated. With checks if all keys are available"""
        resp = self.c.get(self.detail_url, self.get_credentials())
        self.assertValidJSONResponse(resp)

        # We use ``assertKeys`` here to just verify the keys, not all the data.
        #self.assertKeys(self.deserialize(resp), ['area', 'happened_at', 'has_experienced_outage', 'contributor', 'location', 'duration', 'quality', 'resource_uri'])
        self.assertEqual(self.deserialize(resp)['duration'], 121)

    def test_post_list_unauthenticated(self):
        """Try to Post a single report to the API without authenticated"""
        self.assertHttpUnauthorized(self.c.post('/api/v1/reports/', data=self.post_data))

    def test_post_list_without_permissions(self):
        """Post a single report to the API with authenticated and without add permissions"""
        add_powerreport = Permission.objects.get(codename="add_powerreport")
        self.user.user_permissions.remove(add_powerreport)
        nb = PowerReport.objects.count()
        self.assertHttpUnauthorized(self.c.post('/api/v1/reports/?username='******'&api_key=' + self.api_key, data=json.dumps(self.post_data), content_type="application/json"))
        # Verify that nothing was added to the db
        self.assertEqual(PowerReport.objects.count(), nb)

    def test_post_list_with_permissions(self):
        """Post a single report to the API with authenticated and with add permissions"""
        add_powerreport = Permission.objects.get(codename="add_powerreport")
        self.user.user_permissions.add(add_powerreport)
        # Check how many there are first.
        nb = PowerReport.objects.count()
        self.assertHttpCreated(self.c.post('/api/v1/reports/?username=%s&api_key=%s' % (self.username, self.api_key), data=json.dumps(self.post_data), content_type="application/json"))
        # Verify that no report has been added
        self.assertEqual(PowerReport.objects.count(), nb)

    def test_post_list_with_permissions_and_polled_today(self):
        """Post a single report to the API with authenticated and with add permissions"""
        add_powerreport = Permission.objects.get(codename="add_powerreport")
        self.user.user_permissions.add(add_powerreport)

        # Set enquiry to today - so that the contribution is accepted
        self.contributor_1 = Contributor(name="Marc", email="*****@*****.**")
        self.contributor_1.set_password("marc")
        self.contributor_1.enquiry = datetime.today().date()
        self.contributor_1.save()

        # Check how many there are first.
        nb = PowerReport.objects.count()
        rt = PowerReport(has_experienced_outage=True, duration=153, contributor=self.contributor_1, area=Area.objects.get(pk=1), happened_at=datetime.today().date())
        rt.save()
        # Verify that a new report has been added.
        self.assertEqual(PowerReport.objects.count(), nb + 1)

    def test_put_detail_unauthenticated(self):
        """Put a single report is not allowed from the API with authenticated"""
        self.assertHttpMethodNotAllowed(self.c.put(self.detail_url))

    def test_put_detail(self):
        """Put a single report is not allowed from the API with authenticated"""
        self.assertHttpMethodNotAllowed(self.c.put(self.detail_url, self.get_credentials()))

    def test_delete_detail_unauthenticated(self):
        """Delete a single report is not allowed from the API without authenticated"""
        self.assertHttpMethodNotAllowed(self.c.delete(self.detail_url))

    def test_delete_detail(self):
        """Delete a single report is not allowed from the API with authenticated"""
        self.assertHttpMethodNotAllowed(self.c.delete(self.detail_url, self.get_credentials()))
Esempio n. 7
0
class ContributorResourceTest(ResourceTestCase):

    def setUp(self):
        super(ContributorResourceTest, self).setUp()

        # Create a user.
        self.username = u'john'
        self.password = u'doe'
        self.email = u'*****@*****.**'
        self.user = User.objects.create_user(self.username, self.email, self.password)
        self.api_key = self.user.api_key.key
        self.c = Client()
        self.post_data = {
            'name': 'james',
            'email': '*****@*****.**',
            'password': self.user.__dict__["password"],
            'language': 'DE'
        }
        self.put_data = {
            'email': '*****@*****.**',
            'language': 'DE'
        }

        # Fetch the ``Entry`` object we'll use in testing.
        # Note that we aren't using PKs because they can change depending
        # on what other tests are running.
        self.contributor_1 = Contributor(name="Tobias", email="*****@*****.**")
        self.contributor_1.set_password("tobias")
        self.contributor_1.save()

        # We also build a detail URI, since we will be using it all over.
        # DRY, baby. DRY.
        self.list_url = '/api/v1/contributors/'
        self.detail_url = '{0}{1}/'.format(self.list_url, self.contributor_1.pk)

    def get_credentials(self):
        return {"username": self.username, "api_key": self.api_key}

    def test_get_list_unauthorzied(self):
        """Get areas from the API without authenticated"""
        self.assertHttpUnauthorized(self.c.get(self.list_url))

    def test_get_list_json(self):
        """Get users from the API with authenticated. With checks if all keys are available"""
        resp = self.c.get(self.list_url, self.get_credentials())
        self.assertValidJSONResponse(resp)

        # Scope out the data for correctness.
        self.assertEqual(len(self.deserialize(resp)['objects']), 1)
        # Here, we're checking an entire structure for the expected data.
        self.assertEqual(self.deserialize(resp)['objects'][0], {
            'id': '1',
            'name': 'Tobias',
            'email': '*****@*****.**',
            'password': settings.DUMMY_PASSWORD,
            'resource_uri': self.detail_url,
            'language': 'EN',  # EN is the default value
            'frequency': 1,
            'enquiry': None,
            'response': None,
            'resource_uri': '/api/v1/contributors/1/'
        })

    def test_get_detail_unauthenticated(self):
        """Try to Get a single user from the API without authenticated"""
        self.assertHttpUnauthorized(self.c.get(self.detail_url))

    def test_get_detail_json(self):
        """Get a single user from the API with authenticated. With checks if all keys are available"""
        resp = self.c.get(self.detail_url, self.get_credentials())
        self.assertValidJSONResponse(resp)

        # We use ``assertKeys`` here to just verify the keys, not all the data.
        self.assertKeys(self.deserialize(resp), ['id', 'email', 'password', 'name', 'language', 'frequency', 'response', 'enquiry', 'resource_uri'])
        self.assertEqual(self.deserialize(resp)['name'], "Tobias")

    def test_post_list_unauthenticated(self):
        """Try to Post a single user to the API without authenticated"""
        self.assertHttpUnauthorized(self.c.post(self.list_url, data=self.post_data))

    def test_post_list_without_permissions(self):
        """Try to Post a single user to the API with authenticated and without permission"""
        self.assertHttpUnauthorized(self.c.post(self.list_url + '?username='******'&api_key=' + self.api_key, data=json.dumps(self.post_data), content_type="application/json"))

    def test_post_list_with_permissions(self):
        """Try to Post a single user to the API with authenticated and permission"""
        add_contributor = Permission.objects.get(codename="add_contributor")
        self.user.user_permissions.add(add_contributor)
        self.assertEqual(Contributor.objects.count(), 1)
        self.assertHttpCreated(self.c.post(self.list_url + '?username='******'&api_key=' + self.api_key, data=json.dumps(self.post_data), content_type="application/json"))
        self.assertEqual(Contributor.objects.count(), 2)

    def test_put_detail_unauthenticated(self):
        """Try to Put a single user is not allowed from the API with authenticated"""
        self.assertHttpUnauthorized(self.c.put(self.detail_url))

    def test_put_detail_without_permission(self):
        """Try to Put a single user is not allowed from the API with authenticated and without permission"""
        self.assertHttpUnauthorized(self.c.put(self.detail_url, self.get_credentials()))

    def test_put_detail_with_permission(self):
        """Try to Put a single user is not allowed from the API with authenticated abd permission"""
        change_contributor = Permission.objects.get(codename="change_contributor")
        self.user.user_permissions.add(change_contributor)
        self.assertEqual(Contributor.objects.count(), 1)
        self.assertHttpAccepted(self.c.put(self.detail_url + '?username='******'&api_key=' + self.api_key, data=json.dumps(self.put_data), content_type="application/json"))
        self.assertEqual(Contributor.objects.count(), 1)
        self.assertEqual(Contributor.objects.get(pk=self.contributor_1.pk).email, self.put_data.get("email"))

    def test_delete_detail_unauthenticated(self):
        """Delete a single user is not allowed from the API without authenticated"""
        self.assertHttpUnauthorized(self.c.delete(self.detail_url))

    def test_delete_detail_without_permission(self):
        """Delete a single user is allowed from the API with authenticated"""
        self.assertEqual(Contributor.objects.count(), 1)
        self.assertHttpUnauthorized(self.c.delete(self.detail_url, self.get_credentials()))
        self.assertEqual(Contributor.objects.count(), 1)

    def test_delete_detail_with_permision(self):
        """Delete a single user is allowed from the API with authenticated"""
        delete_contributor = Permission.objects.get(codename="delete_contributor")
        self.user.user_permissions.add(delete_contributor)
        self.assertEqual(Contributor.objects.count(), 1)
        self.assertHttpAccepted(self.c.delete(self.detail_url, self.get_credentials()))
        self.assertEqual(Contributor.objects.count(), 0)

    def test_check_password(self):
        """Check that the password of the Contributor is right"""
        check_password_url = self.detail_url + "check_password/"
        credentials = self.get_credentials()
        # Check if only authorized can access this url
        self.assertHttpUnauthorized(self.c.get(check_password_url))

        # Test with credentials and wrong password
        credentials_and_wrong_password = credentials
        credentials_and_wrong_password.update({"password": "******"})
        resp = self.c.get(check_password_url, credentials_and_wrong_password)
        self.assertHttpOK(resp)
        self.assertValidJSONResponse(resp)
        self.assertEqual(self.deserialize(resp)['password_valid'], False)

        # Test with credentials and right password
        credentials_and_password = credentials
        credentials_and_password.update({"password": "******"})
        resp = self.c.get(check_password_url, credentials_and_password)
        self.assertHttpOK(resp)
        self.assertValidJSONResponse(resp)
        self.assertEqual(self.deserialize(resp)['password_valid'], True)

        # Update password with put and chek password again
        change_contributor = Permission.objects.get(codename="change_contributor")
        self.user.user_permissions.add(change_contributor)
        self.assertHttpAccepted(self.c.put(self.detail_url + '?username='******'&api_key=' + self.api_key, data=json.dumps({"password": "******"}), content_type="application/json"))

        credentials_and_updated_password = credentials
        credentials_and_updated_password.update({"password": "******"})
        resp = self.c.get(check_password_url, credentials_and_updated_password)
        self.assertHttpOK(resp)
        self.assertValidJSONResponse(resp)
        self.assertEqual(self.deserialize(resp)['password_valid'], True)