def fill_month(days, iterations):
     user = {}
     month = [0] * days
     for i in range(iterations):
         user['_id'] = bson.objectid.ObjectId()
         day = get_day_to_send(user, days)
         month[day] += 1
     return month
Пример #2
0
def preferences(request):
    schema = UserPreferencesSchema()
    button1 = Button('submit', _('Save changes'))
    button1.css_class = 'btn-primary'

    form = Form(schema, buttons=(button1, ))

    today = request.date_service.today()
    # use 28 to get a consistent day_to_send no matter what the
    # current month is. The disadvantage is that there are
    # several days in a regular month that are not used.
    day_to_send = get_day_to_send(request.user, 28)

    if day_to_send > today.day:
        day_to_send_msg = _(
            'You will receive your passwords backup on the day ${day} of this month',
            mapping={'day': day_to_send})
    elif day_to_send < today.day:
        day_to_send_msg = _(
            'You will receive your passwords backup on the day ${day} of next month',
            mapping={'day': day_to_send})
    else:
        day_to_send_msg = _(
            'You will receive your passwords backup today!',
            mapping={'day': day_to_send})

    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = form.validate(controls)
        except ValidationFailure as e:
            return {'form': e.render(), 'day_to_send': day_to_send_msg}

        changes = dict([(pref, appstruct[pref]) for pref in (
                    analytics.USER_ATTR,
                    'send_passwords_periodically',
                    )])

        result = request.db.users.update({'_id': request.user['_id']},
                                         {'$set': changes},
                                         safe=True)

        if result['n'] == 1:
            request.session.flash(
                _('The changes were saved successfully'),
                'success',
                )
            return HTTPFound(location=request.route_path('user_preferences'))
        else:
            request.session.flash(
                _('There were an error while saving your changes'),
                'error',
                )
            return {'form': appstruct, 'day_to_send': day_to_send_msg}

    return {'form': form.render(request.user), 'day_to_send': day_to_send_msg}
    def test_get_day_to_send(self):
        user = {}
        user['_id'] = bson.objectid.ObjectId('000000000000000000000001')
        self.assertEqual(5, get_day_to_send(user, 28))
        self.assertEqual(13, get_day_to_send(user, 30))
        self.assertEqual(6, get_day_to_send(user, 31))

        user['_id'] = bson.objectid.ObjectId('100000000000000000000000')
        self.assertEqual(5, get_day_to_send(user, 28))
        self.assertEqual(13, get_day_to_send(user, 30))
        self.assertEqual(6, get_day_to_send(user, 31))

        user['_id'] = bson.objectid.ObjectId('00000000000000000000000a')
        self.assertEqual(25, get_day_to_send(user, 28))
        self.assertEqual(1, get_day_to_send(user, 30))
        self.assertEqual(23, get_day_to_send(user, 31))
    def test_several_users(self):
        date_joined = datetime.datetime(2012, 12, 12, 12, 12)
        # Add some users
        self.add_passwords(self.db.users.insert({
                    'first_name': 'John1',
                    'last_name': 'Doe',
                    'date_joined': date_joined,
                    'email': '',
                    'email_verified': False,
                    'send_passwords_periodically': False,
                    }), 10)

        i = 1
        while True:
            user_id = self.add_passwords(self.db.users.insert({
                        'first_name': 'John%d' % i,
                        'last_name': 'Doe',
                        'date_joined': date_joined,
                        'email': '*****@*****.**' % i,
                        'email_verified': True,
                        'send_passwords_periodically': True,
                        }), 10)
            day = get_day_to_send({'_id': user_id}, 28)
            if day == 10:
                break

            i += 1

        sys.argv = ['notused', self.conf_file_path]
        sys.stdout = StringIO()
        result = send_backups_via_email()
        self.assertEqual(result, None)
        stdout = sys.stdout.getvalue()
        expected_output = """Passwords sent to John%d Doe <*****@*****.**>
""" % (i, i)
        self.assertEqual(stdout, expected_output)
    def test_user_preferences(self):
        # this view required authentication
        res = self.testapp.get('/preferences')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain('Log in')

        # Log in
        date = datetime.datetime(2012, 12, 12, 12, 12)
        while True:
            user_id = self.db.users.insert({
                'twitter_id': 'twitter1',
                'screen_name': 'John Doe',
                'first_name': 'John',
                'last_name': 'Doe',
                'email': '',
                'email_verified': False,
                'authorized_apps': [],
                'date_joined': date,
                'last_login': date,
                'allow_google_analytics': False,
            },
                                           safe=True)
            day = get_day_to_send({'_id': user_id}, 28)
            # we want a user with a different day from 1
            # since that's a special case and does not
            # allow us to test a future date to send
            # the passwords
            if day != 1:
                break

            # In most cases day will be != 1 so this line
            # only get executed with very low probability
            self.db.users.remove(user_id, safe=True)  # pragma: no cover

        self.set_user_cookie(str(user_id))

        os.environ['YITH_FAKE_DATE'] = '2012-10-30'
        res = self.testapp.get('/preferences')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain(
            'Preferences', 'Allow statistics cookie',
            'You will receive your passwords backup on the day %d of next month'
            % day, 'Save changes')

        os.environ['YITH_FAKE_DATE'] = '2012-10-%d' % max(1, day - 1)
        res = self.testapp.get('/preferences')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain(
            'Preferences', 'Allow statistics cookie',
            'You will receive your passwords backup on the day %d of this month'
            % day, 'Save changes')

        os.environ['YITH_FAKE_DATE'] = '2012-10-%d' % day
        res = self.testapp.get('/preferences')
        self.assertEqual(res.status, '200 OK')
        res.mustcontain('Preferences', 'Allow statistics cookie',
                        'You will receive your passwords backup today',
                        'Save changes')

        res = self.testapp.post(
            '/preferences', {
                'submit': 'Save changes',
                'allow_google_analytics': 'true',
                'send_passwords_periodically': 'false',
            })
        self.assertEqual(res.status, '302 Found')
        self.assertEqual(res.location, 'http://localhost/preferences')
        # check that the user has changed
        new_user = self.db.users.find_one({'_id': user_id})
        self.assertEqual(new_user['allow_google_analytics'], True)
        self.assertEqual(new_user['send_passwords_periodically'], False)

        # make the form fail
        with patch('deform.Form.validate') as fake:
            fake.side_effect = DummyValidationFailure('f', 'c', 'e')
            res = self.testapp.post('/preferences', {
                'submit': 'Save Changes',
            })
            self.assertEqual(res.status, '200 OK')

        # make the db fail
        with patch('yithlibraryserver.db.MongoDB.get_database') as fake:
            fake.return_value = BadDB(new_user)
            res = self.testapp.post(
                '/preferences', {
                    'submit': 'Save changes',
                    'allow_google_analytics': 'true',
                    'send_passwords_periodically': 'false',
                })
            self.assertEqual(res.status, '200 OK')
            res.mustcontain('There were an error while saving your changes')

        del os.environ['YITH_FAKE_DATE']