示例#1
0
    def test_distinct_activity(self):
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             owner=self.user)

        self.object_client = models.Client(name='test1',
                                           loyal=True,
                                           owner=self.user)

        self.object_contact.save()
        self.object_client.save()

        self.object = models.Activity(title='test',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client,
                                      owner=self.user)
        self.object1 = models.Activity(title='test',
                                       text='test',
                                       contact=self.object_contact,
                                       client=self.object_client)

        self.object.save()
        self.object1.save()

        #Недоступность активности без аутентификации
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 1}))
        self.assertIn("You don't have rights to view this activity",
                      response.content)
        self.assertNotIn('activity', response.context)

        response = self.client.get(reverse('crm:activity', kwargs={'pk': 2}))
        self.assertIn("You don't have rights to view this activity",
                      response.content)
        self.assertNotIn('activity', response.context)

        #Попытка обращения к несуществующей активности без аутентификации
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 3}))
        self.assertTrue(response.content.startswith('<h1>Not Found</h1>'))

        self.client.login(username='******', password='******')
        #Успешная попытка получения информации о активносте принадлежащем пользователю
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 1}))
        self.assertNotIn("You don't have rights to view this activity",
                         response.content)
        self.assertIn('activity', response.context)

        #Не успешная попытка получения информации об активности не принадлежащей пользователю
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 2}))
        self.assertIn("You don't have rights to view this activity",
                      response.content)
        self.assertNotIn('activity', response.context)

        #Попытка обращения к несуществующей активности с аутентификацией
        response = self.client.get(reverse('crm:activity', kwargs={'pk': 3}))
        self.assertTrue(response.content.startswith('<h1>Not Found</h1>'))
示例#2
0
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('testuser', '*****@*****.**',
                                             'testpass')
        self.user1 = User.objects.create_user('testuser1', '*****@*****.**',
                                              'testpass1')
        self.client.login(username='******', password='******')

        self.object_client = models.Client(name='test1',
                                           loyal=True,
                                           owner=self.user)
        self.object_client.save()

        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             client=self.object_client,
                                             owner=self.user)
        self.object_contact.save()

        self.object_activity = models.Activity(title='test',
                                               text='test',
                                               contact=self.object_contact,
                                               client=self.object_client,
                                               owner=self.user)
        self.object_activity.save()
示例#3
0
def create_activities():
    """create and commit entries to the activity table"""
    user_id = get_admin_id()
    activities = []

    new_activity = Activity("swimming", "/static/img/waves-icon.svg", user_id)
    activities.append(new_activity)

    new_activity = Activity("movies", "/static/img/popcorn-and-soda-icon.svg",
                            user_id)
    activities.append(new_activity)

    new_activity = Activity("outdoors", "/static/img/tree-icon.svg", user_id)
    activities.append(new_activity)

    new_activity = Activity("running", "/static/img/sun-icon.svg", user_id)
    activities.append(new_activity)

    new_activity = Activity("music", "/static/img/music-note-icon.svg",
                            user_id)
    activities.append(new_activity)

    new_activity = Activity("BBQ", "/static/img/burger-icon.svg", user_id)
    activities.append(new_activity)

    for activity in activities:
        message = "create_activities(): {}".format(activity)
        with db_session(message) as db:
            new_activity = models.Activity(name=activity.name,
                                           icon=activity.icon,
                                           user_id=activity.user_id)
            db.add(new_activity)
            db.commit()
