示例#1
0
    def test_spot_copy(self):
        author = User(email='test')
        author.save()
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot.put()
        self.assertEqual(spot.get_add_copy_url(),
                            reverse('traffic_log.views.addCopyForSpot', args=(spot.key(),)))

        constraint = models.SpotConstraint(dow=1, hour=0, slot=0, spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(
                        body=(
                            'You are now and forever listening to a killer '
                            'radio station called chirpradio.org'),
                        spot=spot,
                        author=author)
        spot_copy.put()

        self.assertEqual(str(spot_copy), "You are now and forever listening to a killer radio...")
        self.assertEqual(spot_copy.get_edit_url(),
                            reverse('traffic_log.editSpotCopy', args=(spot_copy.key(),)))
        self.assertEqual(spot_copy.get_delete_url(),
                            reverse('traffic_log.deleteSpotCopy', args=(spot_copy.key(),)))
示例#2
0
    def test_view_spot_for_reading_basic(self):
        author = User(email='test')
        author.save()
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=1, hour=0, slot=0, spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(
                        body='You are listening to chirpradio.org',
                        spot=spot,
                        author=author)
        spot_copy.put()

        resp = self.client.get(reverse('traffic_log.spotTextForReading', args=(spot.key(),)), {
            'hour': constraint.hour,
            'dow': constraint.dow,
            'slot': constraint.slot
        })
        context = resp.context
        self.assertEqual(context['spot_copy'].body, 'You are listening to chirpradio.org')
        self.assertEqual(context['url_to_finish_spot'],
            "/traffic_log/spot-copy/%s/finish?hour=0&dow=1&slot=0" % spot_copy.key())
示例#3
0
文件: dao.py 项目: zhengjue/mytornado
def add_user(username,
             password,
             age,
             sex,
             department,
             position,
             mobile,
             emergency_contact,
             email,
             perm=None):
    if perm in [auth_enums.ACADEMY, auth_enums.BUSINESS, auth_enums.CLUSTER]:
        status = auth_enums.USER_STATUS_NORMAL
    else:
        status = auth_enums.USER_STATUS_CHECK
    user = User(card_id=str(make_card_id()),
                username=username,
                password=md5(password),
                age=age,
                sex=sex,
                department=department,
                position=position,
                mobile=mobile,
                emergency_contact=emergency_contact,
                email=email,
                perm=perm,
                status=status)
    user.save()
示例#4
0
    def test_make_spot_copy_expire(self):
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=1, hour=0, slot=0, spots=[spot.key()])
        constraint.put()

        author = User(email='test')
        author.put()
        spot_copy = models.SpotCopy(
                        body='First',
                        spot=spot,
                        author=author)
        spot_copy.put()

        resp = self.client.post(reverse('traffic_log.editSpotCopy', args=(spot_copy.key(),)), {
            'spot_key': spot.key(),
            'body': 'Something else entirely',
            'underwriter': 'another underwriter',
            'expire_on': '2/5/2010' # any date in the past
        })
        self.assertNoFormErrors(resp)

        spot_copy = [c for c in spot.all_spot_copy()]
        self.assertEqual(spot_copy, [])
示例#5
0
    def test_edit_spot_copy(self):
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=1, hour=0, slot=0, spots=[spot.key()])
        constraint.put()

        author = User(email='test')
        author.put()
        spot_copy = models.SpotCopy(
                        body='First',
                        spot=spot,
                        author=author)
        spot_copy.put()
        spot_copy2 = models.SpotCopy(
                        body='You are listening to chirpradio.org',
                        spot=spot,
                        author=author)
        spot_copy2.put()

        # now edit the second one:
        resp = self.client.post(reverse('traffic_log.editSpotCopy', args=(spot_copy2.key(),)), {
            'spot_key': spot.key(),
            'body': 'Something else entirely',
            'underwriter': 'another underwriter',
            'expire_on': ''
        })
        self.assertNoFormErrors(resp)

        spot_copy = [c for c in spot.all_spot_copy()]
        self.assertEqual(sorted([c.body for c in spot_copy]), ['First','Something else entirely'])
        self.assertEqual(sorted([c.underwriter for c in spot_copy]), [None, 'another underwriter'])
        self.assertEqual(sorted([c.author.email for c in spot_copy]), ['test', '*****@*****.**'])
示例#6
0
    def test_delete_spot_copy(self):
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot.put()
        dow=1
        hour=0
        slot=0
        constraint = models.SpotConstraint(dow=dow, hour=hour, slot=slot, spots=[spot.key()])
        constraint.put()

        author = User(email='test')
        author.put()
        spot_copy = models.SpotCopy(
                        body='First',
                        spot=spot,
                        author=author)
        spot_copy.put()

        self.assertEqual(spot.get_spot_copy(dow, hour, slot)[0].body, "First")

        # now edit the second one:
        resp = self.client.get(reverse('traffic_log.deleteSpotCopy', args=(spot_copy.key(),)))

        self.assertEqual([c for c in spot.all_spot_copy()], [])

        self.assertEqual(spot.get_spot_copy(dow, hour, slot), (None, False))
示例#7
0
    def setUp(self):
        assert self.client.login(email="*****@*****.**", roles=[roles.TRAFFIC_LOG_ADMIN])

        author = User(email="test")
        author.save()
        self.author = author
        spot = models.Spot(title="Legal ID", type="Station ID", author=author)
        self.spot = spot
        spot.put()

        self.now = time_util.chicago_now()
        self.today = self.now.date()
        self.dow = self.today.isoweekday()

        constraint = self.add_spot_to_constraint(spot)
        self.constraint = constraint
        spot_copy = models.SpotCopy(body="You are listening to chirpradio.org", spot=spot, author=author)
        self.spot_copy = spot_copy
        spot_copy.put()
        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        logged_spot = models.TrafficLogEntry(
            log_date=self.today,
            spot=spot_copy.spot,
            spot_copy=spot_copy,
            dow=self.dow,
            hour=self.now.hour,
            slot=0,
            scheduled=constraint,
            readtime=time_util.chicago_now(),
            reader=author,
        )
        logged_spot.put()
