Exemple #1
0
def test_get_events(self):
    post(self.get_url('/event'),
         data={
             "event": "Today's first event",
             "date": str(datetime.date.today())
         })

    post(self.get_url('/event'),
         data={
             "event": "Today's second event",
             "date": str(datetime.date.today())
         })

    post(self.get_url('/event'),
         data={
             "event": "Tomorrow event",
             "date": str(datetime.date.today() + datetime.timedelta(days=1))
         })

    response = get(self.get_url('/event'))

    data = get_json_from_response(response)

    if type(data) != list:
        raise WrongAnswer("The response should be a list with events!")

    if len(data) < 3:
        raise WrongAnswer(
            "The response list should contain at least 3 events!")

    find_event(data, str(datetime.date.today()), "Today's first event")
    find_event(data, str(datetime.date.today()), "Today's second event")

    return correct()
Exemple #2
0
    async def test_main_page_structure_async(self):
        browser = await self.launch_and_get_browser()
        page = await browser.newPage()

        await page.goto(self.get_url())

        cards_div = await page.querySelector('div.cards')

        if cards_div is None:
            raise WrongAnswer("Can't find <div> block with class 'cards'")

        button = await self.get_submit_button(page)

        if button is None:
            raise WrongAnswer(
                "Can't find a button with 'submit-button' class!")

        input_field = await self.get_input_field(page)

        if input_field is None:
            raise WrongAnswer("Can't find input field with 'input-city' id!")

        await self.check_cards_in_the_page(page, 0)

        await self.close_browser(browser)

        return CheckResult.correct()
Exemple #3
0
    def from_output(cls, string_field: str, field_number: int = 1):
        grid = Grid()

        field_lines = list(map(str.strip, string_field.splitlines()))
        field_lines = list(
            filter(
                lambda field_line: str(field_line).startswith('|') and str(
                    field_line).endswith('|'), field_lines))

        if len(field_lines) < 3 * field_number:
            raise WrongAnswer(
                "Expected not less than " + str(field_number) +
                " grids in the output!\n" +
                "Make sure you print the game grids in the correct format!")

        field_lines = field_lines[field_number * 3 - 3:field_number * 3]

        for i, line in enumerate(field_lines):
            if len(line) != 9:
                raise WrongAnswer(
                    "Can't parse the game field. The following line has wrong length:\n"
                    + line)
            for j in range(3):
                grid.__grid[i][j] = CellState.get(line[j * 2 + 2])

        return grid
Exemple #4
0
    async def check_cards_in_the_page(cls, page, cards_number):
        cards = await page.querySelectorAll('div.card')

        if len(cards) != cards_number:
            raise WrongAnswer(
                f"Found {len(cards)} <div> blocks with class 'card', but should be {cards_number}!"
            )

        for card in cards:
            degrees = await card.querySelector('div.degrees')
            if degrees is None:
                raise WrongAnswer(
                    "One of the <div> blocks with card class 'card' doesn't contain <div> block with class 'degrees'"
                )
            state = await card.querySelector('div.state')
            if state is None:
                raise WrongAnswer(
                    "One of the <div> blocks with card class 'card' doesn't contain <div> block with class 'state'"
                )
            city = await card.querySelector('div.city')
            if city is None:
                raise WrongAnswer(
                    "One of the <div> blocks with card class 'card' doesn't contain <div> block with class 'city'"
                )
            button = await card.querySelector('button.delete-button')
            if button is None:
                raise WrongAnswer(
                    "One of the <div> blocks with card class 'card' doesn't contain a button with class 'delete-button'"
                )
