Ejemplo n.º 1
0
def test_instructor():
    from models import Instructor
    Instructor(first_name='Joe',
               last_name='Biden',
               email='*****@*****.**',
               password='******',
               gender='M',
               courses=[]).save()
    Instructor(first_name='Kamala',
               last_name='Harris',
               email='*****@*****.**',
               password='******',
               gender='F',
               requests_received=[]).save()
    Instructor(first_name='Nancy',
               last_name='Pelosi',
               email='*****@*****.**',
               password='******').save()
    # TODO add a nonempty `request_received` test case
    pass

    # TODO add a nonempty `courses` test case
    pass

    clean_up()
Ejemplo n.º 2
0
def get_single_entry(id):
    with sqlite3.connect("./dailyjournal.db") as con:
        con.row_factory = sqlite3.Row
        c = con.cursor()
        c.execute('''
        SELECT
            e.id,
            e.date,
            e.topics,
            e.entry,
            e.moodId,
            i.id instructor_id,
            i.first_name,
            i.last_name,
            i.expertise,
            m.id mood_id,
            m.label
        FROM Entries e
        JOIN Instructors i ON i.id = e.instructorId
        JOIN Moods m ON m.id = e.moodId
        WHERE e.id = ?        
        ''', (id, ))
        row = c.fetchone()
        instructor = Instructor(row['instructor_id'],row['first_name'], row['last_name'], row['expertise']).__dict__
        mood = Mood(row['mood_id'], row['label']).__dict__
        entry = Entry(row['id'], row['date'], row['topics'], row['entry'], mood, instructor).__dict__
        return json.dumps(entry)
Ejemplo n.º 3
0
def get_all_entries():
    with sqlite3.connect("./dailyjournal.db") as con:
        con.row_factory = sqlite3.Row
        cursor = con.cursor()
        cursor.execute("""
        SELECT
            e.id,
            e.date,
            e.topics,
            e.entry,
            e.moodId,
            i.id instructor_id,
            i.first_name,
            i.last_name,
            i.expertise,
            m.id mood_id,
            m.label
        FROM Entries e
        JOIN Instructors i ON i.id = e.instructorId
        JOIN Moods m ON m.id = e.moodId
        """)
        entries = []
        data = cursor.fetchall()
        for row in data:
            instructor = Instructor(row['instructor_id'],row['first_name'], row['last_name'], row['expertise']).__dict__
            mood = Mood(row['mood_id'], row['label']).__dict__
            entries.append(Entry(row['id'], row['date'], row['topics'], row['entry'], mood, instructor).__dict__)
    return json.dumps(entries)
Ejemplo n.º 4
0
def taskmod(root, tree, obj_classes=None):
    encoder_path, decoder_path = utils.upernet_ckpt(root)
    instructor = Instructor(tree, obj_classes=obj_classes)
    fpn = upernet.get_fpn(tree, weights_encoder=encoder_path, weights_decoder=decoder_path)
    fpn = add_taskmod(fpn)
    model = TaskMod(instructor, fpn)
    return model, instructor
Ejemplo n.º 5
0
 def instructor_get(cls, request):
     try:
         token = jwt.decode(request.tokenint, 'secret')  #checa token
         instructorentity = ndb.Key(urlsafe=request.entityKey)
         instructor = Instructor.get_by_id(
             cliententity.id())  #obtiene usuario
         #user = Usuarios.get_by_id(token['user_id']) #obtiene usuario dado el token
         lista = []  #crea lista
         lstMessage = InstructorList(code=1)  # crea objeto mensaje
         lista.append(
             InstructorUpdate(
                 token='',
                 entityKey=instructor.entityKey,
                 #empresa_key = user.empresa_key.urlsafe(),
                 name=instructor.name,
                 lastname=instructor.lastname,
                 age=instructor.age,
                 sport=instructor.sport,
                 urlImage=instructor.urlImage))  # agrega a la lista
         lstMessage.data = lista  #ASIGNA a la salida la lista
         message = lstMessage
     except jwt.DecodeError:
         message = ProductList(code=-1, data=[])  #token invalido
     except jwt.ExpiredSignatureError:
         message = ProductList(code=-2, data=[])  #token expiro
     return message