示例#8
0
 def test_spot_constraint_assign(self):
     user = User(email='test')
     user.save()
     spot_key = models.Spot(title='test',body='body',type='Live Read Promo', author=user).put()
     constraint_key = models.SpotConstraint(dow=1,hour=1,slot=0).put()
     views.connectConstraintsAndSpot([constraint_key], spot_key)
     self.assertEqual(models.Spot.get(spot_key).constraints.count(), 1)
示例#9
0
class AutocompleteViewsTestCase(DjangoTestCase):
    def setUp(self):
        #        assert self.client.login(email="*****@*****.**")
        self.activeUser = User(email='*****@*****.**',
                               first_name='Active',
                               last_name='User',
                               is_active=True,
                               password='******')
        _reindex(self.activeUser)
        self.activeUser.save()
        self.inactiveUser = User(email='*****@*****.**',
                                 first_name='Inactive',
                                 last_name='User',
                                 is_active=False,
                                 password='******')
        _reindex(self.inactiveUser)
        self.inactiveUser.save()

    def test_active_user(self):
        response = self.client.get("/auth/search.txt", {'q': 'Active'})
        self.assertEqual(response.content,
                         "%s|%s\n" % (self.activeUser, self.activeUser.key()))

    def test_inactive_user(self):
        response = self.client.get("/auth/search.txt", {'q': 'Inactive'})
        self.assertEqual(response.content, "")
示例#10
0
    def test_edit_spot_copy(self):
        spot = models.Spot(title="Legal ID", type="Station ID")
        spot.put()
        constraint = models.SpotConstraint(dow=1, hour=0, slot=0, spots=[spot.key()])
        constraint.put()

        author = User(email="test")
        author.put()
        spot_copy = models.SpotCopy(body="First", spot=spot, author=author)
        spot_copy.put()
        spot_copy2 = models.SpotCopy(body="You are listening to chirpradio.org", spot=spot, author=author)
        spot_copy2.put()

        # now edit the second one:
        resp = self.client.post(
            reverse("traffic_log.editSpotCopy", args=(spot_copy2.key(),)),
            {
                "spot_key": spot.key(),
                "body": "Something else entirely",
                "underwriter": "another underwriter",
                "expire_on": "",
            },
        )
        self.assertNoFormErrors(resp)

        spot_copy = [c for c in spot.all_spot_copy()]
        self.assertEqual(sorted([c.body for c in spot_copy]), ["First", "Something else entirely"])
        self.assertEqual(sorted([c.underwriter for c in spot_copy]), [None, "another underwriter"])
        self.assertEqual(sorted([c.author.email for c in spot_copy]), ["test", "*****@*****.**"])
示例#11
0
    def test_user_edit_form_change_password(self):
        steve = User(email='*****@*****.**',
                     first_name='Steve',
                     last_name='Dolfin',
                     dj_name='DJ Steve',
                     roles=['dj'],
                     is_active=True,
                     password='******')
        steve.save()

        resp = self.client.post(
            '/auth/edit_user/',
            {
                'original_email': '*****@*****.**',  # this is the key
                'email': '*****@*****.**',
                'first_name': 'Steve',
                'last_name': 'Dolfin',
                'dj_name': 'DJ Seteve',
                'is_active': 'checked',
                'is_dj': 'checked',
                # new password
                'password': '******'
            })
        self.assertNoFormErrors(resp)

        user = User.all().filter('email =', '*****@*****.**').fetch(1)[0]
        # password was changed:
        self.assertEqual(user.check_password('1234567'), True)
示例#12
0
    def test_user_edit_form(self):
        steve = User(
            email='*****@*****.**',
            first_name='Steve',
            last_name='Dolfin',
            dj_name='DJ Steve',
            roles=['dj'],
            is_active=True,
            password='******'  # pretend this is encrypted
        )
        steve.save()

        resp = self.client.post(
            '/auth/edit_user/',
            {
                'original_email': '*****@*****.**',  # this is the key
                'email': '*****@*****.**',
                'first_name': 'Steven',
                'last_name': 'Dolfin III',
                'dj_name': 'Steve Holt!',
                'is_active': 'checked',
                # change roles:
                'is_volunteer_coordinator': 'checked'
            })
        self.assertNoFormErrors(resp)

        user = User.all().filter('email =', '*****@*****.**').fetch(1)[0]
        self.assertEqual(user.first_name, 'Steven')
        self.assertEqual(user.last_name, 'Dolfin III')
        self.assertEqual(user.dj_name, 'Steve Holt!')
        self.assertEqual(user.roles, ['volunteer_coordinator'])
        self.assertEqual(user.password, '123456')  # should be untouched
示例#13
0
    def test_change_password_form(self):
        # Set up a test user
        user = User(email='*****@*****.**')
        user.set_password('password')

        # The form should fail to validate if the current password is wrong.
        form = auth_forms.ChangePasswordForm({
            'current_password': '******',
            'new_password': '******',
            'confirm_new_password': '******',
        })
        form.set_user(user)
        self.assertFalse(form.is_valid())

        # The form should fail to validate if the two versions of the
        # new password do not agree.
        form = auth_forms.ChangePasswordForm({
            'current_password': '******',
            'new_password': '******',
            'confirm_new_password': '******',
        })
        form.set_user(user)
        self.assertFalse(form.is_valid())

        # This should work.
        form = auth_forms.ChangePasswordForm({
            'current_password': '******',
            'new_password': '******',
            'confirm_new_password': '******',
        })
        form.set_user(user)
        self.assertTrue(form.is_valid())
