Merge branch 'master' of https://github.com/sagidayan/SE-Hub into matanBranch

This commit is contained in:
Matan Bar Yosef 2015-06-15 10:05:06 +03:00
commit 9f7a21eca8
14 changed files with 710 additions and 267 deletions

View file

@ -6,6 +6,7 @@ from GithubAPI.GithubAPI import GitHubAPI_Keys
from google.appengine.ext import db
import requests
import uuid
import datetime
from flask import Flask, request, render_template, redirect, abort, Response
@ -19,15 +20,23 @@ from models.Course import Course
from models.Project import Project
from models.Campus import Campus
#Validation Utils Libs
# All API
from SE_API.Validation_Utils import *
from SE_API.Respones_Utils import *
from SE_API.Email_Utils import *
from SE_API.UserRoutes import user_routes
from SE_API.CampusRoutes import campus_routes
from SE_API.CourseRoutes import course_routes
from SE_API.ProjectRoutes import project_routes
app = Flask(__name__, static_folder='../templates')
githubKeys = GitHubAPI_Keys()
app.config['GITHUB_CLIENT_ID'] = githubKeys.getId()
@ -35,6 +44,12 @@ app.config['GITHUB_CLIENT_SECRET'] = githubKeys.getSecret()
github = GitHub(app)
cross = CORS(app)
app.register_blueprint(user_routes)
app.register_blueprint(campus_routes)
app.register_blueprint(course_routes)
app.register_blueprint(project_routes)
auto = Autodoc(app)
@app.errorhandler(404)
@ -108,23 +123,18 @@ def send_activation(token):
403 - Invalid Token<br>
"""
if not request.data:
return Response(response=json.dumps({'message': 'Bad Request'}),
status=400,
mimetype="application/json")
return bad_request()
payload = json.loads(request.data)
if not is_user_token_valid(token):
return Response(response=json.dumps({'message': 'Not A Valid Token!'}),
status=403,
mimetype="application/json")
return forbidden("Not A Valid Token!")
query = User.all()
query.filter('seToken =', token)
for u in query.run(limit=1):
try:
send_validation_email(token=token, name=u.username, email=payload["email"])
except Exception:
return Response(response=json.dumps({'message': 'Bad Request'}),
status=400,
mimetype="application/json")
return bad_request()
return Response(status=200)
@ -132,6 +142,10 @@ def send_activation(token):
def documentation():
return auto.html()
# @app.route('/api/help/campuses')
# def documentation():
# return auto.html()
@app.route('/home')
def returnHome():
try:
@ -141,51 +155,6 @@ def returnHome():
@app.route('/api/getUserByToken/<string:token>', methods=["GET"])
@auto.doc()
def getUserByToken(token):
'''
<span class="card-title">This Function is will Activate a user and add tha campus to it</span>
<br>
<b>Route Parameters</b><br>
- validation_token: 'seToken|email_suffix'
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'username' : 'github_username',<br>
'name' : 'Bob Dylan',<br>
'email' : 'email@domain.com',<br>
'isLecturer' : true,<br>
'seToken' : 'dds2d-sfvvsf-qqq-fdf33-sfaa',<br>
'avatar_url' : 'http://location.domain.com/image.jpg',<br>
'isFirstLogin' : false,<br>
'campuses_id_list': ['22314','243512',...,'356'],<br>
'classes_id_list': ['22314','243512',...,'356']<br>
}
</code>
<br>
403 - Invalid Token
'''
query = User.all()
query.filter("seToken = ", token)
for u in query.run(limit=5):
return Response(response=u.to_JSON(),
status=201,
mimetype="application/json") # Real response!
return Response(response=json.dumps({'message' : 'No User Found'}),
status=400,
mimetype="application/json")
@app.route('/githubOAuth')
@ -229,162 +198,6 @@ def oauth(oauth_token):
return cookieMonster(user.seToken)
@app.route('/api/Campuses/create/<string:token>', methods=['POST'])
@auto.doc()
def create_campus(token):
"""
<span class="card-title">This call will create a new campus in the DB</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- JSON Object, Example: <br>
{<br>
'title': 'Campus name',<br>
'email_ending': '@campus.ac.com',<br>
'avatar_url': 'http://location.domain.com/image.jpg'<br>
}<br>
<br>
<br>
<b>Response</b>
<br>
201 - Created
<br>
403 - Invalid Token/Forbidden
"""
if not request.data:
return Response(response=json.dumps({'message': 'Bad Request'}),
status=400,
mimetype="application/json")
payload = json.loads(request.data)
if not is_lecturer(token): #todo: change to lecturer id
return Response(response=json.dumps({'message': 'Invalid token or not a lecturer!'}),
status=403,
mimetype="application/json")
user = get_user_by_token(token)
#todo: check legality
try:
campus = Campus(title=payload['title'], email_ending=payload['email_ending'], master_user_id=user.key().id(), avatar_url=payload['avatar_url'])
except Exception:
return Response(response=json.dumps({'message': 'Bad Request'}),
status=400,
mimetype="application/json")
db.put(campus)
db.save
return Response(response=json.dumps(campus.to_JSON()),
status=201,
mimetype="application/json")
# @app.route('/api/Courses/create/<string:token>', methods=['POST'])
# @auto.doc()
# def create_course(token):
# """
# This call will create a new campus in the DB
# :param token: user seToken
# Payload
# {
# 'courseName': self.courseName,
# 'campusName': self.campusName,
# 'projects': self.projects
# 'startDate': self.startDate
# 'endDate': self.endDate
# 'taskFlag': self.taskFlag
# }
#
# :return:
# code 200
# """
# if not request.data:
# return Response(response=json.dumps({'message': 'Bad Request'}),
# status=400,
# mimetype="application/json")
# payload = json.loads(request.data)
# if not is_lecturer(token): #todo: change to lecturer id
# return Response(response=json.dumps({'message': 'Invalid token or not a lecturer!'}),
# status=403,
# mimetype="application/json")
#
# user = get_user_by_token(token)
#
# #todo: check legality
#
#
# try:
# course = Course(courseName=payload['courseName'], campusName=payload['campusName'], projects=payload['projects'], startDate=payload['startDate'], endDate=payload['endDate'], taskFlag=payload['taskFlag'])
# except Exception:
# return Response(response=json.dumps({'message': 'Bad Request'}),
# status=400,
# mimetype="application/json")
#
# db.put(course)
# db.save
# return Response(response=json.dumps(course.to_JSON()),
# status=200,
# mimetype="application/json")
#
#
#
@app.route('/api/Campuses/<string:token>', methods=['GET'])
@auto.doc()
def get_campuses(token):
"""
<span class="card-title">This Call will return an array of all Campuses available</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- NONE <br>
<br>
<br>
<b>Response</b>
<br>
200 - JSON Array, Example:<br>
[<br>
{
'title': 'JCE',<br>
'email_ending': '@post.jce.ac.il',<br>
'master_user_id': 123453433341, (User that created the campus)<br>
'avatar_url': 'http://some.domain.com/imagefile.jpg'<br>
},<br>
....<br>
{<br>
...<br>
}req<br>
]<br>
<br>
403 - Invalid Token<br>
500 - Server Error
"""
if is_user_token_valid(token):
arr = []
query = Campus.all()
for c in query.run():
arr.append(dict(json.loads(c.to_JSON())))
print arr
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
else:
return Response(response=json.dumps({'message': 'Invalid Token'}),
status=403,
mimetype="application/json")
@app.route('/login')
@ -433,3 +246,5 @@ def cookieMonster(uid):
response = app.make_response(redirect_to_home )
response.set_cookie('com.sehub.www',value=uid)
return response

