Exemple #1
0
def test_ok_err(ok):
    res = Result.Ok(1) if ok else Result.Err(1)
    if ok:
        assert res.ok() == Some(1)
        assert res.err() == NONE
    else:
        assert res.ok() == NONE
        assert res.err() == Some(1)
Exemple #2
0
def test_delete_note_wrong_author(meeting_api):
    note = next(fake_note())
    meeting = next(fake_meeting())
    author = fake_instructor()
    meeting_api.meeting_persistence.get_note.return_value = Some(note)
    meeting_api.meeting_persistence.get_meeting.return_value = Some(meeting)
    assert "not belong" in meeting_api.delete_note(note.note_id,
                                                   author).unwrap_err()
    meeting_api.meeting_persistence.get_note.assert_called_once_with(
        note.note_id)
    meeting_api.meeting_persistence.get_meeting.assert_called_once_with(
        note.meeting_id)
Exemple #3
0
 def find_job(self,
              worker,
              duration: int = None,
              radius=None,
              latitude=None,
              longitude=None) -> Option['Request']:
     has_radius = not (radius is None or latitude is None
                       or longitude is None)
     with self.request_mutex:
         for candidate in self.pending_requests:
             if duration is not None and candidate.duration.total_seconds(
             ) > duration:
                 continue
             if has_radius and haversine(
                 (candidate.latitude, candidate.longitude),
                 (latitude, longitude)) > radius:
                 continue
             if candidate.customer == worker:
                 continue
             found = candidate
             self.pending_requests = deque(
                 filter(lambda r: r.id != found.id, self.pending_requests))
             break
         else:
             return NONE
     with self.pair_mutex:
         self.paired_requests[found.id] = worker
     assert found is not None
     found.assigned_to = worker
     found.save()
     return Some(found)
Exemple #4
0
def test_check_meeting_user(meeting_api, user_type):
    meeting = next(fake_meeting())
    user = meeting.instructor if user_type == "instructor" else meeting.student
    meeting_api.meeting_persistence.get_meeting.return_value = Some(meeting)
    assert meeting_api._check_meeting_user(meeting.meeting_id, user, "").is_ok
    meeting_api.meeting_persistence.get_meeting.assert_called_once_with(
        meeting.meeting_id)
 def test_duplicate(self, instructor_persistence):
     instructor = fake_instructor()
     instructor_persistence.get_instructor = MagicMock(return_value=Some(instructor))
     assert (
         instructor_persistence.create_instructor(instructor, "aaaa").unwrap_err()
         == f"Instructor {instructor} already exists"
     )
Exemple #6
0
 def find_worker(self, request) -> Option['User']:
     if request.id in self.paired_requests:
         with self.pair_mutex:
             worker = self.paired_requests[request.id]
             del self.paired_requests[request.id]
         return Some(worker)
     return NONE
Exemple #7
0
 def callback(self, value):
   self.semaphore.acquire()
   self.cache = Some(value)
   while (len(self.subscribers) > 0):
     sub = self.subscribers.pop(0)
     t = threading.Thread(target=sub, args=[value])
     t.start()
   self.semaphore.release()
Exemple #8
0
def test_check_meeting_user_not_permitted(meeting_api, user):
    meeting = next(fake_meeting())
    meeting_api.meeting_persistence.get_meeting.return_value = Some(meeting)
    error = fake.pystr()
    assert (meeting_api._check_meeting_user(meeting.meeting_id, user,
                                            error).unwrap_err() == error)
    meeting_api.meeting_persistence.get_meeting.assert_called_once_with(
        meeting.meeting_id)
Exemple #9
0
def test_delete_note(meeting_api, success):
    note = next(fake_note())
    meeting = next(fake_meeting())
    error = Err(fake.pystr())
    meeting_api.meeting_persistence.get_note.return_value = Some(note)
    meeting_api.meeting_persistence.get_meeting.return_value = Some(meeting)
    meeting_api.meeting_persistence.delete_note.return_value = (Ok(
        note.note_id) if success else error)
    result = meeting_api.delete_note(note.note_id, meeting.instructor)
    if success:
        assert result.unwrap() == note.note_id
    else:
        assert result == error
    meeting_api.meeting_persistence.get_note.assert_called_once_with(
        note.note_id)
    meeting_api.meeting_persistence.get_meeting.assert_called_once_with(
        note.meeting_id)