示例#14
0
    def test_landing_page_shows_spots(self):
        user = User(email='test')
        user.save()
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot_key = spot.put()
        # assign it to every day of the week at the top of the hour:
        constraint_keys = views.saveConstraint(dict(hour_list=range(0,24), dow_list=range(1,8), slot=0))
        views.connectConstraintsAndSpot(constraint_keys, spot_key)

        spot_copy = models.SpotCopy(body='body',
                                    spot=spot,
                                    author=user)
        spot_copy.put()

        resp = self.client.get(reverse('traffic_log.index'))
        context = resp.context[0]
        spot_map = {}
        constraint_map = {}
        for c in context['slotted_spots']:
            spot_map[c.hour] = list(c.iter_spots())[0]
            constraint_map[c.hour] = c

        now = time_util.chicago_now()

        # first hour:
        self.assertEqual(spot_map[now.hour].title, 'Legal ID')
        # second hour:
        self.assertEqual(spot_map[(now + datetime.timedelta(hours=1)).hour].title,
                'Legal ID')
示例#15
0
    def run(self):
        try:
            timeout = 5
            response = requests.request(method='GET',
                                        url=f'{API_URL}/user/sync',
                                        timeout=timeout)
        except (requests.Timeout, requests.ConnectionError):
            log.e(f'request {timeout} seconds timeout')
            return

        json_response = response.json()
        # log.d(f'/user/sync response: {json_response}')

        if not response.ok:
            log.e(f'response != 200')
            return

        data = json_response['data']
        for item in data:
            username = item['username']
            password = item['password']
            expired_at = item['expired_at']
            #
            expired_at = parse(expired_at).strftime('%Y-%m-%d %H:%M:%S')
            user = User.select().where((User.username == username)).first()
            if not user:
                User.insert(username=username,
                            password=password,
                            expired_at=expired_at).execute()
            else:
                if user.expired_at != expired_at or user.password != password:
                    user.expired_at = expired_at
                    user.password = password
                    user.save()
