示例#1
0
    def test_removeClassFromStudent(self):
        print('Running removeClassFromStudent test case')

        userRole = 'admin'
        email = '*****@*****.**'
        classCode = 'f77668db-fb9d-4fd6-81f1-026784d6cc9b'
        classCode2 = 'e00045db-fb9d-4fd6-81f1-026784d6cc9b'
        res = ResponseCreation.ControllerResponse()

        # Put user and class data into DB
        usersTable = db.getTable('users', dynamodb)

        userJsonData = {'email': email, 'classCodes': [classCode, classCode2]}

        db.putItem(userJsonData, usersTable)

        # Check test data was successfully placed into DB
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('email'), email)

        class_ctrl.removeClassFromStudent(dynamodb, res, email, classCode2)

        # Check that the classCode was removed from the student
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        cc = response.get('Item').get('classCodes')
        self.assertFalse(classCode2 in cc)
        self.assertTrue(classCode in cc)
示例#2
0
    def test_removeStudentFromClass_len_zero(self):
        print(
            'Running removeStudentFromClass students length is zero test case')

        userRole = 'admin'
        email = '*****@*****.**'
        classCode = 'f77998db-fb9d-4fd6-81f1-026784d6cc9b'
        res = ResponseCreation.ControllerResponse()

        #Put user and class data into DB
        classesTable = db.getTable('classes', dynamodb)

        classJsonData = {'code': classCode, 'students': [email]}

        db.putItem(classJsonData, classesTable)

        #Check test data was successfully placed into DB
        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('code'), classCode)

        class_ctrl.removeStudentFromClass(dynamodb, res, email, classCode)

        #check that the attribute was removed from the class
        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertIsNone(response.get('Item').get('students'))
示例#3
0
    def test_removeStudentFromClasss(self):
        print('Running removeStudentFromClass test case')

        userRole = 'admin'
        email1 = '[email protected]'
        email2 = '[email protected]'
        classCode = 'f77668db-fb9d-4fd6-81f1-026784d6cc9b'
        res = ResponseCreation.ControllerResponse()

        #Put user and class data into DB
        classesTable = db.getTable('classes', dynamodb)

        classJsonData = {'code': classCode, 'students': [email1, email2]}

        db.putItem(classJsonData, classesTable)

        #Check test data was successfully placed into DB
        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('code'), classCode)

        class_ctrl.removeStudentFromClass(dynamodb, res, email1, classCode)

        #check that the student was removed from the class
        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        stu = response.get('Item').get('students')
        self.assertFalse(email1 in stu)
        self.assertTrue(email2 in stu)
示例#4
0
    def test_isCodeInTaughtList(self):
        print('Running isCodeInTaughtList test case')
        email = '*****@*****.**'

        # put user with taught list into db
        usersTable = db.getTable('users', dynamodb)
        userJsonData = {
            'email': email,
            'userRole': 'teacher',
            'teaching': ['d26713cc-f02d-4fd6-80f0-026784d1ab9b'
                         ]  #algebra 1 from mock classes data
        }

        db.putItem(userJsonData, usersTable)

        # code is in teaching list
        jsonData = {'code': 'd26713cc-f02d-4fd6-80f0-026784d1ab9b'}
        response = class_ctrl.isCodeInTaughtList(jsonData, dynamodb, email)
        self.assertTrue(response)

        # code is not in teaching list
        jsonData = {'code': '000000-f02d-4fd6-80f0-026784d1ab9b'}
        response = class_ctrl.isCodeInTaughtList(jsonData, dynamodb, email)
        self.assertFalse(response)

        # no code given
        jsonData = {}
        response = class_ctrl.isCodeInTaughtList(jsonData, dynamodb, email)
        self.assertFalse(response)
示例#5
0
    def test_removeStudent(self):
        print('Running removeStudent test case')

        userRole = 'admin'
        email = '*****@*****.**'
        classCode = 'f24613dc-f09d-4fd6-81f1-026784d6cc9b'

        #Put user and class data into DB
        usersTable = db.getTable('users', dynamodb)
        classesTable = db.getTable('classes', dynamodb)

        userJsonData = {'email': email, 'classCodes': [classCode]}

        classJsonData = {'code': classCode, 'students': [email]}

        db.putItem(userJsonData, usersTable)
        db.putItem(classJsonData, classesTable)

        #Check test data was successfully placed into DB
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('email'), email)

        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('code'), classCode)

        #Test removal
        jsonData = {'email': email, 'classCode': classCode}
        res = class_ctrl.removeStudent(dynamodb, jsonData, userRole=userRole)
        self.assertFalse(res.hasErrors())