Exemple #5
0
    def all_grids_from_output(cls, string_field: str):

        grid_list = list()

        field_lines = list(map(str.strip, string_field.splitlines()))
        field_lines = list(
            filter(
                lambda field_line: str(field_line).startswith('|') and str(
                    field_line).endswith('|'), field_lines))

        if len(field_lines) % 3 != 0:
            raise WrongAnswer(
                "Wrong grid output format! Each grid should contain 3 lines that starts and ends with '|' symbol!"
            )

        for i in range(len(field_lines) // 3):
            grid_lines = field_lines[i * 3:i * 3 + 3]

            grid = Grid()

            for j, line in enumerate(grid_lines):
                if len(line) != 9:
                    raise WrongAnswer(
                        "Can't parse the game field. The following line has wrong length:\n"
                        + line)
                for k in range(3):
                    grid.__grid[j][k] = CellState.get(line[k * 2 + 2])

            grid_list.append(grid)

        return grid_list
Exemple #6
0
def get_json_from_response(response):
    error_message = "The server response should be in JSON format!"
    try:
        if not isinstance(response.json(), dict) and not isinstance(
                response.json(), list):
            raise WrongAnswer(error_message)
        return response.json()
    except Exception:
        raise WrongAnswer(error_message)
Exemple #7
0
def check_key_value_in_dict(dictionary, key, value=None):
    if key not in dictionary:
        raise WrongAnswer(f"Can't find '{key}' key in the response!")

    if not value:
        return

    if dictionary[key] != value:
        raise WrongAnswer(f"The '{key}' key value is wrong!\n"
                          f"Expected  : '{value}'\n"
                          f"Your value: '{dictionary[key]}'")
Exemple #8
0
def check_get_delete_by_id(self):
    response = get(self.get_url('/event'))

    data = get_json_from_response(response)

    if type(data) != list:
        raise WrongAnswer("The response should be a list with events!")

    if len(data) == 0:
        raise WrongAnswer("Looks like you return an empty list of events!")

    event_id = data[-1]['id']

    response = get(self.get_url(f'/event/{event_id}'))

    data = get_json_from_response(response)

    check_key_value_in_dict(data, 'id')

    check_key_value_in_dict(data, 'event')

    check_key_value_in_dict(data, 'date')

    response = delete(self.get_url(f'/event/{event_id}'))

    data = get_json_from_response(response)
    check_status_code(
        response, 200,
        'After deleting an existing event you should response with status code 200!'
    )

    check_key_value_in_dict(data, 'message', 'The event has been deleted!')

    response = delete(self.get_url(f'/event/{event_id}'))

    data = get_json_from_response(response)
    check_status_code(
        response, 404,
        "If the user tries to delete an event that doesn't exists you should response with status code 404!"
    )

    check_key_value_in_dict(data, 'message', "The event doesn't exist!")

    response = get(self.get_url(f'/event/{event_id}'))

    data = get_json_from_response(response)
    check_status_code(
        response, 404,
        "If the user tries to delete an event that doesn't exists you should response with status code 404!"
    )

    check_key_value_in_dict(data, 'message', "The event doesn't exist!")

    return correct()
Exemple #9
0
    async def test_flash_message_async(self):
        print(123123)
        browser = await self.launch_and_get_browser()
        page = await browser.newPage()
        await page.goto(self.get_url())

        input_field = await self.get_input_field(page)
        await input_field.type('Idaho')

        button = await self.get_submit_button(page)

        await asyncio.gather(
            page.waitForNavigation(),
            button.click(),
        )

        input_field = await self.get_input_field(page)
        await input_field.type('Idaho')

        button = await self.get_submit_button(page)

        await asyncio.gather(
            page.waitForNavigation(),
            button.click(),
        )

        html = await page.content()

        if 'The city has already been added to the list!' not in html:
            raise WrongAnswer(
                f'If the user tires to add a city that is already was added you should print '
                f'"The city has already been added to the list!"')

        input_field = await self.get_input_field(page)
        await input_field.type('The city that doesn\'t exist!')

        button = await self.get_submit_button(page)

        await asyncio.gather(
            page.waitForNavigation(),
            button.click(),
        )

        html = await page.content()

        if 'The city doesn\'t exist!' not in html:
            raise WrongAnswer(
                f'If the user tires to add a city that is already was added you should print "The city doesn\'t exist!"'
            )
Exemple #10
0
def test_today_events(self):
    response = get(self.get_url('/event/today'))

    data = get_json_from_response(response)

    if type(data) != list:
        raise WrongAnswer("The response should be a list with events!")

    if len(data) < 2:
        raise WrongAnswer(
            "The response list should contain at least 2 today's events!")

    check_today_events(data)

    return correct()
Exemple #11
0
    async def test_refresh_async(self):
        browser = await self.launch_and_get_browser()
        page = await browser.newPage()
        await page.goto(self.get_url())

        input_field = await self.get_input_field(page)
        await input_field.type('Idaho')

        button = await self.get_submit_button(page)

        await asyncio.gather(
            page.waitForNavigation(),
            button.click(),
        )

        cards_div = await page.querySelector('div.cards')

        if cards_div is None:
            raise WrongAnswer("Can't find <div> block with class 'cards'")

        await self.check_cards_in_the_page(page, 3)

        await page.reload()

        await self.check_cards_in_the_page(page, 3)
Exemple #12
0
 def generate(self):
     if os.path.exists('event.db'):
         try:
             os.remove('event.db')
         except Exception:
             raise WrongAnswer("Can't delete the database file before starting the tests!")
     return []
Exemple #13
0
 async def test_response_async(self):
     browser = await self.launch_and_get_browser()
     page = await browser.newPage()
     try:
         await page.goto(self.get_url())
     except Exception:
         raise WrongAnswer(
             f"Can't access the main page with URL '{self.get_url()}'")
     await self.close_browser(browser)
Exemple #14
0
 def generate(self):
     try:
         if os.path.exists('web/weather.db'):
             os.remove('web/weather.db')
     except Exception as ignored:
         raise WrongAnswer(
             f"Looks like your 'weather.db' database file is blocked. "
             f"Stop your apps that connects to that database!")
     return []
Exemple #15
0
def find_event(events, date, event_name):
    for event in events:
        check_key_value_in_dict(event, 'id')
        check_key_value_in_dict(event, 'date')
        check_key_value_in_dict(event, 'event')
        if event['date'] == date and event['event'] == event_name:
            return
    raise WrongAnswer("Can't find event with the following data:\n"
                      f"'event': {event_name}\n"
                      f"'date': {date}")
Exemple #16
0
def check_today_events(events):
    today = datetime.date.today()

    for event in events:
        check_key_value_in_dict(event, 'date')
        if event['date'] != str(today):
            raise WrongAnswer(
                "/event/today should return a list of today's events!\n"
                "Found wrong event:\n"
                f"{event}")
Exemple #17
0
    def from_line(cls, line):
        if len(line) != 9:
            raise WrongAnswer("Wrong input length. Expected 9.\nFound " +
                              str(len(line)))

        grid = Grid()

        for i, char in enumerate(line):
            grid.__grid[(int(i / 3))][i % 3] = CellState.get(char)

        return grid
Exemple #18
0
    def get(cls, char: str):

        char_to_cell_state = {
            'X': cls.X,
            'O': cls.O,
            ' ': cls.EMPTY,
            '_': cls.EMPTY
        }

        if char not in char_to_cell_state:
            raise WrongAnswer('Bad symbol ' + char + ' in the game grid')
        return char_to_cell_state[char]
Exemple #19
0
    def check_grid_sequence(cls, grids):

        if len(grids) <= 1:
            return

        for i in range(1, len(grids) - 1):
            prev_grid = grids[i - 1]
            grid = grids[i]

            if not grid.is_valid_grid():
                raise WrongAnswer(
                    "Impossible grid was printed! The difference between Os and Xs in the grid is greater than 1:\n"
                    + str(grid))

            if not prev_grid.is_correct_next_grid(grid):
                raise WrongAnswer("After making a move on grid\n" +
                                  str(prev_grid) + "\n it can't become\n" +
                                  str(grid))

            last_grid = grids[-1]

            if last_grid.get_game_state() == GameState.NOT_FINISHED:
                raise WrongAnswer("Last grid is not terminal!\n" +
                                  str(last_grid))
Exemple #20
0
    async def test_add_city_async(self):
        browser = await launch()
        page = await browser.newPage()
        await page.goto(self.get_url())

        input_field = await page.querySelector('input#input-city')
        await input_field.type('London')

        button = await page.querySelector('button.submit-button')

        await asyncio.gather(
            page.waitForNavigation(),
            button.click(),
        )

        cards_div = await page.querySelector('div.cards')

        if cards_div is None:
            raise WrongAnswer("Can't find <div> block with class 'cards'")

        await self.check_cards_in_the_page(page, 1)
Exemple #21
0
def delete(url):
    try:
        return requests.delete(url)
    except Exception as _:
        raise WrongAnswer(f"Can't make a DELETE request for '{url}'")
Exemple #22
0
def post(url, data):
    try:
        return requests.post(url, data)
    except Exception as _:
        raise WrongAnswer(f"Can't make a POST request for '{url}' "
                          f"with the following request body:\n{data}")
Exemple #23
0
def get(url):
    try:
        return requests.get(url)
    except Exception as _:
        raise WrongAnswer(f"Can't make a GET request for '{url}'")
Exemple #24
0
 async def launch_and_get_browser(self):
     try:
         return await launch(self.run_args)
     except Exception as error:
         raise WrongAnswer(str(error))
Exemple #25
0
 async def get_submit_button(self, page):
     button = await page.querySelector('button.submit-button')
     if button is None:
         raise WrongAnswer(
             "Can't find a button with 'submit-button' class!")
     return button
Exemple #26
0
 async def get_input_field(self, page):
     input_field = await page.querySelector('input#input-city')
     if input_field is None:
         raise WrongAnswer("Can't find input field with 'input-city' id!")
     return input_field
Exemple #27
0
def check_events_in_range(self):
    post(self.get_url('/event'),
         data={
             "event": "Event1",
             "date": str(datetime.date.today() + datetime.timedelta(days=10))
         })

    post(self.get_url('/event'),
         data={
             "event": "Event2",
             "date": str(datetime.date.today() + datetime.timedelta(days=15))
         })

    post(self.get_url('/event'),
         data={
             "event": "Event3",
             "date": str(datetime.date.today() + datetime.timedelta(days=20))
         })

    response = get(
        self.get_url(
            f'/event?start_time={str(datetime.date.today() + datetime.timedelta(days=9))}'
            f'&end_time={str(datetime.date.today() + datetime.timedelta(days=11))}'
        ))

    data = get_json_from_response(response)

    if type(data) != list:
        raise WrongAnswer("The response should be a list with events!")

    if len(data) != 1:
        raise WrongAnswer(
            f"Expected only one event in a range from {str(datetime.date.today() + datetime.timedelta(days=9))} "
            f"to {str(datetime.date.today() + datetime.timedelta(days=11))}")

    check_key_value_in_dict(data[0], 'event', 'Event1')

    response = get(
        self.get_url(
            f'/event?start_time={str(datetime.date.today() + datetime.timedelta(days=14))}'
            f'&end_time={str(datetime.date.today() + datetime.timedelta(days=16))}'
        ))

    data = get_json_from_response(response)

    if type(data) != list:
        raise WrongAnswer("The response should be a list with events!")

    if len(data) != 1:
        raise WrongAnswer(
            f"Expected only one event in a range from {str(datetime.date.today() + datetime.timedelta(days=14))} "
            f"to {str(datetime.date.today() + datetime.timedelta(days=16))}")

    check_key_value_in_dict(data[0], 'event', 'Event2')

    response = get(
        self.get_url(
            f'/event?start_time={str(datetime.date.today() + datetime.timedelta(days=19))}'
            f'&end_time={str(datetime.date.today() + datetime.timedelta(days=21))}'
        ))

    data = get_json_from_response(response)

    if type(data) != list:
        raise WrongAnswer("The response should be a list with events!")

    if len(data) != 1:
        raise WrongAnswer(
            f"Expected only one event in a range from {str(datetime.date.today() + datetime.timedelta(days=19))} "
            f"to {str(datetime.date.today() + datetime.timedelta(days=21))}")

    check_key_value_in_dict(data[0], 'event', 'Event3')

    return correct()
Exemple #28
0
 def get_move(cls, from_grid, to_grid):
     for i in range(3):
         for j in range(3):
             if from_grid.__grid[i][j] != to_grid.__grid[i][j]:
                 return Position(i, j)
     raise WrongAnswer("After making a move the grid was the same!")
Exemple #29
0
 def test(self):
     program = TestedProgram()
     program.start()
     raise WrongAnswer('')
Exemple #30
0
def check_status_code(response, correct_code, error_message):
    if response.status_code != correct_code:
        raise WrongAnswer(error_message)