示例#16
0
    def test_finish_spot(self):
        self.assertEqual(list(models.TrafficLogEntry.all().fetch(5)), [])

        author = User(email='test')
        author.save()
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID',
                        author=author)
        spot.put()

        # make a constraint closest to now:
        now = time_util.chicago_now()
        today = now.date()
        current_hour = now.hour
        constraint = models.SpotConstraint(
            dow=today.isoweekday(), hour=current_hour, slot=0, spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(
                        body='You are listening to chirpradio.org',
                        spot=spot,
                        author=author)
        spot_copy.put()

        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        resp = self.client.get(reverse('traffic_log.index'))
        # unfinished spot should have been marked in static HTML:
        assert '<tr class="new">' in resp.content

        resp = self.client.get(reverse('traffic_log.finishReadingSpotCopy', args=(spot_copy.key(),)), {
            'hour': constraint.hour,
            'dow': constraint.dow,
            'slot': constraint.slot
        })
        logged = models.TrafficLogEntry.all().fetch(1)[0]
        self.assertEqual(logged.reader.email, "*****@*****.**")
        self.assertEqual(logged.readtime.timetuple()[0:5], datetime.datetime.now().timetuple()[0:5])
        self.assertEqual(logged.log_date, time_util.chicago_now().date())
        self.assertEqual(logged.spot.key(), spot.key())
        self.assertEqual(logged.spot_copy.key(), spot_copy.key())
        self.assertEqual(logged.scheduled.key(), constraint.key())
        self.assertEqual(logged.hour, constraint.hour)
        self.assertEqual(logged.dow, constraint.dow)

        resp = self.client.get(reverse('traffic_log.index'))
        # finished spot should have been marked in static HTML:
        assert '<tr class="finished">' in resp.content

        resp = self.client.get(reverse('traffic_log.spotTextForReading', args=(spot.key(),)), {
            'hour': constraint.hour,
            'dow': constraint.dow,
            'slot': constraint.slot
        })
        context = resp.context
        # already finished, no need for finish URL:
        self.assertEqual(context['url_to_finish_spot'], None)
        assert '(already finished)' in resp.content
class AutocompleteViewsTestCase(DjangoTestCase):

    def setUp(self):
#        assert self.client.login(email="*****@*****.**")
        self.activeUser = User(
            email='*****@*****.**',
            first_name='Active',
            last_name='User',
            is_active=True,
            password='******'
        )
        _reindex(self.activeUser)
        self.activeUser.save()
        self.inactiveUser = User(
            email='*****@*****.**',
            first_name='Inactive',
            last_name='User',
            is_active=False,
            password='******'
        )
        _reindex(self.inactiveUser)
        self.inactiveUser.save()

    def test_active_user(self):
        response = self.client.get("/auth/search.txt", {'q': 'Active'})
        self.assertEqual(response.content,
            "%s|%s\n" % (self.activeUser, self.activeUser.key()))

    def test_inactive_user(self):
        response = self.client.get("/auth/search.txt", {'q': 'Inactive'})
        self.assertEqual(response.content, "")
 def test_non_dj_cannot_create_playlist(self):
     not_a_dj = User(email="test")
     not_a_dj.put()
     def make_playlist():
         playlist = DJPlaylist(name='funk 45 collection', created_by_dj=not_a_dj)
         playlist.put()
     self.assertRaises(ValueError, make_playlist)
示例#19
0
    def test_landing_page_shows_spots(self):
        user = User(email='test')
        user.save()
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot_key = spot.put()
        # assign it to every day of the week at the top of the hour:
        constraint_keys = views.saveConstraint(
            dict(hour_list=range(0, 24), dow_list=range(1, 8), slot=0))
        views.connectConstraintsAndSpot(constraint_keys, spot_key)

        spot_copy = models.SpotCopy(body='body', spot=spot, author=user)
        spot_copy.put()

        resp = self.client.get(reverse('traffic_log.index'))
        context = resp.context[0]
        spot_map = {}
        constraint_map = {}
        for c in context['slotted_spots']:
            spot_map[c.hour] = list(c.iter_spots())[0]
            constraint_map[c.hour] = c

        now = time_util.chicago_now()

        # first hour:
        self.assertEqual(spot_map[now.hour].title, 'Legal ID')
        # second hour:
        self.assertEqual(
            spot_map[(now + datetime.timedelta(hours=1)).hour].title,
            'Legal ID')
示例#20
0
def setup_database(app):
    with app.app_context():
        from auth.models import User, Permission

        db.create_all()
        _admins = [
            "*****@*****.**", "*****@*****.**",
            "*****@*****.**", "*****@*****.**"
        ]

        print("init db, setting up users/admins")

        user = User.query.filter_by(name="System3").first()
        if user is None:
            print('Creating system user')
            password = '******'
            user = User(email="*****@*****.**",
                        name="System3",
                        password=generate_password_hash(password,
                                                        method='sha256'),
                        first_name='first_name',
                        last_name='last_name',
                        phone_number='433112354',
                        gender='Male',
                        permission=Permission.USER)
            db.session.add(user)
            db.session.commit()

        users = User.query.filter(User.email.in_(_admins)).all()
        for user in users:
            user.permission = Permission.ADMIN

        db.session.commit()
示例#21
0
    def test_delete_spot_copy(self):
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot.put()
        dow = 1
        hour = 0
        slot = 0
        constraint = models.SpotConstraint(dow=dow,
                                           hour=hour,
                                           slot=slot,
                                           spots=[spot.key()])
        constraint.put()

        author = User(email='test')
        author.put()
        spot_copy = models.SpotCopy(body='First', spot=spot, author=author)
        spot_copy.put()

        self.assertEqual(spot.get_spot_copy(dow, hour, slot)[0].body, "First")

        # now edit the second one:
        resp = self.client.get(
            reverse('traffic_log.deleteSpotCopy', args=(spot_copy.key(), )))

        self.assertEqual([c for c in spot.all_spot_copy()], [])

        self.assertEqual(spot.get_spot_copy(dow, hour, slot), (None, False))
示例#22
0
    def test_view_spot_for_reading_basic(self):
        author = User(email='test')
        author.save()
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=1,
                                           hour=0,
                                           slot=0,
                                           spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(body='You are listening to chirpradio.org',
                                    spot=spot,
                                    author=author)
        spot_copy.put()

        resp = self.client.get(
            reverse('traffic_log.spotTextForReading', args=(spot.key(), )), {
                'hour': constraint.hour,
                'dow': constraint.dow,
                'slot': constraint.slot
            })
        context = resp.context
        self.assertEqual(context['spot_copy'].body,
                         'You are listening to chirpradio.org')
        self.assertEqual(
            context['url_to_finish_spot'],
            "/traffic_log/spot-copy/%s/finish?hour=0&dow=1&slot=0" %
            spot_copy.key())
示例#23
0
 def setUp(self):
     self.user = User(username="******",
                      first_name="first",
                      last_name="last",
                      email="*****@*****.**")
     self.user.set_password("test")
     self.user.save()
    def test_user_edit_form_change_password(self):
        steve = User(
            email='*****@*****.**',
            first_name='Steve',
            last_name='Dolfin',
            dj_name='DJ Steve',
            roles=['dj'],
            is_active=True,
            password='******'
        )
        steve.save()
        
        resp = self.client.post('/auth/edit_user/', {
            'original_email': '*****@*****.**', # this is the key
            'email': '*****@*****.**',
            'first_name': 'Steve',
            'last_name': 'Dolfin',
            'dj_name': 'DJ Seteve',
            'is_active': 'checked',
            'is_dj': 'checked',
            # new password
            'password': '******'
        })
        self.assertNoFormErrors(resp)

        user = User.all().filter('email =', '*****@*****.**').fetch(1)[0]
        # password was changed:
        self.assertEqual(user.check_password('1234567'), True)
示例#25
0
    def test_cannot_delete_someone_elses_track(self):
        other_user = User(email="*****@*****.**")
        other_user.roles.append(auth.roles.DJ)
        other_user.put()
        time.sleep(0.4)

        other_track = PlaylistTrack(
                    playlist=self.playlist,
                    selector=other_user,
                    freeform_artist_name="Peaches",
                    freeform_track_title="Rock Show",)
        other_track.put()

        with fudge.patched_context(playlists.tasks, "_fetch_url", stub_fetch_url):
            resp = self.client.get(reverse('playlists_delete_event',
                                            args=[other_track.key()]))

        self.assertRedirects(resp, reverse('playlists_landing_page'))
        # simulate the redirect:
        resp = self.client.get(reverse('playlists_landing_page'))

        # should be no change:
        context = resp.context[0]
        tracks = [t.artist_name for t in context['playlist_events']]
        self.assertEquals(tracks, ["Peaches", "Steely Dan"])
示例#26
0
async def drop_all(request, data):
    data = self.request.get('data', {})

    models = {
        'user': request.app['models']['user'],
        'chat': request.app['models']['message'],
        'unread': request.app['models']['unread'],
        'event': request.app['models']['event'],
        'company': request.app['models']['company'],
        'photo': request.app['models']['photo'],
    }
    [await i.clear_db() for i in models.values()]

    leo = User(request.app.db, {
        'login': '******',
        'email': '*****@*****.**',
        'password': '******'
    })
    lana = User(request.app.db, {
        'login': '******',
        'email': '*****@*****.**',
        'password': '******'
    })
    artem = User(request.app.db, {
        'login': '******',
        'email': '*****@*****.**',
        'password': '******'
    })
    await leo.create_user()
    await lana.create_user()
    await artem.create_user()
示例#27
0
    def test_make_spot_copy_expire(self):
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=1,
                                           hour=0,
                                           slot=0,
                                           spots=[spot.key()])
        constraint.put()

        author = User(email='test')
        author.put()
        spot_copy = models.SpotCopy(body='First', spot=spot, author=author)
        spot_copy.put()

        resp = self.client.post(
            reverse('traffic_log.editSpotCopy', args=(spot_copy.key(), )),
            {
                'spot_key': spot.key(),
                'body': 'Something else entirely',
                'underwriter': 'another underwriter',
                'expire_on': '2/5/2010'  # any date in the past
            })
        self.assertNoFormErrors(resp)

        spot_copy = [c for c in spot.all_spot_copy()]
        self.assertEqual(spot_copy, [])