示例#4
0
文件: views.py 项目: jamcalmon/logger
def start_activity():
    description = request.form['description']
    uid = request.form['user_id']
    if not check_auth(uid):
        return abort(403)
    # Check if user already has an activity underway
    activity_check = models.Activity.query.filter_by(user_id=uid).filter_by(
        current=True).first()
    if activity_check is not None:
        abort(400)
    # Create activity object
    activity = models.Activity()
    activity.description = description
    activity.current = True
    start_time = datetime.utcnow()
    activity.start_time = start_time
    activity.user_id = uid
    # Save activity
    db.session.add(activity)
    db.session.commit()
    # Create activity JSON
    json_activity = {}
    json_activity['description'] = activity.description
    json_activity['start'] = start_time
    return jsonify(json_activity)
    def add_activity(self, request):
        ''' add activity '''
        current_user = endpoints.get_current_user()
        if current_user is None:
            raise endpoints.UnauthorizedException('Invalid token.')

        user = models.User.query(models.User.account == current_user).get()
        try:
            user_key = user.key
        except AttributeError:
            # User does not exist
            return request_messages.StatusMessage(
                status=request_messages.Status.BAD_DATA)

        activity = models.Activity(activity_id=request.activity_id,
                                   lat=request.lat,
                                   lng=request.lng,
                                   parent=user_key)
        if request.user_created_description:
            activity.user_created_description = request.user_created_description

        activity.put()

        return request_messages.StatusMessage(
            status=request_messages.Status.OK)
def outdoor_activity(country_name):
    url = "https://trailapi-trailapi.p.rapidapi.com/"
    headers = {
        'x-rapidapi-host': "trailapi-trailapi.p.rapidapi.com",
        'x-rapidapi-key': "2bc8488dedmsh09812c800fb6b89p19fb19jsn6987dc57cdda"
    }
    querystring = {
        "q-activities_activity_type_name_eq": "hiking",
        "radius": "100000",
        "q-country_cont": "Egypt",
        "limit": "25"
    }
    resp = requests.request("GET", url, headers=headers, params=querystring)
    json_body = resp.json()

    au = json_body["places"][0]["country"]
    au_activity = json_body["places"][0]["activities"][0]["activity_type_name"]
    us = json_body["places"][1]["country"]
    us_activity = json_body["places"][1]["activities"][0]["activity_type_name"]
    ca = json_body["places"][18]["country"]
    ca_activity = json_body["places"][18]["name"]

    if country_name == au:
        outdoor_response = "In {}, you should check out the activity- {}".format(
            country_name, au_activity)
        new_message = models.Activity(au_activity)
        models.db.session.add(new_message)
        models.db.session.commit()
    elif country_name == ca:
        outdoor_response = "In {}, you should walk in a place called- {}".format(
            country_name, ca_activity)
        new_message = models.Activity(ca_activity)
        models.db.session.add(new_message)
        models.db.session.commit()
    elif country_name == us:
        outdoor_response = "In the {}, you should check out the activity- {}".format(
            country_name, us_activity)
        new_message = models.Activity(us_activity)
        models.db.session.add(new_message)
        models.db.session.commit()
    else:
        outdoor_response = "Invalid country input! Please try 'Australia', 'Canada', or 'United States'."

    return (outdoor_response)
示例#7
0
    def test_delete_client(self):
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             client=self.object_client,
                                             owner=self.user)
        self.object_contact.save()

        self.object = models.Activity(title='test',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client,
                                      owner=self.user)
        self.object.save()

        #Неуспешное удаление, есть активность
        initial_data = {'action': 'Delete'}
        self.assertRaises(ProtectedError,
                          self.client.post,
                          path=reverse('crm:client', kwargs={'pk': 1}),
                          data=initial_data)

        #Создаем еще клиента
        self.object_client1 = models.Client(name='test1',
                                            loyal=True,
                                            owner=self.user)
        self.object_client1.save()

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Пробуем удалить - неуспешно, не клиент текущего пользователя
        data_correct_input = {'action': 'Delete'}
        response = self.client.post(reverse('crm:client', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:client', kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)
        self.assertTrue(models.Client.objects.get(pk=2))

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Успешное удаление
        initial_data = {'action': 'Delete'}
        response = self.client.post(reverse('crm:client', kwargs={'pk': 2}),
                                    initial_data)

        self.assertEqual(
            self.client.session['deleted_data'],
            'Name: test1, Id: 2')  #Проверяем, что сохранили информацию
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('crm:main'))
        self.assertEqual(models.Client.objects.count(), 1)
示例#8
0
 def post(self):
     newActivity = models.Activity()
     newActivity.id = generateId()
     newActivity.title = self.request.get("title")
     newActivity.creator = getCurrentLoggedInUser(self)
     newActivity.program = self.request.get("program")
     newActivity.cohort = self.request.get("cohort")
     newActivity.type = self.request.get("type")
     newActivity.desc = self.request.get("desc")
     newActivity.time_slots = int(self.request.get("time_slots"))
     newActivity.status = "IN_REPOSITORY"
     newActivity.put()
     self.response.write("activity saved")
示例#9
0
    def setUp(self):
        self.object_client = models.Client(name='test', loyal=False)
        self.object_client.save()
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             client=self.object_client)
        self.object_contact.save()

        self.object = models.Activity(title='test',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client)
        self.object.save()
