Example #1
0
    def test_list(self):
        """
        Test if API returns list of all todos
        """
        todo = {"title": 'Write API tests',
                "order": self.order,
                "user_id":1}
        
        todo1 = create(self, url='/api', inp=todo)

        todo = {"title": 'Write automation tests',
                "order": self.order,
                "user_id":1}

        todo2 = create(self, url='/api', inp=todo)
        
        response = self.client.get(
            '/api/todos/',
            content_type='application/json')
        if response.status_code != 200:
            assert response.status_code == 404
        
        todos_list = json.loads(response.data)
        
        todos = [todo1,todo2]
        assert todos_list['todos'] == todos
Example #2
0
    def test_create(self):
        """
        Test if app creates new todo item
        """
        todo1 = create(self, 'Write app tests')
        assert todo1['title'] == 'Write app tests'
        assert todo1['order'] == 1
        assert not todo1['completed']
        assert todo1['user'] == 'tsheasha'

        todo2 = create(self,
            'Write automation tests', completed=True)
        assert todo2['title'] == 'Write automation tests'
        assert todo2['order'] == 2
        assert todo2['completed']
        assert todo2['user'] == 'tsheasha'

        logout(self)
        login(self, "nahla", "password")

        todo3 = create(self,
            'Write automation tests', completed=True)
        assert todo3['title'] == 'Write automation tests'
        assert todo3['order'] == 3
        assert todo3['completed']
        assert todo3['user'] == 'nahla'
Example #3
0
    def test_read(self):
        """
        Test if app can get a single item by ID
        """
        todo1 = create(self, 'Write app tests')
        todo2 = create(self,
            'Write automation tests', completed=True)

        read1 = read(self, todo1['id'])
        read2 = read(self, todo2['id'])

        assert read1 == todo1
        assert read2 == todo2

        read3 = read(self, todo2['id'] + 1)
        assert read3 is None
Example #4
0
    def test_list(self):
        """
        Test if app returns list of all todos
        """
        todo1 = create(self, 'Write app tests')
        todo2 = create(self,
            'Write automation tests', completed=True)

        response = self.client.get(
            '/todos/',
            content_type='application/json')
        if response.status_code != 200:
            assert response.status_code == 404
        
        todos_list = json.loads(response.data)

        todos = [todo1,todo2]
        assert todos_list == todos
Example #5
0
    def test_read(self):
        """
        Test if API can get a single item by ID
        """
        todo = {"title": 'Write API tests',
                "order": self.order,
                "user_id":1}

        todo = create(self, url='/api', inp=todo)

        read1 = read(self, todo['id'], url='/api')

        assert read1 == todo
Example #6
0
    def test_create(self):
        """
        Test if API creates new todo item
        """
        todo = {"title": 'Write API tests',
                "order": self.order,
                "user_id":1}

        todo1 = create(self, url='/api', inp=todo)
        assert todo1['title'] == 'Write API tests'
        assert todo1['order'] == 1
        assert not todo1['completed']
        assert todo1['user'] == 'tsheasha'        

        todo = {"title": 'Write automation tests',
                "order": self.order,
                "user_id":1}

        todo2 = create(self, url='/api', inp=todo)
        assert todo2['title'] == 'Write automation tests'
        assert todo2['order'] == 2
        assert not todo2['completed']
        assert todo2['user'] == 'tsheasha'

        assert todo1['id'] != todo2['id']

        logout(self)
        login(self, "nahla", "password")
        
        todo = {"title": 'Write automation tests',
                "order": self.order,
                "user_id":2}
        
        todo3 = create(self, url='/api', inp=todo)
        assert todo3['title'] == 'Write automation tests'
        assert todo3['order'] == 3
        assert not todo3['completed']
        assert todo3['user'] == 'nahla'
Example #7
0
    def test_update(self):
        """
        Test if app can update order of a todo item by ID
        """
        todo = create(self, 'Write app tests')
        id = todo['id']

        updates = dict(**todo)
        updates['completed'] = True
        updates['title'] = 'Write all app tests'

        req = self.client.put(
            '/todos/%d' % id,
            data=json.dumps(updates),
            content_type='application/json')
        updated = json.loads(req.data)

        assert updated == updates
        assert read(self, id) == updates
Example #8
0
    def test_update(self):
        """
        Test if API can update order of a todo item by ID
        """
        payload = {"title": 'Write API tests',
                "order": self.order,
                "user_id":1}

        todo = create(self, url='/api', inp=payload)
        id = todo['id']

        updates = {'order': 2}

        req = self.client.put(
            '/api/todos/%d' % id,
            data=updates,
            content_type='application/json')

        assert read(self, id, url='/api')['order'] == 2 
        assert req.status_code == 204 