示例#6
0
    def test_removeClassFromStudent_len_zero(self):
        print(
            'Running removeClassFromStudent students length is zero test case')

        userRole = 'admin'
        email = '*****@*****.**'
        classCode = 'f84138db-fb9d-4fd6-81f1-026784d6cc9b'
        res = ResponseCreation.ControllerResponse()

        #Put user and class data into DB
        usersTable = db.getTable('users', dynamodb)

        userJsonData = {'email': email, 'classCodes': [classCode]}

        db.putItem(userJsonData, usersTable)

        # Check test data was successfully placed into DB
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('email'), email)

        class_ctrl.removeClassFromStudent(dynamodb, res, email, classCode)

        # Check that the attribute was removed from the student
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertIsNone(response.get('Item').get('classCodes'))
示例#7
0
    def test_putItem_json(self):
        print("Running putItem_json test")
        self.assertIsNotNone(self.table)
        self.assertEqual(self.table.table_status, "ACTIVE")

        jsonData = {"email": "tabby", "gender": "male"}

        db.putItem(jsonData, self.table)
        self.assertIsNotNone(
            self.table.get_item(Key={
                "email": "tabby"
            }).get("Item"))
示例#8
0
    def test_undoClassCodeRemoval(self):
        print('Running undoClassCodeRemoval test case')

        email = '*****@*****.**'
        classCode = 'f99998db-fb9d-4fd6-81f1-026784d6cc9b'
        classCode2 = 'f00000db-fb9d-4fd6-81f1-026784d6cc9b'

        #Put user and class data into DB
        usersTable = db.getTable('users', dynamodb)

        ### to simulate class already removed from student ###
        userJsonData = {'email': email}

        db.putItem(userJsonData, usersTable)

        #Check test data was successfully placed into DB
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('email'), email)

        #Test simulated error in undoClassCodeRemoval email
        class_ctrl.undoClassCodeRemoval(dynamodb, email, classCode)

        #check class was place back into student's classCodes
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        classCodes = response.get('Item').get('classCodes')
        self.assertTrue(classCode in classCodes)

        #### add classCode back to a list that when removed will still have elements ###
        userJsonData = {
            'email': email,
            'classCodes': set([classCode, classCode2])
        }
        db.putItem(userJsonData, usersTable)
        #Check test data was successfully placed into DB
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('email'), email)

        #Test simulated error in undoClassCodeRemoval email
        class_ctrl.undoClassCodeRemoval(dynamodb, email, classCode2)

        #check class was place back into student's classCodes
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        classCodes = response.get('Item').get('classCodes')
        self.assertTrue(classCode in classCodes)
        self.assertTrue(classCode2 in classCodes)
示例#9
0
    def test_updateClassDetails(self):
        print('Running updateClassDetails test')

        classesTable = db.getTable('classes', dynamodb)
        usersTable = db.getTable('users', dynamodb)
        email = '*****@*****.**'
        userRole = 'teacher'

        # put data into db first
        beforeUserData = {'email': email, 'teaching': ['before update code']}

        beforeClassData = {
            'title': 'before update title',
            'department': 'before update department',
            'description': 'before update description',
            'classSection': 'before update section',
            'code': 'before update code'
        }

        db.putItem(beforeClassData, classesTable)
        db.putItem(beforeUserData, usersTable)

        # check item was placed successfully
        code = {'Key': {'code': 'before update code'}}
        c = db.getItem(code, classesTable)
        self.assertTrue('Item' in c.keys())

        e = {'Key': {'email': email}}
        user = db.getItem(e, usersTable)
        self.assertTrue('Item' in user.keys())

        # update class details
        afterData = {
            'title': 'after update title',
            'department': 'after update department',
            'description': 'after update description',
            'section': 'after update section',
            'code': 'before update code'
        }

        response = class_ctrl.updateClassDetails(afterData, dynamodb, email,
                                                 userRole)
        self.assertEqual(response.payload,
                         {'Success': 'Class Details Updated'})
        c = db.getItem(code, classesTable)
        self.assertTrue('Item' in c.keys())
        self.assertEqual(c['Item']['title'], 'after update title')
        self.assertEqual(c['Item']['department'], 'after update department')
        self.assertEqual(c['Item']['classSection'], 'after update section')
        self.assertEqual(c['Item']['description'], 'after update description')