示例#10
0
def create_activity(db: Session, activity: schemas.Activity):
    try:
        db_activity = models.Activity(title=activity.title,
                                      description=activity.description,
                                      category=activity.category,
                                      due_date=activity.due_date,
                                      user_id=activity.user_id)
        db.add(db_activity)
        db.commit()
        db.refresh(db_activity)
        return db_activity

    except Exception as e:
        print(e)
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
                            detail="Unexpected Error Occurred")
示例#11
0
 def post(self):
     newActivity = models.Activity()
     newActivity.id = generateId()
     newActivity.title = self.request.get("title")
     newActivity.creator = getCurrentLoggedInUser(self)
     newActivity.program = self.request.get("program")
     newActivity.cohort = self.request.get("cohort")
     newActivity.type = self.request.get("type")
     newActivity.desc = self.request.get("desc")
     newActivity.time_slots = int(self.request.get("time_slots"))
     newActivity.status = "IN_REPOSITORY"
     newActivity.put()
     template = jinja_environment.get_template(
         '/templates/repository_activity.html')
     context = {}
     context["activity"] = newActivity
     self.response.write(template.render(context))
示例#12
0
    def get(self):
        activities = [{
            "title": "dan",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "tzvi",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "hilly",
            "type": "ASSIGNMENT",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "gilad",
            "type": "EXERCISE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "shai",
            "type": "EXERCISE",
            "desc": "something...",
            "time_slots": 1
        }, {
            "title": "dana",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 1
        }]

        for a in activities:
            newActivity = models.Activity()
            newActivity.id = generateId()
            newActivity.title = a['title']
            newActivity.creator = getCurrentLoggedInUser(self)
            newActivity.program = "bootcamp"
            newActivity.cohort = "winter 2015"
            newActivity.type = a['type']
            newActivity.desc = a['desc']
            newActivity.time_slots = a['time_slots']
            newActivity.status = "IN_REPOSITORY"
            newActivity.put()
示例#13
0
def issueAdoptPetInfo(data):
    EVENT_STATUS = 0
    ADOPT = 1
    userId = data.get("user_id")
    user = models.User.objects.filter(user_id=userId).first()
    if not user:
        return util.errorJsonWrapper("不存在该用户")

    # check token by stanwu
    token = data.get("user_token")
    if token != user.user_token:
        return util.errorJsonWrapper("token错误")

    activityPic = data.get("activity_picture")
    activityIntro = data.get("activity_introduction")
    activityAddr = data.get("activity_address")
    activityLongi = data.get("activity_longitude")
    activityLati = data.get("activity_latitude")
    activityPet = data.get("activity_pet_type")
    activityPrice = data.get("activity_price")
    activityStartTime = data.get("activity_start_time")
    activityEndTime = data.get("activity_end_time")

    try:
        activity = models.Activity(activity_introduction=activityIntro,
                                   activity_picture=activityPic,
                                   activity_price=activityPrice,
                                   activity_pet_type=activityPet,
                                   activity_start_time=activityStartTime,
                                   activity_end_time=activityEndTime,
                                   activity_status=EVENT_STATUS,
                                   activity_address=activityAddr)
        activity.save()
    except Exception:
        return util.errorJsonWrapper("发布收养信息出错,activity无法写入数据库")

    try:
        participant = models.Participant(participant_user=user,
                                         participant_activity=activity,
                                         participant_user_type=ADOPT)
        participant.save()
    except Exception:
        return util.errorJsonWrapper("发布收养信息出错,participant无法写入数据库")

    return util.simpleOkJsonWrapper()