Example #9
0
def create(json_tracks=None,
           json_file=None,
           json_url=None,
           nb_question=None,
           nb_choice=None,
           with_hint=None):
    json_tracks = json_tracks or util.create(json_file=json_file,
                                             json_url=json_url)
    ordered_tracks = json_tracks.tracks or json_tracks or []
    nb_question = nb_question if nb_question is not None else default_nb_question
    nb_choice = nb_choice if nb_choice is not None else default_nb_choice
    with_hint = with_hint if with_hint is not None else default_with_hint

    # filter track without genre
    ordered_tracks = [
        track for track in ordered_tracks if track.genre is not None
    ]

    # find genres
    genres = {}
    for track_id, track in enumerate(ordered_tracks):
        if track.genre not in genres:
            genres[track.genre] = []
        genres[track.genre].append(track_id)

    # shuffle track ids
    track_ids = range(0, len(ordered_tracks))
    random.shuffle(track_ids)

    # select n tracks
    track_ids = track_ids[:nb_question] if len(
        track_ids) >= nb_question else track_ids

    # prepare game
    game = util.create()
    game.questions = []
    for track_id in track_ids:
        track = ordered_tracks[track_id]

        # prepare question
        question = util.create()

        # prepare theme
        question.theme = util.create()
        question.theme.genre = track.genre

        # prepare audio
        question.audio = util.create()
        question.audio.mp3 = track.mp3

        # prepare choices
        question.choices = []

        # prepare correct choice
        choice = util.create()
        choice.answer = track.artist
        choice.hint = track.title
        choice.correct = True
        question.choices.append(choice)

        # prepare incorrect choices ( from same genre as the correct choice )
        candidate_ids = [
            candidate_id for candidate_id in genres[track.genre]
            if candidate_id != track_id
        ]
        random.shuffle(candidate_ids)
        candidate_ids = candidate_ids[:nb_choice - 1] if len(
            candidate_ids) >= nb_choice - 1 else candidate_ids
        for candidate_id in candidate_ids:
            candidate = ordered_tracks[candidate_id]
            choice = util.create()
            choice.answer = candidate.artist
            if with_hint:
                choice.hint = candidate.title
            question.choices.append(choice)

        # shuffle choices
        random.shuffle(question.choices)

        # add question
        game.questions.append(question)

    return game
Example #10
0
def create(json_tracks=None, json_file=None, json_url=None, nb_question=None, nb_choice=None, with_hint=None):
    json_tracks = json_tracks or util.create(json_file=json_file, json_url=json_url)
    ordered_tracks = json_tracks.tracks or json_tracks or []
    nb_question = nb_question if nb_question is not None else  default_nb_question
    nb_choice = nb_choice if nb_choice is not None else  default_nb_choice
    with_hint = with_hint if with_hint is not None else default_with_hint

    # filter track without genre
    ordered_tracks = [track for track in ordered_tracks if track.genre is not None]

    # find genres
    genres = {}
    for track_id, track in enumerate(ordered_tracks):
        if track.genre not in genres:
            genres[track.genre] = []
        genres[track.genre].append(track_id)

    # shuffle track ids
    track_ids = range(0, len(ordered_tracks))
    random.shuffle(track_ids)

    # select n tracks
    track_ids = track_ids[:nb_question] if len(track_ids) >= nb_question else track_ids

    # prepare game
    game = util.create()
    game.questions = []
    for track_id in track_ids:
        track = ordered_tracks[track_id]

        # prepare question
        question = util.create()

        # prepare theme
        question.theme = util.create()
        question.theme.genre = track.genre

        # prepare audio
        question.audio = util.create()
        question.audio.mp3 = track.mp3

        # prepare choices
        question.choices = []

        # prepare correct choice
        choice = util.create()
        choice.answer = track.artist
        choice.hint = track.title
        choice.correct = True
        question.choices.append(choice)

        # prepare incorrect choices ( from same genre as the correct choice )
        candidate_ids = [candidate_id for candidate_id in genres[track.genre] if candidate_id != track_id]
        random.shuffle(candidate_ids)
        candidate_ids = candidate_ids[:nb_choice-1] if len(candidate_ids) >= nb_choice-1 else candidate_ids
        for candidate_id in candidate_ids:
            candidate = ordered_tracks[candidate_id]
            choice = util.create()
            choice.answer = candidate.artist
            if with_hint:
                choice.hint = candidate.title
            question.choices.append(choice)

        # shuffle choices
        random.shuffle(question.choices)

        # add question
        game.questions.append(question)

    return game