Exemple #10
0
def test_delete_note_no_meeting(meeting_api):
    note = next(fake_note())
    author = fake_instructor()
    meeting_api.meeting_persistence.get_note.return_value = Some(note)
    meeting_api.meeting_persistence.get_meeting.return_value = NONE
    assert (f"Meeting with ID: '{note.meeting_id}'"
            in meeting_api.delete_note(note.note_id, author).unwrap_err())
    meeting_api.meeting_persistence.get_note.assert_called_once_with(
        note.note_id)
    meeting_api.meeting_persistence.get_meeting.assert_called_once_with(
        note.meeting_id)
Exemple #11
0
 def test_query_one(self, schema):
     self.before_each()
     fake_domain = self.fake_domain()
     identity = self.get_identity(fake_domain)
     self.mock_get_method().return_value = Some(fake_domain)
     result = schema.execute(self.query,
                             variables=self.variables(identity),
                             context=self.mock_context)
     assert not result.errors
     assert result.data == self.to_graphql(fake_domain)
     self.mock_get_method().assert_called_once_with(identity)
Exemple #12
0
 def test_query_one(self, schema):
     meeting = next(fake_meeting())
     meeting.comments.append(next(fake_comment(fake_student())))
     meeting.comments.append(next(fake_comment(fake_instructor())))
     context = MagicMock()
     context.api.meeting_api.get_meeting.return_value = Some(meeting)
     result = schema.execute(
         self.query_one,
         context=context,
         variables={"meetingId": str(meeting.meeting_id)},
     )
     assert not result.errors
     context.api.meeting_api.get_meeting.assert_called_once_with(
         meeting.meeting_id)
     assert result.data["meeting"]["meetingId"] == str(meeting.meeting_id)
Exemple #13
0
def load_json(string: AnyStr) -> Option[Json]:
    """
    Try to load a JSON string

    Args:
        string: The string to be loaded

    Returns:
        Some(json) if the load is successful
        NONE       otherwise
    """
    try:
        js = json.loads(string)
    except (TypeError, json.JSONDecodeError):
        return NONE
    return Some(js)
Exemple #14
0
def test_verify_token(instructor_api, instructor_found):
    token = fake.sha256()
    instructor = fake_instructor()
    instructor_api.jwt_authenticator.verify_token.return_value = Ok(
        {"id": instructor.user_name})
    if instructor_found:
        instructor_api.get_instructor = MagicMock(
            return_value=Some(instructor))
        assert instructor_api.verify_instructor_by_token(token) == Ok(
            instructor)
    else:
        instructor_api.get_instructor = MagicMock(return_value=NONE)
        assert instructor_api.verify_instructor_by_token(token) == Err(
            "UNAUTHORIZED - Could not get instructor")
    instructor_api.jwt_authenticator.verify_token.assert_called_once_with(
        token)
    instructor_api.get_instructor.assert_called_once_with(instructor.user_name)
Exemple #15
0
def test_create_section(schema, mock_context, create_section_query,
                        supply_instructor):
    context, course_api, instructor_api = mock_context
    section = fake_section()

    if supply_instructor:
        instructor_api.get_instructor = MagicMock(
            return_value=Some(section.taught_by))
    else:
        context.user = section.taught_by

    course_api.create_section = MagicMock(return_value=Ok(section))
    variables = section_input(section)
    if supply_instructor:
        variables["sectionInput"]["taughtBy"] = section.taught_by.user_name
    result = schema.execute(create_section_query,
                            variables=variables,
                            context=context)
    assert not result.errors
    assert result.data == {
        "createSection": {
            "course": {
                "courseCode": section.course.course_code
            },
            "year": section.year,
            "semester": section.semester.name,
            "taughtBy": {
                "userName": section.taught_by.user_name,
                "firstName": section.taught_by.first_name,
                "lastName": section.taught_by.last_name,
            },
            "numStudents": section.num_students,
            "sectionCode": section.section_code,
        }
    }
    course_api.create_section.assert_called_once_with(
        section.course,
        section.year,
        section.semester,
        section.section_code,
        section.taught_by,
        section.num_students,
    )