135
SE_API/CampusRoutes.py Normal file
View file

@ -0,0 +1,135 @@
__author__ = 'Aran'
from flask import Blueprint
import json
from GithubAPI.GithubAPI import GitHubAPI_Keys
from google.appengine.ext import db
import requests
import datetime
from flask import Flask, request, render_template, redirect, abort, Response
from flask.ext.github import GitHub
from flask.ext.cors import CORS, cross_origin
from flask.ext.autodoc import Autodoc
# DB Models
from models.Campus import Campus
#Validation Utils Libs
from SE_API.Validation_Utils import *
from SE_API.Respones_Utils import *
campus_routes = Blueprint("campus_routes", __name__)
auto = Autodoc()
@campus_routes.route('/api/campuses/create/<string:token>', methods=['POST'])
@auto.doc()
def create_campus(token):
"""
<span class="card-title">This call will create a new campus in the DB</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- JSON Object, Example: <br>
{<br>
'title': 'Campus name',<br>
'email_ending': '@campus.ac.com',<br>
'avatar_url': 'http://location.domain.com/image.jpg'<br>
}<br>
<br>
<br>
<b>Response</b>
<br>
201 - Created
<br>
403 - Invalid Token/Forbidden
"""
if not request.data:
return bad_request()
payload = json.loads(request.data)
if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
#todo: check legality
try:
campus = Campus(title=payload['title'], email_ending=payload['email_ending'], master_user_id=user.key().id(), avatar_url=payload['avatar_url'])
except Exception:
return bad_request()
db.put(campus)
db.save
return Response(response=campus.to_JSON(),
status=201,
mimetype="application/json")
@campus_routes.route('/api/campuses/<string:token>', methods=['GET'])
@auto.doc()
def get_campuses(token):
"""
<span class="card-title">This Call will return an array of all Campuses available</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- NONE <br>
<br>
<br>
<b>Response</b>
<br>
200 - JSON Array, Example:<br>
[<br>
{
'title': 'JCE',<br>
'email_ending': '@post.jce.ac.il',<br>
'master_user_id': 123453433341, (User that created the campus)<br>
'avatar_url': 'http://some.domain.com/imagefile.jpg'<br>
},<br>
....<br>
{<br>
...<br>
}req<br>
]<br>
<br>
403 - Invalid Token<br>
500 - Server Error
"""
if is_user_token_valid(token):
arr = []
query = Campus.all()
for c in query.run():
arr.append(dict(json.loads(c.to_JSON())))
print arr
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
else:
return forbidden("Invalid Token")
@campus_routes.route('/api/campuses/help')
def documentation():
return auto.html()