示例#10
0
    def test_putItem_string(self):
        print("Running putItem_string test")
        self.assertIsNotNone(self.table)
        self.assertEqual(self.table.table_status, "ACTIVE")

        jsonData = '{\
      "email": "doggy",\
      "gender": "female"\
    }'

        db.putItem(jsonData, self.table)
        self.assertIsNotNone(
            self.table.get_item(Key={
                "email": "doggy"
            }).get("Item"))
示例#11
0
def addUserAndSendEmail(httpOrigin, email, password, mailer, dbInstance):
  activationId = str(uuid.uuid4())
  table = dbUtils.getTable('users', dbInstance)

  jsonData = {
    'email': email,
    'password': password,
    'activationId': activationId,
    'active': 'F',
    'userRole' : "student"
  }
  if table is None:
    MentiiLogging.getLogger().error('Unable to get table users in addUserAndSendEmail')
    activationId = None

  #This will change an existing user with the same email.
  response = dbUtils.putItem(jsonData,table)

  if response is None:
    MentiiLogging.getLogger().error('Unable to add user to table users in addUserAndSendEmail')
    activationId = None

  try:
    sendEmail(httpOrigin, email, activationId, mailer)
  except Exception as e:
    MentiiLogging.getLogger().exception(e)

  return activationId
示例#12
0
def addActivity(classCode, jsonData, dynamodb, email=None, userRole=None):
    response = ControllerResponse()
    classTable = dbUtils.getTable('classes', dynamodb)

    if classTable is None:
        MentiiLogging.getLogger().error(
            'Unable to get classes table in getPublicClassList')
        response.addError('Failed to add activity', 'A database error occured')
    else:
        if g:  # pragma: no cover
            email = g.authenticatedUser['email']
            userRole = g.authenticatedUser['userRole']
        if isTeacherOfClass(email, userRole, classCode, dynamodb):
            classData = getClassByCode(classCode, dynamodb)
            if not classData:
                response.addError('Failed to add activity',
                                  'A database error occured')
            else:
                activities = classData.get('activities', [])
                activities.append(jsonData)
                classData['activities'] = activities
                result = dbUtils.putItem(classData, classTable)
                if result is None:
                    response.addError('Failed to add activity',
                                      'A database error occured')
                else:
                    response.addToPayload('Success', 'Activity Added')
        else:
            MentiiLogging.getLogger().error(
                email + ' is not the teacher of ' + classCode +
                ', but attempted to add an activity.')
            response.addError('Unable to add activity',
                              'A permissions error occured')
    return response
示例#13
0
def createClass(dynamoDBInstance, classData, email=None, userRole=None):
    response = ControllerResponse()

    #g will be not be available during testing
    #and email and userRole will need to be passed to the function
    if g:  # pragma: no cover
        email = g.authenticatedUser['email']
        userRole = g.authenticatedUser['userRole']
    #role is confirmed here incase createClass is called from somewhere other
    #than app.py create_class()
    if userRole != 'teacher' and userRole != 'admin':
        response.addError('Role error', 'Only teachers can create classes')
    elif classData is None or not checkClassDataValid(classData):
        response.addError('createClass call Failed.',
                          'Invalid class data given.')
    else:
        classTable = dbUtils.getTable('classes', dynamoDBInstance)
        userTable = dbUtils.getTable('users', dynamoDBInstance)
        if classTable is None or userTable is None:
            response.addError('createClass call Failed.',
                              'Unable to locate necessary table(s).')
        else:
            classCode = str(uuid.uuid4())
            newClass = {
                'code': classCode,
                'title': classData['title'],
                'description': classData['description']
            }

            if 'department' in classData.keys() and classData['department']:
                newClass['department'] = classData['department']
            if 'section' in classData.keys() and classData['section']:
                newClass['classSection'] = classData['section']

            result = dbUtils.putItem(newClass, classTable)

            if result is None:
                response.addError('createClass call Failed.',
                                  'Unable to create class in classes table.')
            else:
                # Note: if teaching attribute does not previously exist, a set of class codes will be created
                # otherwise, the class code will be added to the set of class codes
                codeSet = set([classCode])
                jsonData = {
                    'Key': {
                        'email': email
                    },
                    'UpdateExpression': 'ADD teaching :classCode',
                    'ExpressionAttributeValues': {
                        ':classCode': codeSet
                    },
                    'ReturnValues': 'UPDATED_NEW'
                }
                res = dbUtils.updateItem(jsonData, userTable)
                if res is None:
                    response.addError('createClass call failed',
                                      'Unable to update user data')
                else:
                    response.addToPayload('Success', 'Class Created')
    return response