示例#14
0
    def test_activities(self):
        self.object_contact = models.Contact(first_name='test1',
                                             last_name='test',
                                             email='*****@*****.**',
                                             phone='123',
                                             owner=self.user)

        self.object_client = models.Client(name='test1',
                                           loyal=True,
                                           owner=self.user)

        self.object_contact.save()
        self.object_client.save()

        self.object = models.Activity(title='test1',
                                      text='test',
                                      contact=self.object_contact,
                                      client=self.object_client,
                                      owner=self.user)

        self.object.save()

        #Проверка доступности активности без аутентификации
        response = self.client.get(reverse('crm:activities'))
        self.assertIn('No activities are available', response.content)
        self.assertNotIn('test1', response.content)
        self.assertFalse(response.context['activities_list'])

        #Недоступность чужих активностей
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('crm:activities'))
        self.assertIn('No activities are available', response.content)
        self.assertFalse(response.context['activities_list'])

        #Доступность своей активности
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('crm:activities'))
        self.assertNotIn('No activities are available', response.content)
        self.assertIn('test1', response.content)
        self.assertTrue(response.context['activities_list'])
示例#15
0
s = Session()
#%%
u = models.User(lms_user='******', is_prof=True, token='alks')
s.add(u)
s.commit()
# %%
print(sess.query(models.User).all())

# %%

u = s.query(models.User).first()

c = models.Course(name='test', responsible=u)
s.add(c)
s.commit()

# %%

a = models.Activity(course_specific_id='at1', course=c)
s.add(a)
s.commit()

#%%
u2 = models.User(lms_user='******', is_prof=False, token='alks2')
s.add(u2)
sub = models.Submission(sender_id=u2.id, activity_id=a.id, content='sdlkfjsdlfsdlfjsdkl')
s.add(sub)
s.commit()
# %%
示例#16
0
def add_activity(activity_name: str):
    activity_row = models.Activity(name=activity_name)
    models.db.session.add(activity_row)
    models.db.session.commit()

    return activity_row