88
SE_API/CourseRoutes.py Normal file
View file

@ -0,0 +1,88 @@
__author__ = 'Aran'
from flask import Blueprint
import json
from GithubAPI.GithubAPI import GitHubAPI_Keys
from google.appengine.ext import db
import requests
import datetime
from flask import Flask, request, render_template, redirect, abort, Response
from flask.ext.github import GitHub
from flask.ext.cors import CORS, cross_origin
from flask.ext.autodoc import Autodoc
# DB Models
from models.Course import Course
#Validation Utils Libs
from SE_API.Validation_Utils import *
from SE_API.Respones_Utils import *
course_routes = Blueprint("course_routes", __name__)
auto = Autodoc()
@course_routes.route('/api/courses/create/<string:token>', methods=['POST'])
@auto.doc()
def create_course(token):
"""
This call will create a new campus in the DB
:param token: user seToken
Payload
{
'courseName': self.courseName,
'campusName': self.campusName,
'projects': self.projects
'startDate': self.startDate
'endDate': self.endDate
'taskFlag': self.taskFlag
}
:return:
code 200
"""
if not request.data:
return bad_request()
payload = json.loads(request.data)
if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
#todo: check legality
try:
start_date = datetime.date(payload['startDate']['year'],payload['startDate']['month'],payload['startDate']['day'])
end_date = datetime.date(payload['endDate']['year'],payload['endDate']['month'],payload['endDate']['day'])
course = Course(courseName=payload['courseName'], campusName=payload['campusName'],
startDate=start_date, endDate=end_date)
try:
course.projects=payload['projects']
except Exception:
pass
except Exception:
return bad_request()
db.put(course)
db.save
return Response(response=course.to_JSON(),
status=201,
mimetype="application/json")
@course_routes.route('/api/courses/help')
def documentation():
return auto.html()