示例#14
0
    def test_addDataToClassAndUser(self):
        userRole = 'student'
        email = '*****@*****.**'
        classCode = 'abcef12345'
        title = 'some class'
        response = ControllerResponse()

        # add student to user table
        usersTable = db.getTable('users', dynamodb)
        jsonData = {'email': email}
        db.putItem(jsonData, usersTable)

        # add class to class table
        classesTable = db.getTable('classes', dynamodb)
        jsonData = {'code': classCode, 'title': title}
        db.putItem(jsonData, classesTable)

        usr.addDataToClassAndUser(classCode, email, response, dynamodb)
        self.assertFalse(response.hasErrors())
        self.assertEqual(response.payload['title'], title)
        self.assertEqual(response.payload['code'], classCode)
示例#15
0
def createBook(bookData, dynamoDBInstance, userRole=None):
    response = ControllerResponse()

    #g will be not be available during testing
    #userRole will need to be passed to the function
    if g:  # pragma: no cover
        userRole = g.authenticatedUser['userRole']
    #role is confirmed here incase createBook is called from somewhere other
    #than app.py createBook()
    if userRole != 'admin':
        response.addError('Role error', 'Only admins can create books')
    # check for required options
    elif 'title' not in bookData.keys() or 'description' not in bookData.keys(
    ):
        response.addError('Book creation failed.', 'Invalid book data given.')
    else:
        # Get books table
        booksTable = dbUtils.getTable('books', dynamoDBInstance)
        if booksTable is None:
            response.addError('Get Books Table Failed',
                              'Unable to get books table from database')
        else:
            bookId = str(uuid.uuid4())
            # prep json data
            book = {
                'bookId': bookId,
                'title': bookData['title'],
                'description': bookData['description'],
                'chapters': bookData.get('chapters', [])
            }
            # put item into table
            result = dbUtils.putItem(book, booksTable)
            if result is None:
                response.addError('Book creation failed.',
                                  'Unable to create Book in database.')
            else:
                response.addToPayload('Success', 'Book Created')

    return response
示例#16
0
def editBook(bookData, dynamoDBInstance):
    response = ControllerResponse()
    # check for required options
    if not bookData or 'title' not in bookData.keys(
    ) or 'description' not in bookData.keys() or 'bookId' not in bookData.keys(
    ):
        response.addError('Book update failed.', 'Invalid book data given.')
    else:
        # Get books table
        booksTable = dbUtils.getTable('books', dynamoDBInstance)
        if booksTable is None:
            response.addError('Get Books Table Failed',
                              'Unable to get books table from database')
        else:
            # put item into table
            result = dbUtils.putItem(bookData, booksTable)
            if result is None:
                response.addError('Book update failed.',
                                  'Unable to update Book in database.')
            else:
                response.addToPayload('Success', 'Book Updated')

    return response