Example #11
0
except Exception as e:
    print "Got wrong options: %s, exit ..." % e
    sys.exit(1)

if not BUILD_PARAMETERS.pkgarch:
    print "Please add the -a parameter for the pkgarch"
    sys.exit(1)
elif BUILD_PARAMETERS.pkgarch and not BUILD_PARAMETERS.pkgarch in PKG_ARCHS:
    print "Wrong pkg-arch, only support: %s, exit ..." % PKG_ARCHS
    sys.exit(1)

app_name = "CrosswalkVersion"
pkg_name = "com.example.crosswalkVersion1"
current_path_tmp = os.getcwd()
project_path = os.path.join(current_path_tmp, app_name)
util.create(app_name, pkg_name, current_path_tmp)

main_version = util.CROSSWALK_VERSION.split('.')[0]

latestVersion = util.getLatestCrosswalkVersion(util.CROSSWALK_BRANCH,
                                               main_version)

pkg_mode_tmp = "core"
apk_name_arch = "armv7"
pack_arch_tmp = "arm"

if BUILD_PARAMETERS.pkgarch and BUILD_PARAMETERS.pkgarch != "arm":
    apk_name_arch = BUILD_PARAMETERS.pkgarch
    if BUILD_PARAMETERS.pkgarch == "x86":
        pack_arch_tmp = "x86"
    elif BUILD_PARAMETERS.pkgarch == "x86_64":
Example #12
0
from flask import Flask, render_template, request, session, redirect, url_for, Response, jsonify
import util
import hashlib
import random

app = Flask(__name__)
app.secret_key = "nothing"
util.create()


@app.route("/")
@app.route("/index")
def index():
    return render_template("index.html")


@app.route("/restaurants", methods=["GET", "POST"])
def restaurants():
    if request.method == "POST":
        form = request.form
        details = form["details"]
        session["details"] = details
        details = [c.strip() for c in details.strip().strip(",").split(";")]
        # address radius ratings categories
        address = details[0]
        radius = int(details[1]) * 1609
        rating = details[2]
        types = [d.strip() for d in details[3].split(",")]
        session["setrad"] = details[1]
        session["setrating"] = rating
        session["addr"] = address
Example #13
0
from flask import Flask, render_template, request, session, redirect, url_for, Response, jsonify
import util
import hashlib
import random

app = Flask(__name__)
app.secret_key = "nothing"
util.create()


@app.route('/')
@app.route('/index')
def index():
    return render_template("index.html")


@app.route('/restaurants', methods=["GET", "POST"])
def restaurants():
    if request.method == "POST":
        form = request.form
        details = form['details']
        session['details'] = details
        details = [c.strip() for c in details.strip().strip(',').split(';')]
        #address radius ratings categories
        address = details[0]
        radius = int(details[1]) * 1609
        rating = details[2]
        types = [d.strip() for d in details[3].split(',')]
        session['setrad'] = details[1]
        session['setrating'] = rating
        session['addr'] = address
Example #14
0
    print "Got wrong options: %s, exit ..." % e
    sys.exit(1)


if not BUILD_PARAMETERS.pkgarch:
    print "Please add the -a parameter for the pkgarch"
    sys.exit(1)
elif BUILD_PARAMETERS.pkgarch and not BUILD_PARAMETERS.pkgarch in PKG_ARCHS:
    print "Wrong pkg-arch, only support: %s, exit ..." % PKG_ARCHS
    sys.exit(1)

app_name = "CrosswalkVersion"
pkg_name = "com.example.crosswalkVersion1"
current_path_tmp = os.getcwd()
project_path = os.path.join(current_path_tmp, app_name)
util.create(app_name, pkg_name, current_path_tmp)

main_version = util.CROSSWALK_VERSION.split('.')[0]

latestVersion = util.getLatestCrosswalkVersion(util.CROSSWALK_BRANCH, main_version)

pkg_mode_tmp = "core"
apk_name_arch = "armv7"
pack_arch_tmp = "arm"

if BUILD_PARAMETERS.pkgarch and BUILD_PARAMETERS.pkgarch != "arm":
    apk_name_arch = BUILD_PARAMETERS.pkgarch
    if BUILD_PARAMETERS.pkgarch == "x86":
        pack_arch_tmp = "x86"
    elif BUILD_PARAMETERS.pkgarch == "x86_64":
        pack_arch_tmp = "x86 --xwalk64bit"