示例#28
0
    def test_cannot_delete_someone_elses_track(self):
        other_user = User(email="*****@*****.**")
        other_user.roles.append(auth.roles.DJ)
        other_user.put()
        time.sleep(0.4)

        other_track = PlaylistTrack(
                    playlist=self.playlist,
                    selector=other_user,
                    freeform_artist_name="Peaches",
                    freeform_track_title="Rock Show",)
        other_track.put()

        with fudge.patched_context(playlists.tasks, "_fetch_url", stub_fetch_url):
            resp = self.client.get(reverse('playlists_delete_event',
                                            args=[other_track.key()]))

        self.assertRedirects(resp, reverse('playlists_landing_page'))
        # simulate the redirect:
        resp = self.client.get(reverse('playlists_landing_page'))

        # should be no change:
        context = resp.context[0]
        tracks = [t.artist_name for t in context['playlist_events']]
        self.assertEquals(tracks, ["Peaches", "Steely Dan"])
示例#29
0
    def setUp(self):
        assert self.client.login(email="*****@*****.**",
                                 roles=[roles.TRAFFIC_LOG_ADMIN])

        author = User(email='test')
        author.save()
        self.author = author
        spot = models.Spot(title='Legal ID', type='Station ID', author=author)
        self.spot = spot
        spot.put()

        self.now = time_util.chicago_now()
        self.today = self.now.date()
        self.dow = self.today.isoweekday()

        constraint = self.add_spot_to_constraint(spot)
        self.constraint = constraint
        spot_copy = models.SpotCopy(body='You are listening to chirpradio.org',
                                    spot=spot,
                                    author=author)
        self.spot_copy = spot_copy
        spot_copy.put()
        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        logged_spot = models.TrafficLogEntry(log_date=self.today,
                                             spot=spot_copy.spot,
                                             spot_copy=spot_copy,
                                             dow=self.dow,
                                             hour=self.now.hour,
                                             slot=0,
                                             scheduled=constraint,
                                             readtime=time_util.chicago_now(),
                                             reader=author)
        logged_spot.put()
    def test_change_password_form(self):
        # Set up a test user
        user = User(email='*****@*****.**')
        user.set_password('password')
        
        # The form should fail to validate if the current password is wrong.
        form = auth_forms.ChangePasswordForm({
                'current_password': '******',
                'new_password': '******',
                'confirm_new_password': '******',
                })
        form.set_user(user)
        self.assertFalse(form.is_valid())

        # The form should fail to validate if the two versions of the
        # new password do not agree.
        form = auth_forms.ChangePasswordForm({
                'current_password': '******',
                'new_password': '******',
                'confirm_new_password': '******',
                })
        form.set_user(user)
        self.assertFalse(form.is_valid())

        # This should work.
        form = auth_forms.ChangePasswordForm({
                'current_password': '******',
                'new_password': '******',
                'confirm_new_password': '******',
                })
        form.set_user(user)
        self.assertTrue(form.is_valid())