示例#17
0
    async def notify_yt_act(self):
        # this will notify about new activites on a yt channel
        # ->
        # notify all guilds that are following this yt channel
        #
        try:
            start_time = datetime.now()

            seq = random.getrandbits(32)  # generate sequence id

            s = self.db.Session()

            # get all youtube channels we need to follow
            ytchannels = s.query(models.Youtube) \
                .filter(models.Youtube.valid == 1)

            if ytchannels is None:
                # there are no yt channels at all configured,
                # skip look
                logging.debug(f"notify_yt_goals-{seq} no yt channels to " +
                              "follow, skipping loop")
                return

            # query all activities for channel
            for ytchannel in ytchannels:
                # query channel statistics
                yta = self.bot.youtube \
                    .get_activities_detailed(ytchannel.ytchannel_id)

                # if we don't get any activities for any reason,
                # continue with the next channel ...
                if yta is None:
                    logging.error(
                        "notify_yt_act: " +
                        f"error for channel-{ytchannel.ytchannel_id}," +
                        "skipping this channel and move to next"
                    )

                    # update all activities with seq id + datetime
                    s.query(models.Activity) \
                        .filter(
                            models.Activity.youtube_id == ytchannel.id
                        ) \
                        .update({
                            models.Activity.last_sequence: seq
                        })

                    continue

                # check if we have queried this channel before
                if ytchannel.last_seen is None:
                    # we didn't query this channel before, insert
                    # everything in db and do nothing...
                    for a in yta:
                        new_activity = models.Activity(
                            id=a.get('id'),
                            youtube_id=ytchannel.id,
                            last_sequence=seq
                        )
                        s.add(new_activity)

                    s.commit()

                else:
                    # we have queried this channel before, check
                    # if the activities are in db
                    for a in yta:
                        if s.query(
                            exists()
                            .where(
                                models.Activity.id == a.get('id')
                                )).scalar():
                            # we have already seen this activity
                            # update seq id
                            s.query(models.Activity) \
                                .filter(
                                    models.Activity.id == a.get('id')
                                ) \
                                .update(
                                    {models.Activity.last_sequence: seq}
                                )
                        else:
                            # we have not seen this activity
                            # this is a new activity we need to
                            # send a notification for...
                            new_activity = models.Activity(
                                id=a.get('id'),
                                youtube_id=ytchannel.id,
                                last_sequence=seq
                            )
                            s.add(new_activity)

                            # we need to notify all guilds, that are
                            # following this youtube channel about this
                            # new activity!
                            for result in s.query(
                                        models.Guild,
                                        models.YoutubeFollow
                                    ) \
                                .filter(
                                    models.YoutubeFollow.guild_id ==
                                    models.Guild.id,
                                    models.YoutubeFollow.youtube_id ==
                                    ytchannel.id,
                                    models.YoutubeFollow.monitor_videos ==
                                    1,
                                    ).all():

                                # get the channel id where notification
                                # should be sent to
                                nc = result.Guild.notify_channel_id

                                # get the role that should be notified
                                nr_id = result.Guild.notify_role_id
                                nr = self.bot.get_guild(
                                    result.Guild.id
                                ).get_role(
                                    nr_id
                                ).mention

                                if nc is None:
                                    # if no notification channel is set,
                                    # send
                                    # this to the guilds system channel
                                    c = self.bot.get_guild(
                                        result.Guild.id
                                    ).system_channel
                                else:
                                    c = self.bot.get_channel(nc)

                                # send notification message to channel
                                await c.send(
                                    f"Hey {nr}, there is a new youtube video: "
                                    f"{a.get('url')}"
                                )

                # clean up task
                s.query(models.Youtube) \
                    .filter(
                        models.Youtube.id == ytchannel.id
                    ) \
                    .update({
                        models.Youtube.last_seen: datetime.now()
                    })

                s.commit()

            # clean up orphaned entires
            oe = s.query(
                models.Activity
            ).filter(
                models.Activity.last_sequence != seq
            )
            oe.delete()

            s.commit()
            s.close()

            run_time = datetime.now() - start_time
            logging.info(f"telemetry: notify_yt_act took {run_time}s")

        except Exception as e:
            run_time = datetime.now() - start_time
            logging.error(f"notify_yt_act failed because of: {e} {run_time}s")
            s.rollback()
            s.close()