示例#17
0
    def test_updateClassDetails_len_zero(self):
        print('Running updateClassDetails length zero test')

        classesTable = db.getTable('classes', dynamodb)
        usersTable = db.getTable('users', dynamodb)
        email = '*****@*****.**'
        userRole = 'admin'

        # put data into db first
        beforeUserData = {'email': email, 'teaching': ['before update code']}

        beforeClassData = {
            'title': 'before update title',
            'department': 'before update department',
            'description': 'before update description',
            'classSection': 'before update section',
            'code': 'before update code'
        }

        db.putItem(beforeClassData, classesTable)
        db.putItem(beforeUserData, usersTable)

        # check item was placed successfully
        code = {'Key': {'code': 'before update code'}}
        c = db.getItem(code, classesTable)
        self.assertTrue('Item' in c.keys())

        e = {'Key': {'email': email}}
        user = db.getItem(e, usersTable)
        self.assertTrue('Item' in user.keys())

        ##### update class details removing both optional attributes
        afterData = {
            'title': 'after update title',
            'department': '',
            'description': 'after update description',
            'section': '',
            'code': 'before update code'
        }

        response = class_ctrl.updateClassDetails(afterData, dynamodb, email,
                                                 userRole)
        self.assertEqual(response.payload,
                         {'Success': 'Class Details Updated'})
        c = db.getItem(code, classesTable)
        self.assertTrue('Item' in c.keys())
        self.assertFalse('department' in c['Item'])
        self.assertFalse('classSection' in c['Item'])

        ##### update class details removing only one of the optional attributes
        beforeData = {
            'title': 'before update title',
            'department': 'asdf',
            'description': 'before update description',
            'classSection': 'lkjh',
            'code': 'before update code'
        }

        db.putItem(beforeData, classesTable)

        afterData = {
            'title': 'after update title',
            'department': 'asdf',
            'description': 'after update description',
            'section': '',
            'code': 'before update code'
        }

        response = class_ctrl.updateClassDetails(afterData, dynamodb, email,
                                                 userRole)
        self.assertEqual(response.payload,
                         {'Success': 'Class Details Updated'})
        c = db.getItem(code, classesTable)
        self.assertTrue('Item' in c.keys())
        self.assertFalse('classSection' in c['Item'])
        self.assertEqual(c['Item']['department'], 'asdf')

        afterData = {
            'title': 'after update title',
            'department': '',
            'description': 'after update description',
            'section': 'lkjh',
            'code': 'before update code'
        }

        response = class_ctrl.updateClassDetails(afterData, dynamodb, email,
                                                 userRole)
        self.assertEqual(response.payload,
                         {'Success': 'Class Details Updated'})
        c = db.getItem(code, classesTable)
        self.assertTrue('Item' in c.keys())
        self.assertFalse('department' in c['Item'])
        self.assertEqual(c['Item']['classSection'], 'lkjh')
示例#18
0
    def test_removeStudent_data_fail(self):
        print('Running removeStudent data fail test case')

        userRole = 'admin'
        email = '*****@*****.**'
        classCode = 'f15708db-fb9d-4fd6-81f1-026784d6cc9b'

        #Put user and class data into DB
        usersTable = db.getTable('users', dynamodb)
        classesTable = db.getTable('classes', dynamodb)

        userJsonData = {'email': email, 'classCodes': [classCode]}

        classJsonData = {'code': classCode, 'students': [email]}

        db.putItem(userJsonData, usersTable)
        db.putItem(classJsonData, classesTable)

        #Check test data was successfully placed into DB
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('email'), email)

        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        self.assertEqual(response.get('Item').get('code'), classCode)

        #Test bad class code
        jsonData = {
            'email': email,
            'classCode': 'f24abcdc-f09d-4fd6-81f1-026784d6cc9b'
        }
        res = class_ctrl.removeStudent(dynamodb, jsonData, userRole=userRole)
        self.assertTrue(res.hasErrors())
        self.assertEqual(
            res.errors[0], {
                'message': 'Class not found',
                'title': 'Failed to remove class from student'
            })

        #check student wasn't removed from class
        jsonData = {'Key': {'code': classCode}}
        response = db.getItem(jsonData, classesTable)
        self.assertIsNotNone(response.get('Item'))
        students = response.get('Item').get('students')
        self.assertTrue(email in students)

        #Test bad email
        jsonData = {'email': '*****@*****.**', 'classCode': classCode}
        res = class_ctrl.removeStudent(dynamodb, jsonData, userRole=userRole)
        self.assertTrue(res.hasErrors())
        self.assertEqual(
            res.errors[0], {
                'message': 'Unable to find user',
                'title': 'Failed to remove student from class'
            })

        #check class wasn't removed from student
        jsonData = {'Key': {'email': email}}
        response = db.getItem(jsonData, usersTable)
        self.assertIsNotNone(response.get('Item'))
        classCodes = response.get('Item').get('classCodes')
        self.assertTrue(classCode in classCodes)