Example #15
0
def fusion_system():
    """
    Fusion system.
    :return: <None>
    """

    # set resource
    print("FusionStudent Platform System starting... please wait.")
    logs.info("FusionStudent Platform System start...")
    classes = {}
    id_pools = {"class": []}
    prepare.upload(classes, id_pools)
    print("FusionStudent Platform System start success.")

    # running system
    while True:
        command = handle(input(">>> ").strip())

        if command == "help":
            help.help_doc()

        elif command == "__test":
            try:
                url = logs.get_path()
                print(url)
            except Exception as e:
                print(traceback.format_exc())
                continue

        elif command.startswith("system"):
            if command == "system version":
                system.show_version()
            elif command == "system help":
                help.help_doc("system")
            elif command == "system exit":
                try:
                    if system.exit_system():
                        logs.info("FusionStudent system soft shutdown.")
                        break
                    else:
                        continue
                except InputError as e:
                    print(str(e))
                    continue

            elif command == "system date":
                print(system.system_date())
            else:
                print("Invalid command input '%s'. "
                      "Please input help for more information." % command)
                logs.error("Invalid command input: %s. 404" % command)
                continue

        elif command.startswith("clear"):
            if command.startswith("clear log"):
                try:
                    command_list = command.split()
                    if len(command_list) <= 2:
                        print("Lose argument for command 'clear log'. "
                              "Please input help for more information.")
                        logs.error("Clear logs failed.")
                        continue
                    command_list = command_list[2:]
                    logs_type = []
                    for i in command_list:
                        if i == "--error":
                            logs_type.append("error")
                        elif i == "--info":
                            logs_type.append("info")
                        elif i == "--warn":
                            logs_type.append("warn")
                        elif i == "--all":
                            logs_type.append("all")
                            break
                        else:
                            logs.error("Clear logs failed. "
                                       "BadRequest: Invalid argument '%s'." %
                                       i)
                            raise InputError(
                                "Invalid argument '%s'. "
                                "Please input help for more information." % i)
                    clears.clear_logs(logs_type)
                    print("Clear log success.")
                except InputError as e:
                    print(str(e))
                    continue

            elif command == "clear help":
                help.help_doc("clear")

            else:
                print("Invalid command input '%s'. "
                      "Please input help for more information." % command)
                logs.error("Invalid command %s input." % command)

        elif command.startswith("class"):
            if command.startswith("class create"):
                try:
                    command_list = command.split()[2:]
                    index = 0
                    type = "class"
                    name = None
                    size = None
                    remark = None
                    while index < len(command_list):
                        if command_list[index] == "--name":
                            index += 1
                            name = command_list[index]
                        elif command_list[index] == "--size":
                            index += 1
                            size = int(command_list[index])
                        elif command_list[index] == "--remark":
                            index += 1
                            remark = command_list[index]
                        else:
                            raise InputError(
                                "Invalid param %s. "
                                "Please input 'help' for more information." %
                                command_list[index])
                        index += 1

                    util.create(type,
                                id_pools,
                                classes,
                                name=name,
                                size=size,
                                remark=remark)
                except InputError as e:
                    print(str(e))
                    continue
                except ValueError:
                    print("BadRequest: Size must be an integer number.")
                    logs.error("Create class failed.\n"
                               "BadRequest: Size must be an integer number.")
                    logs.error(traceback.format_exc())
                except ClassException as e:
                    print(str(e))
                    logs.error("Create class failed. %s" % str(e))
                    logs.error(traceback.format_exc())

            elif command == "class help":
                help.help_doc("class")

            elif command == "class list":
                cls_cmd.class_show(classes)

            elif command.startswith("class delete"):
                try:
                    command_list = command.split()
                    if len(command_list) != 3:
                        print("Invalid command input '%s'. "
                              "Please input help for more information." %
                              command)
                        logs.error("Invalid command %s input." % command)
                        continue

                    uuid = command_list[-1]
                    util.class_delete(classes, uuid)
                except ClassException as e:
                    print(str(e))
                    continue

            elif command.startswith("class show"):
                try:
                    command_list = command.split()
                    if len(command_list) != 3:
                        print("Invalid command input '%s'. "
                              "Please input help for more information." %
                              command)
                        logs.error("Invalid command %s input." % command)
                        continue

                    uuid = command_list[-1]
                    util.show_class(classes, uuid)
                except ClassException as e:
                    print(str(e))
                    continue

            else:
                print("Invalid command input '%s'. "
                      "Please input help for more information." % command)
                logs.error("Invalid command %s input." % command)

        else:
            if command == "":
                continue
            else:
                print("Invalid command input '%s'. "
                      "Please input help for more information." % command)
                logs.error("Invalid command %s input." % command)