示例#18
0
def issueAdoptPetInfo(data, files):
    EVENT_STATUS = 1
    ADOPT = 1

    try:
        userId = data["user_id"]
    except KeyError:
        return util.errorJsonWrapper("请求数据没有user_id字段")
    try:
        userToken = data["user_token"]
    except KeyError:
        return util.errorJsonWrapper("请求数据没有token字段")

    if not util.checkToken(userId, userToken):
        return util.errorJsonWrapper("token 验证失败")

    user = models.User.objects.filter(user_id=userId).first()
    if not user:
        return util.errorJsonWrapper("不存在该用户")

    if not user.user_authenticated:
        return util.errorJsonWrapper("failed")

    activityIntro = data.get("activity_introduction")
    activityAddr = data.get("activity_address")
    activityLongi = data.get("activity_longitude")
    activityLati = data.get("activity_latitude")
    activityPet = data.get("activity_pet_type")
    activityPrice = data.get("activity_price")
    activityStartTime = data.get("activity_start_time")
    activityEndTime = data.get("activity_end_time")
    activityStartTime = time.strftime(
        "%Y-%m-%d", (time.strptime(activityStartTime, "%Y-%m-%d")))
    activityEndTime = time.strftime(
        "%Y-%m-%d", (time.strptime(activityEndTime, "%Y-%m-%d")))

    resDict = {}
    resDict['activity_introduction'] = activityIntro
    resDict['activity_address'] = activityAddr
    resDict['activity_longitude'] = activityLongi
    resDict['activity_latitude'] = activityLati
    resDict['activity_pet_type'] = activityPet
    resDict['activity_price'] = activityPrice
    resDict['activity_start_time'] = activityStartTime
    resDict['activity_end_time'] = activityEndTime
    resDict["user_id"] = user.user_id
    resDict["user_nickname"] = user.user_nickname
    resDict["user_avatar"] = user.user_avatar
    resDict["user_address"] = user.user_address
    resDict["user_age"] = user.user_age
    resDict["user_interest"] = user.user_interest
    resDict["user_gender"] = user.user_gender
    resDict["user_authenticated"] = user.user_authenticated

    picName = util.savePicture(files, "activity_picture", 20 * 1024 * 1024)
    if picName == -1:
        return util.errorJsonWrapper("failed")
    activityPic = picName

    try:

        activity = models.Activity(activity_introduction=activityIntro,
                                   activity_picture=activityPic,
                                   activity_price=activityPrice,
                                   activity_pet_type=activityPet,
                                   activity_start_time=activityStartTime,
                                   activity_end_time=activityEndTime,
                                   activity_status=EVENT_STATUS,
                                   activity_latitude=activityLati,
                                   activity_longitude=activityLongi,
                                   activity_address=activityAddr)
        activity.save()
    except Exception:
        return util.errorJsonWrapper("发布收养信息出错,activity无法写入数据库")

    resDict["activity_id"] = activity.pk
    resDict["activity_picture"] = picName

    try:
        participant = models.Participant(participant_user=user,
                                         participant_activity=activity,
                                         participant_user_type=ADOPT)
        participant.save()
    except Exception:
        return util.errorJsonWrapper("发布收养信息出错,participant无法写入数据库")

    #userDict = {"user_id" : userId}
    res = dict(retCode=0, retMsg="", retValue=resDict)
    return json.dumps(res)
示例#19
0
    def get(self):
        activities = [{
            "title": "JAVA101",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "JAVA 101",
            "type": "EXERCISE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "JAVA 101",
            "type": "ASSIGNMENT",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "CSS Intro to design",
            "type": "ASSIGNMENT",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "CSS Bootstrap",
            "type": "EXERCISE",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "CSS Responsive",
            "type": "ASSIGNMENT",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "Angular basics",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "Angular advanced",
            "type": "EXERCISE",
            "desc": "something...",
            "time_slots": 1
        }, {
            "title": "Python",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 1
        }, {
            "title": "Python",
            "type": "EXERCISE",
            "desc": "something...",
            "time_slots": 1
        }, {
            "title": "Django",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "Django",
            "type": "ASSIGNMENT",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "SQL intro",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "Github",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 1
        }, {
            "title": "Github",
            "type": "ASSIGNMENT",
            "desc": "something...",
            "time_slots": 1
        }, {
            "title": "Project Management",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "Javascript Intro",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 2
        }, {
            "title": "Jquery",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }, {
            "title": "DOM",
            "type": "LECTURE",
            "desc": "something...",
            "time_slots": 3
        }]

        for a in activities:
            newActivity = models.Activity()
            newActivity.id = generateId()
            newActivity.title = a['title']
            newActivity.creator = getCurrentLoggedInUser(self)
            newActivity.program = "bootcamp"
            newActivity.cohort = "winter 2015"
            newActivity.type = a['type']
            newActivity.desc = a['desc']
            newActivity.time_slots = a['time_slots']
            newActivity.status = "IN_REPOSITORY"
            newActivity.put()