127
SE_API/Email_Utils.py Normal file
View file

@ -0,0 +1,127 @@
__author__ = 'sagi'
from google.appengine.api import mail
def send_validation_email(token, email, name):
emailSuffix = str(email).split('@')[1]
message = mail.EmailMessage(sender="SE-Hub Support <se-hub@appspot.gserviceaccount.com>",
subject="SE-Hub Activate Account")
message.to = email
message.body = """
Dear """+name+""":
To Activate your SE-Hub Account please click on the link below:<br>
http://se-hub.appspot.com/api/validation/confirm/"""+token+"""|"""+emailSuffix+"""
to get access to your Campus :)
Please let us know if you have any questions.
SE-Hub (c) 2015 niptop Team.
"""
message.html = """
<html><head></head><body>
<div>
<center>
<img src='https://cloud.githubusercontent.com/assets/2984053/6825467/7c9d0402-d303-11e4-9827-62a6d66f937a.png'>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</center>
</div>
<div style='width:70%'>
<h1>Hey """+name+"""- Just one More Step...</h1>
<h3>Dear """+name+""":</h3>
To Activate your SE-Hub Account please click on the link below:<br>
http://se-hub.appspot.com/api/validation/confirm/"""+token+"""|"""+emailSuffix+"""
to access you virtual class.
</div>
<br><br>
Please let us know if you have any questions.
<br>
SE-Hub (c) 2015 niptop Team.
</body>
</html>
"""
message.send()
def send_create_campus_request(email, name, campus_name):
message = mail.EmailMessage(sender="SE-Hub Support <se-hub@appspot.gserviceaccount.com>",
subject="SE-Hub: "+campus_name+" Is Being Evaluated")
message.to = email
message.body = """
Dear """+name+""":
Thank You For Choosing SE-Hub!
Your Request for creating a new Campus named """+campus_name + """
is Being Evaluated.
You Will Receive an e-mail When We finish the process<br>
Please let us know if you have any questions.
SE-Hub (c) 2015 niptop Team.
"""
message.html = """
<html><head></head><body>
<div>
<center>
<img src='https://cloud.githubusercontent.com/assets/2984053/6825467/7c9d0402-d303-11e4-9827-62a6d66f937a.png'>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</center>
</div>
<div style='width:70%'>
<h1>Thank You For Choosing SE-Hub!</h1>
<h3>Dear """+name+""":</h3>
Your Request for creating a new Campus named """+campus_name + """
is Being Evaluated.
You Will Receive an e-mail When We finish the process<br>
to access you virtual class.
</div>
<br><br>
Please let us know if you have any questions.
<br>
SE-Hub (c) 2015 niptop Team.
</body>
</html>
"""
message.send()
def notify_se_hub_campus_request(campus, campus_name):
message = mail.EmailMessage(sender="SE-Hub Support <se-hub@appspot.gserviceaccount.com>",
subject="SE-Hub: "+campus_name+" Is Being Evaluated")
message.to = 'se-hub@appspot.gserviceaccount.com'
message.body = """
a new Campus request
"""+str(campus.to_JSON())
message.html = """
<html><head></head><body>
<div>
<center>
<img src='https://cloud.githubusercontent.com/assets/2984053/6825467/7c9d0402-d303-11e4-9827-62a6d66f937a.png'>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</center>
</div>
<div style='width:70%'>
<h1>New Campus!</h1>
<br>
""" + str(campus.to_JSON()) + """
<br>
SE-Hub (c) 2015 niptop Team.
</body>
</html>
"""
message.send()

141
SE_API/ProjectRoutes.py Normal file
View file