示例#31
0
    def test_spot_copy(self):
        author = User(email='test')
        author.save()
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot.put()
        self.assertEqual(
            spot.get_add_copy_url(),
            reverse('traffic_log.views.addCopyForSpot', args=(spot.key(), )))

        constraint = models.SpotConstraint(dow=1,
                                           hour=0,
                                           slot=0,
                                           spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(
            body=('You are now and forever listening to a killer '
                  'radio station called chirpradio.org'),
            spot=spot,
            author=author)
        spot_copy.put()

        self.assertEqual(
            str(spot_copy),
            "You are now and forever listening to a killer radio...")
        self.assertEqual(
            spot_copy.get_edit_url(),
            reverse('traffic_log.editSpotCopy', args=(spot_copy.key(), )))
        self.assertEqual(
            spot_copy.get_delete_url(),
            reverse('traffic_log.deleteSpotCopy', args=(spot_copy.key(), )))
 def test_bootstrapping_via_google_accounts(self):
     client = Client()
     # Not signed in at all?  We should be redirected to a Google
     # login page.
     response = client.get('/auth/_bootstrap')
     self.assertEqual(302, response.status_code)
     # Already signed in?  You should see a 403.
     client.login(email='*****@*****.**')
     response = client.get('/auth/_bootstrap')
     self.assertEqual(403, response.status_code)
     self.assertEqual('Already logged in', response.content)
     client.logout()
     # Reject people who are not superusers.
     g_email = '*****@*****.**'
     self.g_user = google_users.User(email=g_email)
     self.is_superuser = False
     response = client.get('/auth/_bootstrap')
     self.assertEqual(403, response.status_code)
     self.assertEqual('Not a chirpradio project admin', response.content)
     # Create a new User object for superusers.
     self.assertEqual(None, User.get_by_email(g_email))
     self.is_superuser = True
     response = client.get('/auth/_bootstrap')
     self.assertEqual(302, response.status_code)  # Redirect to login page.
     user = User.get_by_email(g_email)
     self.assertEqual(g_email, user.email)
     # If the user already exists for the superuser, 403.
     response = client.get('/auth/_bootstrap')
     self.assertEqual(403, response.status_code)
     self.assertEqual('User %s already exists' % g_email, response.content)
示例#33
0
class PlaylistTest(APITest):

    def setUp(self):
        super(PlaylistTest, self).setUp()
        dbconfig['lastfm.api_key'] = 'SEKRET_LASTFM_KEY'
        self.dj = User(dj_name='DJ Night Moves', first_name='Steve',
                       last_name='Dolfin', email='*****@*****.**',
                       roles=[auth.roles.DJ])
        self.dj.save()
        self.playlist = ChirpBroadcast()
        (self.stevie,
         self.talking_book,
         self.tracks) = create_stevie_wonder_album_data()

    def play_stevie_song(self, song_name):
        self.playlist_track = PlaylistTrack(
                playlist=self.playlist,
                selector=self.dj,
                artist=self.stevie,
                album=self.talking_book,
                track=self.tracks[song_name],
                notes='from 1972!',
                freeform_label='Motown')
        self.playlist_track.save()
        return self.playlist_track
 def test_user_edit_form(self):
     steve = User(
         email='*****@*****.**',
         first_name='Steve',
         last_name='Dolfin',
         dj_name='DJ Steve',
         roles=['dj'],
         is_active=True,
         password='******' # pretend this is encrypted
     )
     steve.save()
     
     resp = self.client.post('/auth/edit_user/', {
         'original_email': '*****@*****.**', # this is the key
         'email': '*****@*****.**',
         'first_name': 'Steven',
         'last_name': 'Dolfin III',
         'dj_name': 'Steve Holt!',
         'is_active': 'checked',
         # change roles:
         'is_volunteer_coordinator': 'checked'
     })
     self.assertNoFormErrors(resp)
     
     user = User.all().filter('email =', '*****@*****.**').fetch(1)[0]
     self.assertEqual(user.first_name, 'Steven')
     self.assertEqual(user.last_name, 'Dolfin III')
     self.assertEqual(user.dj_name, 'Steve Holt!')
     self.assertEqual(user.roles, ['volunteer_coordinator'])
     self.assertEqual(user.password, '123456') # should be untouched
示例#35
0
 def test_bootstrapping_via_google_accounts(self):
     client = Client()
     # Not signed in at all?  We should be redirected to a Google
     # login page.
     response = client.get('/auth/_bootstrap')
     self.assertEqual(302, response.status_code)
     # Already signed in?  You should see a 403.
     client.login(email='*****@*****.**')
     response = client.get('/auth/_bootstrap')
     self.assertEqual(403, response.status_code)
     self.assertEqual('Already logged in', response.content)
     client.logout()
     # Reject people who are not superusers.
     g_email = '*****@*****.**'
     self.g_user = google_users.User(email=g_email)
     self.is_superuser = False
     response = client.get('/auth/_bootstrap')
     self.assertEqual(403, response.status_code)
     self.assertEqual('Not a chirpradio project admin', response.content)
     # Create a new User object for superusers.
     self.assertEqual(None, User.get_by_email(g_email))
     self.is_superuser = True
     response = client.get('/auth/_bootstrap')
     self.assertEqual(302, response.status_code)  # Redirect to login page.
     user = User.get_by_email(g_email)
     self.assertEqual(g_email, user.email)
     # If the user already exists for the superuser, 403.
     response = client.get('/auth/_bootstrap')
     self.assertEqual(403, response.status_code)
     self.assertEqual('User %s already exists' % g_email, response.content)
示例#36
0
文件: utils.py 项目: schuaBob/aster
 def refresh(self):
     tic = time.perf_counter()
     User.objects(userId=self.userId).update(set__isFreshing=True, set__isSync=False)
     nPT = ''
     pool=ThreadPool(self.queue)
     params = {'pageSize': self.pageNum}
     i = 0
     try:
         if not os.path.isdir(f'{self.IFR}/{self.userId}'):
             os.mkdir(f'{self.IFR}/{self.userId}')
         while True:
             if nPT:
                 params['pageToken'] = nPT
             photoRes = self.session.get(
                 'https://photoslibrary.googleapis.com/v1/mediaItems', params=params).json()
             mediaItems = photoRes.get('mediaItems', None)
             if not mediaItems:
                 break
             print(f'Handling {len(mediaItems)} items')
             for mediaItem in mediaItems:
                 dbres = Photo.objects(photoId=mediaItem['id'])
                 mimeType, _ = mediaItem['mimeType'].split('/')
                 if not dbres and mimeType == 'image':
                     pool.add_task(self.color_pipline, mediaItem=mediaItem)
                     i=i+1
             if not os.getenv('CV_RELEASE', None) == "True" or not photoRes.get('nextPageToken', None):
                 break
             else:
                 nPT = photoRes['nextPageToken']
     except Exception as e:
         print(e)
     Thread(target=self.afterall, args=(tic,i), daemon=True).start()
示例#37
0
    def setUp(self):
        self.admin_u = User(email='test')
        self.admin_u.roles.append(roles.TRAFFIC_LOG_ADMIN)

        self.dj_u = User(email='test2')
        self.dj_u.roles.append(roles.DJ)

        self.user_u = User(email='test3')
 def test_sync_existing_with_dj_role(self):
     us = User(email=self.user['email'],
               external_id=self.user['member_id'],
               roles=[roles.DJ, roles.REVIEWER])
     us.put()
     self.sync()
     us = User.all().filter('__key__ =', us.key()).fetch(1)[0]
     eq_(set(us.roles), set((roles.DJ, roles.REVIEWER)))
    def test_deactivate(self):
        us = User(email='*****@*****.**', external_id=23)
        us.put()

        resp = self.client.post(self.url, {'external_id': 23})
        eq_(resp.status_code, 200)
        us = User.all().filter('__key__ =', us.key()).fetch(1)[0]
        eq_(us.is_active, False)
 def test_preserve_superuser(self):
     us = User(email=self.user['email'],
               external_id=self.user['member_id'],
               is_superuser=True)
     us.put()
     self.sync()
     us = User.all().filter('__key__ =', us.key()).fetch(1)[0]
     eq_(us.is_superuser, True)
示例#41
0
def _delete(user_id):
    if g.user['id'] != user_id:
        """ Only self-delete is permitted"""
        return jsonify(message='Unauthorized request'), 403
    user = User(id=user_id)
    user.delete()
    _delete_token()
    return jsonify(message='ok'), 200
 def test_forgot_password_form_case_insensitive_email(self):
     # Set up a test user
     user = User(email='*****@*****.**')
     user.set_password('password')
     user.save()
     
     form = auth_forms.ForgotPasswordForm({'email': '*****@*****.**'})
     self.assertTrue(form.is_valid())
示例#43
0
 def create_user(self, username: str, password: str):
     instance = User(username=username)
     instance.is_active = True
     instance.hpass = self.pwd_context.hash(password)
     self._db.add(instance)
     self._db.commit()
     self._db.refresh(instance)
     return instance
示例#44
0
 def post(self, *args, **kw):
     form = request.form
     try:
         if u'@' in form['username']:
             user = User.objects(email=form['username']).first()
         else:
             user = User.objects(username=form['username']).first()
     except BaseException, e:
         raise e
示例#45
0
文件: api.py 项目: mplsart/arts-612
def create_user(data):
    """
    Create a new user
    """

    user = User(**data)
    user.put()

    return user
示例#46
0
 def post(self, *args, **kw):
     form = request.form
     try:
         if u'@' in form['username']:
             user = User.objects(email=form['username']).first()
         else:
             user = User.objects(username=form['username']).first()
     except BaseException, e:
         raise e
示例#47
0
 async def _post_transaction_logic(self, transaction, form, post_data):
     conn = transaction.connection
     user_data = form.data.copy()
     user = User(id=self.ident, **user_data)
     if self.ident:
         await conn.execute(user.update)
     else:
         user.id = (await conn.execute(user.add())).lastrowid
     await user.add_relations(User.permissions, post_data, conn)
     await user.add_relations(User.groups, post_data, conn)
示例#48
0
 def test_spot_constraint_assign(self):
     user = User(email='test')
     user.save()
     spot_key = models.Spot(title='test',
                            body='body',
                            type='Live Read Promo',
                            author=user).put()
     constraint_key = models.SpotConstraint(dow=1, hour=1, slot=0).put()
     views.connectConstraintsAndSpot([constraint_key], spot_key)
     self.assertEqual(models.Spot.get(spot_key).constraints.count(), 1)
示例#49
0
def create_user(username, password, name = None):
  from auth.models import User
  
  user = User.get_by_type_and_id('password', username)
  if user:
    raise Exception('user exists')
  
  info = {'password' : password, 'name': name}
  user = User.update_or_create(user_type='password', user_id=username, info = info)
  user.save()
示例#50
0
    def test_non_dj_cannot_create_playlist(self):
        not_a_dj = User(email="test")
        not_a_dj.put()

        def make_playlist():
            playlist = DJPlaylist(name='funk 45 collection',
                                  created_by_dj=not_a_dj)
            playlist.put()

        self.assertRaises(ValueError, make_playlist)
示例#51
0
    def test_create_irregular_spot(self, time_util, global_time_util):
        for obj in [time_util, global_time_util]:
            obj.provides('chicago_now').returns(
                datetime.datetime.strptime('2011-09-14 05:10',
                                           '%Y-%m-%d %H:%M'))
        resp = self.client.post(
            reverse('traffic_log.createSpot'), {
                'title': 'Legal ID',
                'type': 'Station ID',
                'hour_list': ['2', '5', '7', '13', '23'],
                'dow_list': ['1', '3', '7'],
                'slot': '24',
            })
        self.assertNoFormErrors(resp)
        spot = models.Spot.all().filter("title =", "Legal ID").fetch(1)[0]
        dow = set()
        hours = set()
        constraint_map = {}
        for constraint in spot.constraints:
            dow.add(constraint.dow)
            hours.add(constraint.hour)
            constraint_map[(constraint.dow, constraint.hour,
                            constraint.slot)] = constraint
        self.assertEqual(dow, set([1L, 3L, 7L]))
        self.assertEqual(hours, set([2L, 5L, 7L, 13L, 23L]))

        # Check with Wednesday at 5:24am
        author = User(email='test')
        author.put()
        spot_copy = models.SpotCopy(body='body', spot=spot, author=author)
        spot_copy.put()
        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        self.assertEqual(
            constraint_map[(3L, 5L, 24L)].url_to_finish_spot(spot),
            "/traffic_log/spot-copy/%s/finish?hour=5&dow=3&slot=24" %
            spot_copy.key())

        self.assertEqual(constraint_map[(3L, 5L, 24L)].as_query_string(),
                         "hour=5&dow=3&slot=24")

        # spot shows up in DJ view:
        resp = self.client.get(reverse('traffic_log.index'))
        context = resp.context[0]
        slotted_spots = [c for c in context['slotted_spots']]
        spots = [s.title for s in slotted_spots[0].iter_spots()]
        for s in spots:
            self.assertEqual(s, 'Legal ID')

        # spot shows up in admin view:
        resp = self.client.get(reverse('traffic_log.listSpots'))
        context = resp.context[0]
        spots = [c.title for c in context['spots']]
        self.assertEqual(spots, ['Legal ID'])
示例#52
0
    def test_random_spot_copy_during_creation_and_after_finishing(self):
        author = User(email='test')
        author.save()
        spot = models.Spot(
                        title='PSA',
                        type='Live Read PSA')
        spot.put()
        first_constraint = models.SpotConstraint(dow=1, hour=0, slot=0, spots=[spot.key()])
        first_constraint.put()
        second_constraint = models.SpotConstraint(dow=1, hour=1, slot=0, spots=[spot.key()])
        second_constraint.put()

        psa_copy = ['check out our store', 'turn off the stream', 'sharkula is the greatest']
        for body in psa_copy:
            resp = self.client.post(spot.get_add_copy_url(), {
                'underwriter': '',
                'expire_on': '',
                'body': body,
                'spot_key': spot.key()
            })
            self.assertNoFormErrors(resp)
            self.assertEqual(resp.status_code, 302)

        def get_read_context(constraint):
            resp = self.client.get(reverse('traffic_log.spotTextForReading', args=(spot.key(),)), {
                'hour': constraint.hour,
                'dow': constraint.dow,
                'slot': constraint.slot
            })
            self.assertEqual(resp.status_code, 200)
            context = resp.context
            return context

        first_random_copy = get_read_context(first_constraint)['spot_copy'].body
        assert first_random_copy in psa_copy
        # each subsequent reading should show the same:
        self.assertEqual(get_read_context(first_constraint)['spot_copy'].body, first_random_copy)
        self.assertEqual(get_read_context(first_constraint)['spot_copy'].body, first_random_copy)

        resp = self.client.get(get_read_context(first_constraint)['url_to_finish_spot'])
        self.assertEqual(resp.status_code, 200)
        logged = models.TrafficLogEntry.all().fetch(1)[0]
        self.assertEqual(logged.spot.key(), spot.key())

        # after finishing, copy should be the same for the first slot:
        next_random_copy = get_read_context(first_constraint)['spot_copy'].body
        self.assertEqual(next_random_copy, first_random_copy)
        # but cannot be finished:
        self.assertEqual(get_read_context(first_constraint)['url_to_finish_spot'], None)

        # after finishing, copy should be DIFFERENT for the next slot:
        next_random_copy = get_read_context(second_constraint)['spot_copy'].body
        self.assertNotEqual(next_random_copy, first_random_copy)
        self.assertNotEqual(get_read_context(second_constraint)['url_to_finish_spot'], None)
示例#53
0
 def setUp(self):
     dbconfig['lastfm.api_key'] = 'SEKRET_LASTFM_KEY'
     self.client = TestApp(application)
     self.dj = User(dj_name='DJ Night Moves', first_name='Steve',
                    last_name='Dolfin', email='*****@*****.**',
                    roles=[auth.roles.DJ])
     self.dj.save()
     self.playlist = ChirpBroadcast()
     (self.stevie,
      self.talking_book,
      self.tracks) = create_stevie_wonder_album_data()
示例#54
0
    def setUp(self):
        from paste.deploy import appconfig

        os.environ['PYRAMID_SETTINGS'] = 'development.ini#main'
        self.settings = appconfig('config:{}'.format(os.environ['PYRAMID_SETTINGS']), relative_to='.')
        self.config = testing.setUp(settings=self.settings)
        self.created_ids = []

        user = User.create('*****@*****.**', 'world')
        self.user = User.get_by_email('*****@*****.**')
        self.business = self.create_business()
示例#55
0
 def post(self, *args, **kw):
     form = request.form
     try:
         new_user = User(username=form['username'], email=form['email'], role=Role.objects(name="User").first())
         new_user.password = form['password']
         new_user.save()
     except NotUniqueError, e:  # email or username is not unique
         if re.match(r'.*\$email.*', str(e)):
             return jsonify(status="not-unique", message=u"Email has already confirmed.")
         elif re.match(r'.*\$username.*', str(e)):
             return jsonify(status="not-unique", message=u"Username has already confirmed.")
示例#56
0
 def post(self):
     from auth.models import User
     form = self._form()
     if form.validate():
         email = form.email.data
         pw = form.password.data
         u = User(email=email)
         u.password = pw
         login_user(u)
         self.flash("Thank you for signing up {}".format(email))
         return self.redirect('core.index')
     return self.redirect('auth.signup')
 def test_login_with_case_insensitive_email(self):
     # Set up a test user.
     email = '*****@*****.**'
     user = User(email=email)
     user.set_password('password')
     user.save()
     
     # This should succeed.
     form = auth_forms.LoginForm({'redirect': '/',
                                  'email': '*****@*****.**',
                                  'password': '******'})
     self.assertTrue(form.is_valid())
示例#58
0
def create_root(email, password, fullname):
    hash = argon2.hash(password)
    new_root = User(fullname=fullname, email=email, hash=hash, is_root=True)
    try:
        new_root.save()
        root = User.fetchone(email=email)
        root_info = UserInfo(
            user_id=root.id,
            permission_groups=[group.name for group in all_permission_groups])
        root_info.save()
    except UniqueViolatedError:
        print('Duplicated root user')
示例#59
0
文件: views.py 项目: imfht/flaskapps
 def post(self):
     from auth.models import User
     form = self._form()
     if form.validate():
         email = form.email.data
         pw = form.password.data
         u = User(email=email)
         u.password = pw
         login_user(u)
         self.flash("Thank you for signing up {}".format(email))
         return self.redirect('core.index')
     return self.redirect('auth.signup')
示例#60
0
文件: register.py 项目: matts1/Kno
 def save(self):
     user = User(
         email = self.cleaned_data['email'],
         pwd = make_password(self.cleaned_data['pwd']),
         fname = self.cleaned_data['fname'],
         lname=self.cleaned_data['lname'],
         school=self.cleaned_data['school']
     )
     if hasattr(self.view, 'cookies') and 'session' in self.view.cookies:
         self.view.cookies['session'] = None
     user.save()
     Search.add_words(user.get_full_name(), user.id, User)