示例#20
0
    def test_change_activity(self):
        self.object_client1 = models.Client(name='test2',
                                            loyal=True,
                                            owner=self.user)
        self.object_client1.save()

        self.object_contact1 = models.Contact(first_name='test2',
                                              last_name='test',
                                              email='*****@*****.**',
                                              phone='123',
                                              client=self.object_client1,
                                              owner=self.user)
        self.object_contact1.save()
        #Пробуем изменить активность выбрав клиента, который не связан с контактом
        data_client_input = {
            'title': 'test',
            'text': 'test',
            'client': 2,
            'contact': 1
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_client_input)
        self.failIf(response.context['form'].is_valid())
        self.assertIn('Chosen contact doesn&#39;t belong to chosen client',
                      response.content)

        #Аналогично пытаемся отправить форму с контактом не связанным с клиентом
        data_contact_input = {
            'title': 'test',
            'text': 'test',
            'client': 1,
            'contact': 2
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_contact_input)
        self.failIf(response.context['form'].is_valid())
        self.assertIn('Chosen contact doesn&#39;t belong to chosen client',
                      response.content)

        #Передаем связанных клиента/контакта, успешно меняем запись
        data_correct_input = {
            'title': 'test',
            'text': 'test',
            'client': 2,
            'contact': 2
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 1}))
        self.assertEqual(response.status_code, 302)

        #Проверяем, что новые значения сохранились в базе данных
        activity = models.Activity.objects.get(pk=1)
        self.assertTrue(activity.client.id == activity.contact.id == 2)

        #Проверяем невозможность изменения отправленной активности
        content = {'action': 'Send'}
        self.client.post(reverse('crm:activity', kwargs={'pk': 1}), content)
        activity = models.Activity.objects.get(pk=1)

        self.assertIsNotNone(
            activity.send_date)  #Проверяем, что дата отправки проставилась

        data_correct_input = {
            'title': 'test',
            'text': 'test',
            'client': 1,
            'contact': 1
        }

        response = self.client.post(reverse('crm:activity', kwargs={'pk': 1}),
                                    data_correct_input)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', None,
                             "You can't change activity which was sent")

        #Создаем еще одну активность
        self.object2 = models.Activity(title='test1',
                                       text='test1',
                                       contact=self.object_contact,
                                       client=self.object_client,
                                       owner=self.user)
        self.object2.save()

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Пробуем изменить - неуспешно, так как пользователь - не owner объекта
        data_correct_input = {
            'title': 'test1123',
            'text': 'test',
            'client': 1,
            'contact': 1
        }
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)
        self.assertEqual(models.Activity.objects.get(pk=2).title, 'test1')

        #Пробуем удалить - неуспешно
        data_correct_input = {'action': 'Delete'}
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)
        self.assertTrue(models.Activity.objects.get(pk=2))

        self.client.login(username='******',
                          password='******')  #Перелогиниваемся

        #Пробуем изменить - успешно
        data_correct_input = {
            'title': 'test1',
            'text': 'test',
            'client': 2,
            'contact': 2
        }
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)
        self.assertRedirects(response, reverse('crm:activity',
                                               kwargs={'pk': 2}))
        self.assertEqual(response.status_code, 302)

        #Пробуем удалить
        data_correct_input = {'action': 'Delete'}
        response = self.client.post(reverse('crm:activity', kwargs={'pk': 2}),
                                    data_correct_input)

        self.assertTrue(self.client.session['deleted_data']
                        )  #Проверяем, что сохранили информацию
        self.assertEqual(response.status_code, 302)
        self.assertRedirects(response, reverse('crm:main'))
        self.assertEqual(models.Activity.objects.count(), 1)