@ -0,0 +1,141 @@
__author__ = 'Aran'
from flask import Blueprint
import json
from GithubAPI.GithubAPI import GitHubAPI_Keys
from google.appengine.ext import db
import requests
import datetime
from flask import Flask, request, render_template, redirect, abort, Response
from flask.ext.github import GitHub
from flask.ext.cors import CORS, cross_origin
from flask.ext.autodoc import Autodoc
# DB Models
from models.Project import Project
#Validation Utils Libs
from SE_API.Validation_Utils import *
from SE_API.Respones_Utils import *
project_routes = Blueprint("project_routes", __name__)
auto = Autodoc()
@project_routes.route('/api/projects/Create/<string:token>/<string:id>', methods=['POST'])
@auto.doc()
def create_project(token,id):
"""
<span class="card-title">This call will create a new project in the DB</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- JSON Object, Example: <br>
{<br>
'title': 'Campus name',<br>
'email_ending': '@campus.ac.com',<br>
'avatar_url': 'http://location.domain.com/image.jpg'<br>
}<br>
<br>
<br>
<b>Response</b>
<br>
201 - Created
<br>
403 - Invalid Token/Forbidden
"""
if not request.data:
return bad_request()
payload = json.loads(request.data)
if not is_lecturer(token): #todo: change to lecturer id
return forbidden("Invalid token or not a lecturer!")
user = get_user_by_token(token)
#todo: check legality
try:
project = Project(projectName=payload['projectName'], masterId=user.key().id(), gitRepository=payload['gitRepository'], membersId=[token])
except Exception as e:
print e
return bad_request()
db.put(project)
db.save
return Response(response=project.to_JSON(),
status=201,
mimetype="application/json")
@project_routes.route('/api/projects/get/<string:token>', methods=['GET'])
@auto.doc()
def get_projects(token):
"""
<span class="card-title">This Call will return an array of all projects available</span>
<br>
<b>Route Parameters</b><br>
- seToken: 'seToken'
<br>
<br>
<b>Payload</b><br>
- NONE <br>
<br>
<br>
<b>Response</b>
<br>
200 - JSON Array, Example:<br>
[<br>
{
'title': 'JCE',<br>
'email_ending': '@post.jce.ac.il',<br>
'master_user_id': 123453433341, (User that created the campus)<br>
'avatar_url': 'http://some.domain.com/imagefile.jpg'<br>
},<br>
....<br>
{<br>
...<br>
}req<br>
]<br>
<br>
403 - Invalid Token<br>
500 - Server Error
"""
if is_user_token_valid(token):
arr = []
query = Campus.all()
for c in query.run():
arr.append(dict(json.loads(c.to_JSON())))
print arr
if len(arr) != 0:
return Response(response=json.dumps(arr),
status=200,
mimetype="application/json")
else:
return Response(response=[],
status=200,
mimetype="application/json")
else:
return forbidden("Invalid Token")
@project_routes.route('/api/Projects/<string:token>', methods=['GET'])
@auto.doc()
def get_campuses(token):
pass
@project_routes.route('/api/projects/help')
def documentation():
return auto.html()

View file