Ejemplo n.º 6
0
def ins_sign_up():
    if request.method == 'POST':
        email = request.form.get('email')
        first_name = request.form.get('firstName')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        inst = Instructor.query.filter_by(email=email).first()
        if inst:
            flash('Email already exists.', category='error')
        elif password1 != password2:
            flash('Passwords don\'t match.', category='error')
        elif len(password1) < 7:
            flash('Password must be at least 7 characters.', category='error')
        else:
            new_inst = Instructor(email=email,
                                  first_name=first_name,
                                  password=generate_password_hash(
                                      password1, method='sha256'))
            db.session.add(new_inst)
            db.session.commit()
            session['logged_in'] = True
            flash('Account created!', category='success')
            return redirect(url_for('instructor'))

    return render_template("ins_sign_up.html", user=current_user)
Ejemplo n.º 7
0
def get_all_instructors():
    with sqlite3.connect("./dailyJournal.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(""" 
        SELECT 
            i.id,
            i.first_name,
            i.last_name
        FROM instructors i
        """)

        instructors = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            instructor = Instructor(row["id"], row["first_name"],
                                    row["last_name"])

            instructors.append(instructor.__dict__)

        return json.dumps(instructors)
Ejemplo n.º 8
0
    def instructor_list(cls, request):
        try:
            token = jwt.decode(request.tokenint, 'secret')  #checa token
            user = Usuarios.get_by_id(
                token['user_id'])  #obtiene usuario dado el token
            lista = []  #crea lista
            lstMessage = InstructorList(code=1)  # crea objeto mensaje
            lstBd = Instructor.query().fetch(
            )  # recupera de base de datos igual a un select * from blabla
            for i in lstBd:  # recorre
                lista.append(
                    InstructorUpdate(
                        token='',
                        entityKey=i.entityKey,
                        #empresa_key=user.empresa_key.urlsafe(),
                        name=i.name,
                        lastname=i.lastname,
                        age=i.age,
                        sport=i.sport,
                        urlImage=i.urlImage))

            lstMessage.data = lista  # la manda al messa
            message = lstMessage  #regresa

        except jwt.DecodeError:
            message = ClientList(code=-1, data=[])  #token invalido
        except jwt.ExpiredSignatureError:
            message = ClientList(code=-2, data=[])  #token expiro
        return message
Ejemplo n.º 9
0
def test_request_for_course():
    from models import RequestForCourse
    from models import Course, Instructor, Staff, Student
    from models import Instructor

    joe = Instructor(first_name='Joe',
                     last_name='Biden',
                     email='*****@*****.**',
                     password='******').save()
    pl999 = Course(code='PL999', course_name='US Presidency',
                   professor=joe).save()

    RequestForCourse(course=pl999, requests_quota=8,
                     recommender=joe).validate()

    # negative quota
    with pytest.raises(ValidationError):
        RequestForCourse(course=pl999, requests_quota=-1,
                         recommender=joe).validate()
    # missing quota
    with pytest.raises(ValidationError):
        RequestForCourse(course=pl999, recommender=joe).validate()
    # missing recommender
    with pytest.raises(ValidationError):
        RequestForCourse(course=pl999, requests_quota=10).validate()
    # missing course
    with pytest.raises(ValidationError):
        RequestForCourse(requests_quota=10, recommender=joe).validate()

    clean_up()
Ejemplo n.º 10
0
def create_instructor(request):
	if request.method=="POST":
		try:
			inst_obj = Instructor(name=request.POST.get("name"),
								email=request.POST.get("email"),
								mobile=request.POST.get("cell"),
								info=request.POST.get("extratext"))
			inst_obj.save()
			msg="successfully created instructor"
		except Exception as err:
			msg=err.message()
		#return render(request,"create_instructor.html",{"message":msg})
		#data = Instructor.objects.all()
		#return render(request,"list_instructor.html",{"msg":msg,"data":data})
		return redirect("/instructor/")
	else:

		return render(request,"create_instructor.html")
Ejemplo n.º 11
0
 def instructor_add(cls, request):
     try:
         token = jwt.decode(request.token, 'secret')  #CHECA EL TOKEN
         user = Usuarios.get_by_id(
             token['user_id']
         )  #obtiene el usuario para poder acceder a los metodos declarados en models.py en la seccion de
         myinstructor = Instructor()
         if myinstructor.instructor_m(
                 request, user.key
         ) == 0:  #llama a la funcion declarada en models.py en la seccion de PRODUCTS
             codigo = 1
         else:
             codigo = -3
             #la funcion josue_m puede actualizar e insertar
             #depende de la ENTRADA de este endpoint method
         message = CodeMessage(code=codigo, message='Instructor added')
     except jwt.DecodeError:
         message = CodeMessage(code=-2, message='Invalid token')
     except jwt.ExpiredSignatureError:
         message = CodeMessage(code=-1, message='Token expired')
     return message
Ejemplo n.º 12
0
def scrape_instuctors(requester, course_id, instr_id=None):
    """
    Scrape instructor data
    """
    instr = Instructor()
    url = '/course_evaluation_reports/fas/inst-tf_summary.html?course_id={}'.format(course_id)
    if instr_id is not None:
        url += '&current_instructor_or_tf_huid_param={}'.format(instr_id)

    soup = requester.make_request(url)
    select = soup.select('select[name="current_instructor_or_tf_huid_param"]')[0]

    if not select.select('option'):
        print('No instructors found for this course')
        return []

    option = select.select('option[selected="selected"]')[0]
    id_role = option.attrs['value']
    instr.instructor_id, instr.instructor_role = id_role.split(':')
    instr.last_name, instr.first_name = map(str.strip, option.text.split(','))

    graph_reports = soup.select('.graphReport')
    if not graph_reports:
        instr.ratings = []
        print('No ratings for instructor {} {}'.format(instr.first_name,
                                                       instr.last_name))
    else:
        if len(graph_reports) != 1:
            print('More than one graph report found')
        instr.ratings = scrape_ratings(graph_reports[0])
    instr_lst = [instr]

    # Don't want recursion more than one level deep
    if instr_id is None:
        for option in select.select('option')[1:]:
            iid = option.attrs['value']
            instr_lst += scrape_instuctors(requester, course_id, iid)

    return instr_lst
Ejemplo n.º 13
0
 def instructor_update(cls, request):
     try:
         token = jwt.decode(request.token, 'secret')  #CHECA EL TOKEN
         user = Usuarios.get_by_id(
             token['user_id']
         )  #obtiene el usuario para poder acceder a los metodos declarados en models.py en la seccion de USUARIOS
         #empresakey = ndb.Key(urlsafe=user.empresa_key.urlsafe())#convierte el string dado a entityKey
         intructor = Instructor(
         )  #Se crea para instanciarse solamente, no para hacer uno nuevo
         if intructor.instructor_m(
                 request, user.key
         ) == 0:  #llama a la funcion declarada en models.py en la seccion de USUARIOS
             codigo = 1
         else:
             codigo = -3
             #la funcion josue_m puede actualizar e insertar
             #depende de la ENTRADA de este endpoint method
         message = CodeMessage(
             code=1, message='Sus cambios han sido guardados exitosamente')
     except jwt.DecodeError:
         message = CodeMessage(code=-2, message='Invalid token')
     except jwt.ExpiredSignatureError:
         message = CodeMessage(code=-1, message='Token expired')
     return message
Ejemplo n.º 14
0
def get_all_instructors():
    with sqlite3.connect("./dailyjournal.db") as con:
        con.row_factory = sqlite3.Row
        cursor = con.cursor()
        cursor.execute("""
        SELECT 
            i.id,
            i.first_name,
            i.last_name,
            i.expertise
        FROM Instructors i    
        """)
        instructors = []
        dataset = cursor.fetchall()
        for row in dataset:
            instructors.append(Instructor(row['id'], row['first_name'], row['last_name'], row['expertise']).__dict__)
        return json.dumps(instructors)    
Ejemplo n.º 15
0
    def create_instructor(*args, **kwargs):

        try:
            instructor_name = request.form.get('instructor-name')
            instructor_qualification = request.form.get(
                'instructor-qualification')

            instructor_to_add = Instructor(
                name=instructor_name, qualification=instructor_qualification)

            db.session.add(instructor_to_add)
            db.session.commit()

        except Exception:
            print(Exception)
            abort(500)

        return render_template("catalog.html", data=instructor_name)
Ejemplo n.º 16
0
    def create_instructor_json(*args, **kwargs):
        try:

            data = request.get_json()

            instructor_name = data['name']
            instructor_qualification = data['qualification']

            instructor_to_add = Instructor(
                name=instructor_name, qualification=instructor_qualification)

            db.session.add(instructor_to_add)
            db.session.commit()

        except Exception:
            print(Exception)
            abort(422)

        return jsonify({'message': True, 'name': instructor_name})
Ejemplo n.º 17
0
 def create_instructor(accessinfo):
     success = False
     try:
         body = request.get_json()
         name = body['name']
         profile_pic_path = body['profile_pic_path']
         age = body['age']
         new_instructor = Instructor(name=name, profile_pic_path=profile_pic_path, age=age)
         db.session.add(new_instructor)
         db.session.commit()
         success = True
     except:
         print(sys.exc_info())
         abort(404)
     return jsonify({
         'success' : success,
         'created' : new_instructor.id,
         'exercice name' : new_instructor.name
     })
Ejemplo n.º 18
0
def get_all_entries():
    with sqlite3.connect("dailyjournal.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(""" 
        SELECT DISTINCT
            e.id,
            e.date,
            e.concept,
            e.entry,
            e.mood_id,
            e.instructor_id,
            m.label,
            i.first_name,
            i.last_name
        FROM entries e
        JOIN moods m
            ON m.id = e.mood_id
        LEFT JOIN instructors i
            ON i.id = e.instructor_id
        """)

        entries = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            entry = Entry(row["id"], row["date"], row["concept"], row["entry"],
                          row["mood_id"], row["instructor_id"])

            mood = Mood(row["mood_id"], row["label"])
            entry.mood = mood.__dict__

            instructor = Instructor(row["instructor_id"], row["first_name"],
                                    row["last_name"])
            entry.instructor = instructor.__dict__

            entries.append(entry.__dict__)

    return json.dumps(entries)
    def _update_udacity_courses(self, courses):
        '''
        Add Udactiy courses to the MongoDB database

        '''
        for course in courses:
            if not Mooc.objects(mooc=course['mooc'], title=course['title']):
                instructors = [
                    Instructor(name=item['name'],
                               bio=item['bio'],
                               image=item['image'])
                    for item in course['instructors']
                ]
                affiliates = [item['name'] for item in course['affiliates']]
                mooc = Mooc(course['mooc'], course['key'], course['title'],
                            course['photo'], course['trailer'],
                            course['short_summary'], course['summary'],
                            course['recommended_background'],
                            course['syllabus'], instructors, course['faq'],
                            course['categories'], affiliates)
                mooc.save()
Ejemplo n.º 20
0
    def get_course(self, course_id):
        """Return a Course object from the ID if it exists, None otherwise."""
        try:
            cur = self.conn.cursor()
            query = (
                'SELECT CourseNum, Name, Course.InstructorNum, FirstName, LastName '
                'FROM Course '
                'JOIN Instructor ON Course.InstructorNum = Instructor.InstructorNum '
                'WHERE CourseNum = ?')
            cur.execute(query, (course_id, ))

            row = cur.fetchone()
            if row:
                course_id, course_name = (row[0], row[1])
                instructor_id, first_name, last_name = (row[2], row[3], row[4])
                instructor = Instructor(instructor_id, first_name, last_name)
                return Course(course_id, course_name, instructor)

        except sqlite3.OperationalError as oe:
            print('Sql execution error', oe)
        except sqlite3.Error as e:
            print("Connection error ", e)
Ejemplo n.º 21
0
def get_all_instructors():
    # Open a connection to the database
    with sqlite3.connect("./dailyjournal.db") as conn:

        # Just use these. It's a Black Box.
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute("""
        SELECT
            i.id,
            i.first_name,
            i.last_name

        FROM Instructors i
        """)

        # Initialize an empty list to hold all instructor representations
        instructors = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create an instructor instance from the current row.
            # Note that the database fields are specified in
            # exact order of the parameters defined in the
            # instructor class above.
            instructor = Instructor(row['id'], row['first_name'],
                                    row['last_name'])

            instructors.append(instructor.__dict__)

    # Use `json` package to properly serialize list as JSON
    return json.dumps(instructors)
    def get(self):
        self.response.headers.add_header('Access-Control-Allow-Origin', '*')
        self.response.headers['Content-Type'] = 'application/json'

        id_user = self.request.get('empresa')
        objemp = Empresa.query(Empresa.codigo_empresa == id_user).get()
        strKey = objemp.key.urlsafe()
        myEmpKey = ndb.Key(urlsafe=strKey)
        myInstructors = Instructor.query()

        myList = []
        for i in myInstructors:
            myObj = DemoClass()
            myObj.id = i.key.urlsafe()
            myObj.name = i.name
            myObj.lastname = i.lastname
            myObj.age = i.age
            myObj.sport = i.sport
            myObj.urlImage = i.urlImage
            myList.append(myObj)

        json_string = json.dumps(myList, default=MyClass)
        self.response.write(json_string)
Ejemplo n.º 23
0
def test_message():
    from models import Message
    from models import Student, Instructor

    # datetime
    now = datetime.utcnow
    # instructor & student
    joe = Instructor(first_name='Joe',
                     last_name='Biden',
                     email='*****@*****.**',
                     password='******').save()
    john = Student(first_name='John',
                   last_name='Doe',
                   email='*****@*****.**',
                   password='******',
                   gender='M').save()

    # from student
    msg = Message(sender=john, content="Hello, Joe!", time=now())
    msg.validate()
    assert msg.sender == 'John Doe'
    # from instructor
    msg = Message(sender=joe, content="Hello, John!", time=now())
    msg.validate()
    assert msg.sender == 'Joe Biden'
    # custom sender_name
    msg = Message(sender='US President', content="Hello, John!", time=now())
    msg.validate()
    assert msg.sender == 'US President'
    # w/o time
    Message(sender=john, content="Hello, again!").validate()

    # content too long
    with pytest.raises(ValidationError):
        Message(sender=joe, content="a" * 501).validate()

    clean_up()
Ejemplo n.º 24
0
    def get_courses_by_name(self, course_name):
        """Return a list of Courses that match the course_name."""
        try:
            cur = self.conn.cursor()
            # TODO: Query parameter might need some wildcards added.
            query = (
                'SELECT CourseNum, Name, Course.InstructorNum, FirstName, LastName '
                'FROM Course '
                'JOIN Instructor ON Course.InstructorNum = Instructor.InstructorNum '
                'WHERE UPPER(Name) LIKE ?')
            cur.execute(query, ('%{}%'.format(course_name.upper()), ))

            courses = []
            for row in cur:
                course_id, course_name = (row[0], row[1])
                instructor_id, first_name, last_name = (row[2], row[3], row[4])
                instructor = Instructor(instructor_id, first_name, last_name)
                courses.append(Course(course_id, course_name, instructor))
            return courses

        except sqlite3.OperationalError as oe:
            print('Sql execution error', oe)
        except sqlite3.Error as e:
            print("Connection error ", e)
Ejemplo n.º 25
0
# A DBSession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()

# Insert a time block into the time_blocks table
new_time_block = TimeBlock(CRN=13243, course_num="CMET133")
session.add(new_time_block)
session.commit()

# Insert an instructor in the instructors table
new_instructor = Instructor(first_name="peter")
session.add(new_instructor)
session.commit()

# Try a more complicated time_block insertion
t1 = datetime.time(9, 0, 0)
t2 = datetime.time(11, 50, 0)

d = {
    "CRN": 55555,
    "building": "AM",
    "campus": "SY",
    "course_num": "CMET211",
    "course_title": "Environmental Quality",
    "day": "Tuesday",
    "department": "CMET",
Ejemplo n.º 26
0
 def instructors():
     selection = Instructor.query.all()
     instructors = [Instructor.format() for Instructor in selection]
     
     return jsonify({'instructors' : instructors})
Ejemplo n.º 27
0
from models import engine, db_session, Base, Department, Course, Instructor
Base.metadata.create_all(bind=engine)

compsci = Department(name="Computer Science", short="COMPSCI")
math = Department(name="Math", short="MATH")
db_session.add(compsci)
db_session.add(math)

john = Instructor(name="John")
paul = Instructor(name="Paul")
db_session.add(john)
db_session.add(paul)

intro_cs = Course(title="Intro to CS",
                  number=101,
                  department=compsci,
                  instructors=[john])
db_session.add(intro_cs)
medium_cs = Course(title="Intermediate CS",
                   number=201,
                   prerequisites=[intro_cs],
                   department=compsci,
                   instructors=[john])
db_session.add(medium_cs)
db_session.commit()

intro_math = Course(title="Intro to Math",
                    number=101,
                    department=math,
                    instructors=[paul])
db_session.add(intro_math)
Ejemplo n.º 28
0
from models import db, connect_db, Course, Review, Instructor, TeachingAssignment
from app import app

db.create_all()

matt = Instructor(first_name="Matt", last_name="Lane")
nate = Instructor(first_name="Nate", last_name="Lipp")
tim = Instructor(first_name="Tim", last_name="Garcia")

db.session.add_all([matt, nate, tim])
db.session.commit()
Ejemplo n.º 29
0
def get_model(root, tree, op):
    encoder_path, decoder_path = utils.upernet_ckpt(root)
    instructor = Instructor(tree)
    model = CSHead(instructor, tree, encoder_path, decoder_path, emb_op=op)
    return model, instructor
Ejemplo n.º 30
0
def test_course():
    from models import Course, Instructor, Staff, Student
    today = date.today()

    # instructors
    joe = Instructor(first_name='Joe',
                     last_name='Biden',
                     email='*****@*****.**',
                     password='******').save()
    tony = Instructor(first_name='Tony',
                      last_name='Stark',
                      email='*****@*****.**',
                      password='******').save()
    kamala = Instructor(first_name='Kamala',
                        last_name='Harris',
                        email='*****@*****.**',
                        password='******').save()
    pepper = Instructor(first_name='Pepper',
                        last_name='Potts',
                        email='*****@*****.**',
                        password='******').save()
    morgan = Instructor(first_name='Morgan',
                        last_name='Stark',
                        email='*****@*****.**',
                        password='******').save()

    # coordinators
    james = Staff(first_name='James',
                  last_name='Bond',
                  email='*****@*****.**',
                  password='******').save()
    eve = Staff(first_name='Eve',
                last_name='Moneypenny',
                email='*****@*****.**',
                password='******').save()

    # students
    john = Student(first_name='John',
                   last_name='Doe',
                   email='*****@*****.**',
                   password='******',
                   gender='M').save()
    jane = Student(first_name='Jane',
                   last_name='Doe',
                   email='*****@*****.**',
                   password='******',
                   gender='F').save()

    # w/o start_date
    Course(code='PL999', course_name='US Presidency', professor=joe).save()
    # w/ start_date
    Course(code='PL888',
           start_date=today,
           course_name='US Senatorship',
           professor=joe).save()
    # w/o mentors, coordinator, and students
    Course(code='PL101', course_name='Introduction to Politics',
           professor=joe).save()
    # w/ single mentor; w/o coordinator and students
    Course(code='PL102',
           course_name='Intermediate Politics',
           professor=joe,
           mentors=[kamala]).save()
    # w/ mentors and coordinator; w/o students
    Course(code='CS101',
           course_name='Introduction to Computer Science',
           professor=tony,
           mentors=[pepper, morgan],
           coordinator=james).save()
    # w/ mentors, coordinator, and students
    Course(code='CS103',
           course_name='Advanced Computer Science',
           professor=tony,
           mentors=[pepper, morgan],
           coordinator=eve,
           students=[john, jane]).save()

    # w/o professor
    with pytest.raises(ValidationError):
        Course(code='PL103', course_name='Advanced Politics').save()
    # duplicate course code
    with pytest.raises(NotUniqueError):
        Course(code='CS103',
               course_name='Computational Science',
               professor=tony).save()

    clean_up()
Ejemplo n.º 31
0
def test_request():
    from models import Student, Instructor, Course
    from models import Request
    from models import STATUS_REQUESTED, STATUS_EMAILED, STATUS_UNFULFILLED, STATUS_FULFILLED

    ILLEGAL_STATUS = 1234

    # date
    today = date.today()
    # instructor & student
    joe = Instructor(first_name='Joe',
                     last_name='Biden',
                     email='*****@*****.**',
                     password='******').save()
    john = Student(first_name='John',
                   last_name='Doe',
                   email='*****@*****.**',
                   password='******',
                   gender='M').save()
    # course
    pl999 = Course(code='PL999', course_name='US Presidency',
                   professor=joe).save()

    # w/ everything filled (except for messages)
    Request(student=john,
            instructor=joe,
            course=pl999,
            school_applied='Harvard',
            program_applied='Politics',
            deadline=today,
            date_created=today,
            date_updated=today,
            date_fulfilled=today,
            status=STATUS_FULFILLED).save()
    # w/o date_created
    Request(student=john,
            instructor=joe,
            course=pl999,
            school_applied='Harvard',
            program_applied='Politics',
            deadline=today,
            date_updated=today,
            date_fulfilled=today,
            status=STATUS_FULFILLED).save()
    # w/o date_fulfilled
    Request(student=john,
            instructor=joe,
            course=pl999,
            school_applied='Harvard',
            program_applied='Politics',
            deadline=today,
            date_created=today,
            date_updated=today,
            status=STATUS_UNFULFILLED).save()

    # w/o student
    with pytest.raises(ValidationError):
        Request(instructor=joe,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # w/o professor
    with pytest.raises(ValidationError):
        Request(student=john,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # w/o course
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                school_applied='Harvard',
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # w/o school_applied
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # w/o program_applied
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # w/o deadline
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics',
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # w/o date_fulfilled but status==STATUS_FULFILLED
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                status=STATUS_FULFILLED).save()
    # w/ date_fulfilled but status!=STATUS_FULFILLED
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_REQUESTED).save()
    # illegal status
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=ILLEGAL_STATUS).save()
    # School name too long
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard' * 10,
                program_applied='Politics',
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()
    # Program name too long
    with pytest.raises(ValidationError):
        Request(student=john,
                instructor=joe,
                course=pl999,
                school_applied='Harvard',
                program_applied='Politics' * 10,
                deadline=today,
                date_created=today,
                date_updated=today,
                date_fulfilled=today,
                status=STATUS_FULFILLED).save()

    # TODO add test case for nonempty `messages`

    clean_up()