Exemple #16
0
def validate_int(x) -> Option[int]:
    """
    Try to convert some value to a int

    Args:
        x: The value

    Returns:
        Some(int) if the conversion is successful
        NONE      otherwise
    """
    if isinstance(x, (str, int)):
        try:
            parsed_int = int(x)
        except (TypeError, ValueError):
            return NONE
        else:
            return Some(parsed_int)
    return NONE
Exemple #17
0
def validate_bool(x) -> Option[bool]:
    if str(x).lower() == 'true':
        return Some(True)
    elif str(x).lower() == 'false':
        return Some(False)
    return NONE
Exemple #18
0
import pytest

from option import NONE, Option, Some, maybe
from tests.conftest import parametrize


@parametrize('is_some', [True, False])
def test_no_init(is_some):
    with pytest.raises(TypeError):
        if is_some:
            Option(1, True)
        else:
            Option(None, False)


@parametrize('obj', [Option.Some(1), Some(1)])
def test_some(obj):
    assert obj.is_some is True
    assert obj.is_none is False
    assert bool(obj)
    assert obj._val == 1


@parametrize('obj', [Option.NONE(), NONE])
def test_none(obj):
    assert obj.is_some is False
    assert obj.is_none is True
    assert bool(obj) is False
    assert obj._val is None

Exemple #19
0
def test_create_officehour(schema, success):
    context = MagicMock()
    officehour = fake_officehour()
    error = Err(fake.pystr())
    context.api.course_api.get_section.return_value = Some(officehour.section)
    context.api.course_api.create_officehour.return_value = (
        Ok(officehour) if success else error)
    query = """
    mutation createOfficeHour(
        $sectionInput: SectionInput!, $startingHour: Int!, $weekday: Weekday!
    ) {
        createOfficeHour(
            sectionInput: $sectionInput, startingHour: $startingHour, weekday: $weekday
        ) {
            officeHourId
            section {
                sectionCode
            }
            startingHour
            weekday
            meetings {
                meeting {
                    meetingId
                }
            }
        }
    }
    """
    variables = {
        "sectionInput": {
            "course": {
                "courseCode": officehour.section.course.course_code
            },
            "year": officehour.section.year,
            "semester": officehour.section.semester.name,
            "sectionCode": officehour.section.section_code,
            "taughtBy": officehour.section.taught_by.user_name,
            "numStudents": officehour.section.num_students,
        },
        "startingHour": officehour.starting_hour,
        "weekday": officehour.weekday.name,
    }
    result = schema.execute(query, context=context, variables=variables)
    if success:
        assert not result.errors
        create_officehour = result.data["createOfficeHour"]
        assert create_officehour["officeHourId"] == str(
            officehour.office_hour_id)
        assert (create_officehour["section"]["sectionCode"] ==
                officehour.section.section_code)
        assert create_officehour["weekday"] == officehour.weekday.name
        assert create_officehour["startingHour"] == officehour.starting_hour
        for slot, meeting in zip(create_officehour["meetings"],
                                 officehour.meetings):
            if not slot["meeting"]:
                assert not meeting
            else:
                assert slot["meeting"]["meetingId"] == str(meeting.meeting_id)
    else:
        assert error.unwrap_err() in str(result.errors)
    context.api.course_api.create_officehour.assert_called_once_with(
        officehour.section, officehour.starting_hour, officehour.weekday)
Exemple #20
0
        meeting.meeting_id)