@ -3,6 +3,29 @@ __author__ = 'Aran'
from flask import Response
import json
def ok(message='OK'):
return Response(response=json.dumps({'message': message}),
status=200,
mimetype="application/json")
def created(message='Created'):
return Response(response=json.dumps({'message': message}),
status=201,
mimetype="application/json")
def accepted(message='Accepted'):
return Response(response=json.dumps({'message': message}),
status=202,
mimetype="application/json")
def no_content(message='No Content'):
return Response(response=json.dumps({'message': message}),
status=204,
mimetype="application/json")
def bad_request(message='Bad Request'):
return Response(response=json.dumps({'message': message}),
status=400,

75
SE_API/UserRoutes.py Normal file
View file

@ -0,0 +1,75 @@
__author__ = 'Aran'
from flask import Blueprint
import json
from GithubAPI.GithubAPI import GitHubAPI_Keys
from google.appengine.ext import db
import requests
import datetime
from flask import Flask, request, render_template, redirect, abort, Response
from flask.ext.github import GitHub
from flask.ext.cors import CORS, cross_origin
from flask.ext.autodoc import Autodoc
# DB Models
from models.User import User
#Validation Utils Libs
from SE_API.Validation_Utils import *
from SE_API.Respones_Utils import *
user_routes = Blueprint("user_routes", __name__)
auto = Autodoc()
@user_routes.route('/api/users/getUserByToken/<string:token>', methods=["GET"])
@auto.doc()
def getUserByToken(token):
'''
<span class="card-title">This Function is will Activate a user and add tha campus to it</span>
<br>
<b>Route Parameters</b><br>
- validation_token: 'seToken|email_suffix'
<br>
<br>
<b>Payload</b><br>
- NONE
<br>
<br>
<b>Response</b>
<br>
200 - JSON Example:<br>
<code>
{<br>
'username' : 'github_username',<br>
'name' : 'Bob Dylan',<br>
'email' : 'email@domain.com',<br>
'isLecturer' : true,<br>
'seToken' : 'dds2d-sfvvsf-qqq-fdf33-sfaa',<br>
'avatar_url' : 'http://location.domain.com/image.jpg',<br>
'isFirstLogin' : false,<br>
'campuses_id_list': ['22314','243512',...,'356'],<br>
'classes_id_list': ['22314','243512',...,'356']<br>
}
</code>
<br>
403 - Invalid Token
'''
query = User.all()
query.filter("seToken = ", token)
for u in query.run(limit=5):
return Response(response=u.to_JSON(),
status=200,
mimetype="application/json") # Real response!
return bad_request("No User Found")
@user_routes.route('/api/users/help')
def documentation():
return auto.html()

View file

@ -2,7 +2,7 @@ __author__ = 'sagi'
from google.appengine.ext import db
from models.User import User
from models.Campus import Campus
from google.appengine.api import mail
def get_user_by_token(token):
@ -32,50 +32,3 @@ def is_lecturer(token):
if user is None:
return False
return user.isLecturer
def send_validation_email(token, email, name):
emailSuffix = str(email).split('@')[1]
message = mail.EmailMessage(sender="SE-Hub Support <se-hub@appspot.gserviceaccount.com>",
subject="SE-Hub Activate Account")
message.to = email
message.body = """
Dear """+name+""":
To Activate your SE-Hub Account please click on the link below:<br>
http://se-hub.appspot.com/api/validation/confirm/"""+token+"""|"""+emailSuffix+"""
to get access to your Campus :)
Please let us know if you have any questions.
SE-Hub (c) 2015 niptop Team.
"""
message.html = """
<html><head></head><body>
<div>
<center>
<img src='https://cloud.githubusercontent.com/assets/2984053/6825467/7c9d0402-d303-11e4-9827-62a6d66f937a.png'>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
</center>
</div>
<div style='width:70%'>
<h1>Hey """+name+"""- Just one More Step...</h1>
<h3>Dear """+name+""":</h3>
To Activate your SE-Hub Account please click on the link below:<br>
http://se-hub.appspot.com/api/validation/confirm/"""+token+"""|"""+emailSuffix+"""
to access you virtual class.
</div>
<br><br>
Please let us know if you have any questions.
<br>
SE-Hub (c) 2015 niptop Team.
</body>
</html>
"""
message.send()

26
Testing/CampusAPI_Test.py Normal file
View file

@ -0,0 +1,26 @@
__author__ = 'etye'
import unittest
import requests
from Testing.config import __CONFIG__
class UserTestPlan(unittest.TestCase):
def setUpClass(cls):
debug = __CONFIG__['DEBUG']
if debug:
url = __CONFIG__['PATHS']['DEBUG']
else:
url = __CONFIG__['PATHS']['PRODUCTION']
cls.url_ = url
request = requests.get(url+'api/qa/init')
if 200 <= request.status_code <= 299:
print 'Initialized'
def test_Campuses_invalid(self):
r = requests.get(self.__class__.url_+'api/Campuses/invalidtoken')
self.assertEquals(r.status_code, 403)
def test_Campuses_valid(self):
r = requests.get(self.__class__.url_+'api/Campuses/'+__CONFIG__['TOKENS']['STUDENT'])
self.assertEquals(r.status_code, 200)
self.assertEquals(r.json()['username'], 'qa_student')
if __name__ == '__main__':
unittest.main()

37
Testing/UserAPI_Test.py Normal file
View file

@ -0,0 +1,37 @@
__author__ = 'etye'
import unittest
import requests
from Testing.config import __CONFIG__
class UserTestPlan(unittest.TestCase):
@classmethod
def setUpClass(cls):
debug = __CONFIG__['DEBUG']
if debug:
url = __CONFIG__['PATHS']['DEBUG']
else:
url = __CONFIG__['PATHS']['PRODUCTION']
cls.url_ = url
request = requests.get(url+'api/qa/init')
if 200 <= request.status_code <= 299:
print 'Initialized'
def test_getUserByToken_invalid(self):
r = requests.get(self.__class__.url_+'api/getUserByToken/invalidtoken')
self.assertEquals(r.status_code, 403)
def test_getUserByToken_valid(self):
r = requests.get(self.__class__.url_+'api/getUserByToken/'+__CONFIG__['TOKENS']['STUDENT'])
self.assertEquals(r.status_code, 200)
self.assertEquals(r.json()['username'], 'qa_student')
def test_getUserByToken_empty(self):
r = requests.get(self.__class__.url_+'api/getUserByToken/')
self.assertEquals(r.status_code, 400)
if __name__ == '__main__':
unittest.main()

1
Testing/__init__.py Normal file
View file

@ -0,0 +1 @@
__author__ = 'etye'

14
Testing/config.py Normal file
View file

@ -0,0 +1,14 @@
__author__ = 'etye'
__CONFIG__ = {
'DEBUG': True,
'PATHS': {
'DEBUG': 'http://localhost:8080/',
'PRODUCTION': 'http://se-hub.appspot.com/'
},
'TOKENS':{
'STUDENT': '_QA_TOKEN_TEST_STUDENT',
'LECTURER': '_QA_TOKEN_TEST_LECTURER'
}
}

View file

@ -6,17 +6,23 @@ from google.appengine.ext import db
class Course(db.Model):
courseName = db.StringProperty(required=True)
campusName = db.StringProperty(required=True)
projects = db.StringListProperty(required=True)
projects = db.StringListProperty(required=True,default=[])
startDate = db.DateProperty(required=True)
endDate = db.DateProperty(required=False)
taskFlag = db.BooleanProperty(required=True)
endDate = db.DateProperty(required=True)
def to_JSON(self):
data = {'courseName' : self.courseName,
'campusName' : self.campusName,
'projects' : self.projects,
'startDate' : self.startDate,
'endDate' : self.endDate,
'taskFlag' : self.taskFlag,
'startDate' : {
'year': self.startDate.year,
'month': self.startDate.month,
'day': self.startDate.day,
},
'endDate' : {
'year': self.endDate.year,
'month': self.endDate.month,
'day': self.endDate.day,
}
}
return json.dumps(data)

View file

@ -5,13 +5,15 @@ from google.appengine.ext import db
class Project(db.Model):
projectName = db.StringProperty(required=True)
grade = db.IntegerProperty(required=True)
logo_url = db.StringProperty(required=True)
masterId = db.IntegerProperty(required=True)
grade = db.IntegerProperty(required=True, default=0)
logo_url = db.StringProperty(required=False)
gitRepository = db.StringProperty(required=True)
membersId = db.StringListProperty(required=True)
def to_JSON(self):
data = {'projectName' : self.projectName,
'masterId' : self.masterId,
'grade' : self.grade,
'logo_url' : self.logo_url,
'gitRepository' : self.gitRepository,