@pytest.mark.parametrize("user", [fake_instructor(), fake_student()])
def test_delete_meeting_fail_user_check(meeting_api, user):
    meeting = next(fake_meeting())
    error = Err(fake.pystr())
    meeting_api._check_meeting_user = MagicMock(return_value=error)
    assert meeting_api.delete_meeting(meeting.meeting_id, user) == error
    meeting_api.meeting_persistence.delete_meeting.assert_not_called()
    meeting_api._check_meeting_user.assert_called_once_with(
        meeting.meeting_id, user,
        "Cannot delete meeting that you are not a part of")


@pytest.mark.parametrize("expected", [Some(next(fake_meeting())), NONE])
def test_get_meeting(meeting_api, expected):
    meeting_id = expected.unwrap().meeting_id if expected else uuid4()
    meeting_api.meeting_persistence.get_meeting.return_value = expected
    assert meeting_api.get_meeting(meeting_id) == expected
    meeting_api.meeting_persistence.get_meeting.assert_called_once_with(
        meeting_id)
    meeting_api.meeting_persistence.delete_meeting.assert_not_called()


def test_get_meetings_of_instructor(meeting_api):
    user_name = fake.pystr()
    expected = [meeting for meeting, _ in zip(fake_meeting(), range(10))]
    meeting_api.meeting_persistence.get_meetings_of_instructor.return_value = expected
    assert meeting_api.get_meetings_of_instructor(user_name) == expected
    meeting_api.meeting_persistence.get_meetings_of_instructor.assert_called_once_with(
Exemple #21
0
    course_api = CourseApi(mock_course_presistence)
    mock_course_presistence.query_courses = MagicMock(return_value=expected)
    assert course_api.query_courses(filters) == expected
    mock_course_presistence.query_courses.assert_called_once_with(filters)


@pytest.mark.parametrize("filters,expected",
                         [(None, list_fakes(fake_section, 5))])
def test_query_sections(mock_course_presistence, filters, expected):
    course_api = CourseApi(mock_course_presistence)
    mock_course_presistence.query_sections = MagicMock(return_value=expected)
    assert course_api.query_sections(filters) == expected
    mock_course_presistence.query_sections.assert_called_once_with(filters)


@pytest.mark.parametrize("expected", [NONE, Some(fake_course())])
def test_get_course(mock_course_presistence, expected):
    course_api = CourseApi(mock_course_presistence)
    mock_course_presistence.get_course = MagicMock(return_value=expected)
    course_code = expected.map_or(lambda c: c.course_code, None)
    assert course_api.get_course(course_code) == expected
    mock_course_presistence.get_course.assert_called_once_with(course_code)


@pytest.mark.parametrize("expected", [NONE, Some(fake_section())])
def test_get_section(mock_course_presistence, expected):
    course_api = CourseApi(mock_course_presistence)
    expected_identity = expected.map_or(lambda section: section.identity, None)
    mock_course_presistence.get_section = MagicMock(return_value=expected)
    assert course_api.get_section(expected_identity) == expected
    mock_course_presistence.get_section.assert_called_once_with(
Exemple #22
0
def validate_float(x) -> Option[float]:
    try:
        f = float(x)
    except (TypeError, ValueError):
        return NONE
    return Some(f)
Exemple #23
0
 def test_duplicate(self, course_persistence):
     section = fake_section()
     course_persistence.get_section = MagicMock(return_value=Some(section))
     assert (course_persistence.create_section(section).unwrap_err() ==
             f"Section {section} already exists")
Exemple #24
0
 def test_duplicate(self, student_persistence):
     student = fake_student()
     student_persistence.get_student = MagicMock(return_value=Some(student))
     assert (student_persistence.create_student(
         student,
         "aaaa").unwrap_err() == f"Student {student} already exists")
Exemple #25
0
 def test_duplicate(self, course_persistence):
     course = fake_course()
     course_persistence.get_course = MagicMock(return_value=Some(course))
     assert (course_persistence.create_course(course).unwrap_err() ==
             f"Course {course} already exists")