예제 #1
0
def manifests(client: FlaskClient, election_id: str,
              jurisdiction_ids: List[str]):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
        data={
            "manifest": (
                io.BytesIO(b"Batch Name,Number of Ballots\n"
                           b"1,200000\n"
                           b"2,200000\n"
                           b"3,200000\n"
                           b"4,200000\n"
                           b"5,200000"),
                "manifest.csv",
            )
        },
    )
    assert_ok(rv)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[1]}/ballot-manifest",
        data={
            "manifest": (
                io.BytesIO(b"Batch Name,Number of Ballots\n"
                           b"1,200000\n"
                           b"2,200000\n"
                           b"3,200000\n"
                           b"4,200000\n"
                           b"5,200000"),
                "manifest.csv",
            )
        },
    )
    assert_ok(rv)
    bgcompute_update_ballot_manifest_file()
예제 #2
0
def test_api_source_put(
    test_client: FlaskClient, example_ledger: FavaLedger
) -> None:
    path = Path(example_ledger.beancount_file_path)

    url = "/long-example/api/source"
    # test bad request
    response = test_client.put(url)
    assert_api_error(response, "Invalid JSON request.")

    payload = path.read_text("utf-8")
    sha256sum = hashlib.sha256(path.read_bytes()).hexdigest()

    # change source
    response = test_client.put(
        url,
        json={
            "source": "asdf" + payload,
            "sha256sum": sha256sum,
            "file_path": path,
        },
    )
    sha256sum = hashlib.sha256(path.read_bytes()).hexdigest()
    assert_api_success(response, sha256sum)

    # check if the file has been written
    assert path.read_text("utf-8") == "asdf" + payload

    # write original source file
    result = test_client.put(
        url,
        json={"source": payload, "sha256sum": sha256sum, "file_path": path},
    )
    assert result.status_code == 200
    assert path.read_text("utf-8") == payload
예제 #3
0
def test_search_pagination(client: FlaskClient):
    """
    Test pagination param on search request

    Arguments:
        client {FlaskClient} -- client to access flask web ressource
    """
    # generate may matching groups
    groups_1: List[Group] = create_groups(search_query="v",
                                          valid_groups=True,
                                          amount=50)

    # test page 0 with 25 entries
    response_1: JSONResponse = client.put(
        url_for("meetupsearchapi"),
        data=generate_search_dict(query="v", page=0, limit=25),
    )
    assert response_1.status_code == 200
    assert response_1.json["results"][0]["urlname"] == groups_1[0].urlname
    assert len(response_1.json["results"]) == 25
    assert response_1.json["hits"] == 50
    assert isinstance(response_1, JSONResponse)

    # test page 1 with 25 entries
    response_2: JSONResponse = client.put(
        url_for("meetupsearchapi"),
        data=generate_search_dict(query="v", page=1, limit=25),
    )
    assert response_2.status_code == 200
    assert response_2.json["results"][0]["urlname"] == groups_1[25].urlname
    assert len(response_2.json["results"]) == 25
    assert response_2.json["hits"] == 50
    assert isinstance(response_2, JSONResponse)
예제 #4
0
def test_api_add_document(
    app: Flask,
    test_client: FlaskClient,
    tmp_path: Path,
    monkeypatch: MonkeyPatch,
) -> None:
    with app.test_request_context("/long-example/"):
        app.preprocess_request()

        monkeypatch.setitem(
            g.ledger.options, "documents", [str(tmp_path)]  # type: ignore
        )
        request_data = {
            "folder": str(tmp_path),
            "account": "Expenses:Food:Restaurant",
            "file": (BytesIO(b"asdfasdf"), "2015-12-12 test"),
        }
        url = url_for("json_api.put_add_document")

        response = test_client.put(url)
        assert_api_error(response, "No file uploaded.")

        filename = (
            tmp_path / "Expenses" / "Food" / "Restaurant" / "2015-12-12 test"
        )

        response = test_client.put(url, data=request_data)
        assert_api_success(response, f"Uploaded to {filename}")
        assert Path(filename).is_file()

        request_data["file"] = (BytesIO(b"asdfasdf"), "2015-12-12 test")
        response = test_client.put(url, data=request_data)
        assert_api_error(response, f"{filename} already exists.")
예제 #5
0
def test_ballot_manifest_replace(
    client: FlaskClient, election_id: str, jurisdiction_ids: List[str]
):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
        data={
            "manifest": (
                io.BytesIO(
                    b"Batch Name,Number of Ballots,Storage Location,Tabulator\n"
                    b"1,23,Bin 2,Tabulator 1\n"
                    b"12,100,Bin 3,Tabulator 2\n"
                    b"6,0,,\n"
                ),
                "manifest.csv",
            )
        },
    )
    assert_ok(rv)

    file_id = Jurisdiction.query.get(jurisdiction_ids[0]).manifest_file_id

    bgcompute_update_ballot_manifest_file()

    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
        data={
            "manifest": (
                io.BytesIO(
                    b"Batch Name,Number of Ballots,Storage Location,Tabulator\n"
                    b"1,23,Bin 2,Tabulator 1\n"
                    b"12,6,Bin 6,Tabulator 2\n"
                ),
                "manifest.csv",
            )
        },
    )
    assert_ok(rv)

    # The old file should have been deleted
    jurisdiction = Jurisdiction.query.get(jurisdiction_ids[0])
    assert File.query.get(file_id) is None
    assert jurisdiction.manifest_file_id != file_id

    bgcompute_update_ballot_manifest_file()

    jurisdiction = Jurisdiction.query.get(jurisdiction_ids[0])
    assert jurisdiction.manifest_num_batches == 2
    assert jurisdiction.manifest_num_ballots == 29
    assert len(jurisdiction.batches) == 2
    assert jurisdiction.batches[0].name == "1"
    assert jurisdiction.batches[0].num_ballots == 23
    assert jurisdiction.batches[0].storage_location == "Bin 2"
    assert jurisdiction.batches[0].tabulator == "Tabulator 1"
    assert jurisdiction.batches[1].name == "12"
    assert jurisdiction.batches[1].num_ballots == 6
    assert jurisdiction.batches[1].storage_location == "Bin 6"
    assert jurisdiction.batches[1].tabulator == "Tabulator 2"
def test_activate_client(test_client: FlaskClient, admin_headers: dict,
                         user_password: str):
    hash_password = bcrypt.generate_password_hash(user_password)
    hash_password = hash_password.decode('utf-8')

    user = User(
        email='*****@*****.**',
        password=hash_password,
        role='client',
        active=False,
    )

    session.add(user)
    session.commit()

    data = {
        "email": user.email,
        "password": user_password,
    }

    response = test_client.post('/api/client/v1/login/', json=data)

    actual = response.status_code
    expected = 400

    assert actual == expected

    data = {
        "active": True,
    }

    test_client.put(f"/api/admin/v1/users/{user.id}/",
                    json=data,
                    headers=admin_headers)

    actual = user.active
    expected = True

    assert actual == expected

    data = {
        "email": user.email,
        "password": user_password,
    }

    response = test_client.post('/api/client/v1/login/', json=data)

    actual = response.status_code
    expected = 200

    assert actual == expected
예제 #7
0
def test_sub_pass(client: FlaskClient, calc_url: str) -> None:
    # given
    x, y = 2, 1

    # when (sub)
    client.put(calc_url, json={'operator': 'push', 'operand': x})
    client.put(calc_url, json={'operator': 'push', 'operand': y})
    client.put(calc_url, json={'operator': 'sub'})

    # then
    response = client.get(calc_url)
    assert 200 == response.status_code
    response_data = response.get_json()
    assert x - y == response_data['result']
예제 #8
0
def test_add_pass(client: FlaskClient, calc_url: str) -> None:
    # given
    x, y = 1, 2

    # when (add)
    client.put(calc_url, json={'operator': 'push', 'operand': x})
    client.put(calc_url, json={'operator': 'push', 'operand': y})
    client.put(calc_url, json={'operator': 'add'})

    # then
    # response = authorize(client.get, calc_url, auth_token=auth_token)
    response = client.get(calc_url)
    assert 200 == response.status_code
    response_data = response.get_json()
    assert x + y == response_data['result']
def test_update(test_client: FlaskClient, admin_headers: dict,
                user_password: str):
    hash_password = bcrypt.generate_password_hash(user_password)
    hash_password = hash_password.decode('utf-8')

    user = User(
        email='*****@*****.**',
        password=hash_password,
        role='admin',
        active=True,
    )

    session.add(user)
    session.commit()

    data = ({
        "email": '*****@*****.**',
        "password": f'{user_password}1',
        "role": 'client',
    })

    response = test_client.put(f"/api/admin/v1/users/{user.id}/",
                               json=data,
                               headers=admin_headers)
    actual = response.json['result']
    expected = UserClientSchema().dump(user)

    assert actual == expected
예제 #10
0
    def get_dynamic_input_schema(
        client: FlaskClient,
        endpoint: str,
        headers: Optional[Dict[str, str]],
        method: str = "post",
    ) -> List[Dict[str, Any]]:
        """
        Retrieve a dynamic data schema associated with a endpoint
        """

        method = method.lower()

        if method == "post":
            r = client.post(f"{API_URI}/{endpoint}",
                            json={"get_schema": 1},
                            headers=headers)
        else:
            r = client.put(f"{API_URI}/{endpoint}",
                           json={"get_schema": 1},
                           headers=headers)

        assert r.status_code == 200

        schema = orjson.loads(r.data.decode("utf-8"))
        assert isinstance(schema, list)
        for f in schema:
            assert isinstance(f, dict)
        return schema
예제 #11
0
def test_cvrs_wrong_audit_type(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],
        manifests,  # pylint: disable=unused-argument
):
    for audit_type in [AuditType.BALLOT_POLLING, AuditType.BATCH_COMPARISON]:
        # Hackily change the audit type
        election = Election.query.get(election_id)
        election.audit_type = audit_type
        db_session.add(election)
        db_session.commit()

        set_logged_in_user(client, UserType.JURISDICTION_ADMIN,
                           DEFAULT_JA_EMAIL)
        rv = client.put(
            f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/cvrs",
            data={"cvrs": (
                io.BytesIO(TEST_CVRS.encode()),
                "cvrs.csv",
            )},
        )
        assert rv.status_code == 409
        assert json.loads(rv.data) == {
            "errors": [{
                "errorType":
                "Conflict",
                "message":
                "Can only upload CVR file for ballot comparison audits.",
            }]
        }
예제 #12
0
def test_cvrs_upload_bad_csv(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],
        manifests,  # pylint: disable=unused-argument
):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/cvrs",
        data={"cvrs": (io.BytesIO(b"not a CSV file"), "random.txt")},
    )
    assert_ok(rv)

    bgcompute_update_cvr_file()

    rv = client.get(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/cvrs")
    compare_json(
        json.loads(rv.data),
        {
            "file": {
                "name": "random.txt",
                "uploadedAt": assert_is_date,
            },
            "processing": {
                "status": ProcessingStatus.ERRORED,
                "startedAt": assert_is_date,
                "completedAt": assert_is_date,
                "error": "Could not parse CVR file",
            },
        },
    )
예제 #13
0
def test_update_time_entry_calls_partial_update_with_incoming_payload(
    client: FlaskClient,
    mocker: MockFixture,
    valid_header: dict,
    valid_id: str,
    owner_id: str,
    time_entries_dao,
):
    valid_time_entry_input_to_update = valid_time_entry_input.copy()
    valid_time_entry_input_to_update["owner_id"] = owner_id

    time_entries_dao.repository.partial_update = Mock(return_value={})

    time_entries_dao.repository.find = Mock(return_value={})
    time_entries_dao.check_whether_current_user_owns_item = Mock()

    response = client.put(
        f'/time-entries/{valid_id}',
        headers=valid_header,
        json=valid_time_entry_input_to_update,
        follow_redirects=True,
    )

    assert HTTPStatus.OK == response.status_code
    time_entries_dao.repository.partial_update.assert_called_once_with(
        valid_id, valid_time_entry_input_to_update, ANY)

    time_entries_dao.repository.find.assert_called_once()
    time_entries_dao.check_whether_current_user_owns_item.assert_called_once()
예제 #14
0
def test_update_project_should_reject_bad_request(
    client: FlaskClient, mocker: MockFixture, valid_header: dict
):
    from time_tracker_api.projects.projects_namespace import project_dao

    invalid_project_data = valid_project_data.copy()
    invalid_project_data.update(
        {
            "project_type_id": fake.pyint(min_value=1, max_value=100),
        }
    )
    repository_update_mock = mocker.patch.object(
        project_dao.repository, 'partial_update', return_value=fake_project
    )

    valid_id = fake.random_int(1, 9999)
    response = client.put(
        "/projects/%s" % valid_id,
        headers=valid_header,
        json=invalid_project_data,
        follow_redirects=True,
    )

    assert HTTPStatus.BAD_REQUEST == response.status_code
    repository_update_mock.assert_not_called()
예제 #15
0
def test_batch_tallies_before_manifests(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],
        contest_ids: List[str],  # pylint: disable=unused-argument
):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/batch-tallies",
        data={
            "batchTallies": (
                io.BytesIO(b"Batch Name,candidate 1,candidate 2,candidate 3\n"
                           b"Batch 1,300,10,100\n"
                           b"Batch 2,2,20,200\n"
                           b"Batch 3,3,30,300\n"),
                "batchTallies.csv",
            )
        },
    )
    assert rv.status_code == 409
    assert json.loads(rv.data) == {
        "errors": [{
            "errorType":
            "Conflict",
            "message":
            "Must upload ballot manifest before uploading batch tallies.",
        }]
    }
예제 #16
0
def test_update_time_entry_raise_not_found(
    client: FlaskClient,
    mocker: MockFixture,
    valid_header: dict,
    valid_id: str,
    owner_id: str,
    time_entries_dao,
):
    from werkzeug.exceptions import NotFound

    valid_time_entry_input_to_update = valid_time_entry_input.copy()
    valid_time_entry_input_to_update["owner_id"] = owner_id

    time_entries_dao.repository.partial_update = Mock(side_effect=NotFound)

    time_entries_dao.repository.find = Mock(return_value={})
    time_entries_dao.check_whether_current_user_owns_item = Mock()

    response = client.put(
        f'/time-entries/{valid_id}',
        headers=valid_header,
        json=valid_time_entry_input_to_update,
        follow_redirects=True,
    )

    assert HTTPStatus.NOT_FOUND == response.status_code
    time_entries_dao.repository.partial_update.assert_called_once_with(
        valid_id, valid_time_entry_input_to_update, ANY)

    time_entries_dao.repository.find.assert_called_once()
    time_entries_dao.check_whether_current_user_owns_item.assert_called_once()
예제 #17
0
def test_batch_tallies_bad_jurisdiction(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],
        contest_ids: List[str],  # pylint: disable=unused-argument
        manifests,  # pylint: disable=unused-argument
):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, "*****@*****.**")
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[2]}/batch-tallies",
        data={
            "batchTallies": (
                io.BytesIO(b"Batch Name,candidate 1,candidate 2,candidate 3\n"
                           b"Batch 1,300,10,100\n"
                           b"Batch 2,2,20,200\n"
                           b"Batch 3,3,30,300\n"),
                "batchTallies.csv",
            )
        },
    )
    assert rv.status_code == 409
    assert json.loads(rv.data) == {
        "errors": [{
            "errorType":
            "Conflict",
            "message":
            "Jurisdiction does not have any contests assigned",
        }]
    }
예제 #18
0
def test_standardized_contests_wrong_audit_type(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],  # pylint: disable=unused-argument
):
    for audit_type in [AuditType.BALLOT_POLLING, AuditType.BATCH_COMPARISON]:
        # Hackily change the audit type
        election = Election.query.get(election_id)
        election.audit_type = audit_type
        db_session.add(election)
        db_session.commit()

        rv = client.put(
            f"/api/election/{election_id}/standardized-contests/file",
            data={
                "standardized-contests": (
                    io.BytesIO(b"Contest Name,Jurisdictions\n"
                               b"Contest 1,all\n"),
                    "standardized-contests.csv",
                )
            },
        )
        assert rv.status_code == 409
        assert json.loads(rv.data) == {
            "errors": [{
                "errorType":
                "Conflict",
                "message":
                "Can only upload standardized contests file for ballot comparison audits.",
            }]
        }
def test_ballot_manifest_clear(client: FlaskClient, election_id: str,
                               jurisdiction_ids: List[str]):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
        data={
            "manifest": (
                io.BytesIO(b"Batch Name,Number of Ballots\n"
                           b"1,23\n"),
                "manifest.csv",
            )
        },
    )
    assert_ok(rv)

    file_id = Jurisdiction.query.get(jurisdiction_ids[0]).manifest_file_id

    bgcompute_update_ballot_manifest_file()

    rv = client.delete(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
    )
    assert_ok(rv)

    rv = client.get(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest"
    )
    assert json.loads(rv.data) == {"file": None, "processing": None}

    jurisdiction = Jurisdiction.query.get(jurisdiction_ids[0])
    assert jurisdiction.manifest_num_batches is None
    assert jurisdiction.manifest_num_ballots is None
    assert jurisdiction.batches == []
    assert jurisdiction.manifest_file_id is None
    assert File.query.get(file_id) is None
예제 #20
0
def test_update_time_entry_calls_update_last_entry(
    client: FlaskClient,
    mocker: MockFixture,
    valid_header: dict,
    valid_id: str,
    time_entries_dao,
):
    time_entries_dao.repository.partial_update = Mock(return_value={})
    time_entries_dao.repository.find = Mock(return_value={})
    time_entries_dao.check_whether_current_user_owns_item = Mock()
    time_entries_dao.repository.update_last_entry = Mock(return_value={})

    update_time_entry = valid_time_entry_input.copy()
    update_time_entry['update_last_entry_if_overlap'] = True

    response = client.put(
        f'/time-entries/{valid_id}',
        headers=valid_header,
        json=update_time_entry,
        follow_redirects=True,
    )

    assert HTTPStatus.OK == response.status_code
    time_entries_dao.repository.partial_update.assert_called_once()
    time_entries_dao.repository.find.assert_called_once()
    time_entries_dao.check_whether_current_user_owns_item.assert_called_once()
    time_entries_dao.repository.update_last_entry.assert_called_once()
예제 #21
0
def test_ballot_manifest_upload_invalid_num_ballots(
    client: FlaskClient, election_id: str, jurisdiction_ids: List[str]
):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
        data={
            "manifest": (
                io.BytesIO(
                    b"Batch Name,Number of Ballots,Storage Location,Tabulator\n"
                    b"1,not a number,Bin 2,Tabulator 1\n"
                ),
                "manifest.csv",
            )
        },
    )
    assert_ok(rv)

    bgcompute_update_ballot_manifest_file()

    rv = client.get(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest"
    )
    compare_json(
        json.loads(rv.data),
        {
            "file": {"name": "manifest.csv", "uploadedAt": assert_is_date,},
            "processing": {
                "status": ProcessingStatus.ERRORED,
                "startedAt": assert_is_date,
                "completedAt": assert_is_date,
                "error": "Expected a number in column Number of Ballots, row 2. Got: not a number.",
            },
        },
    )
def test_ballot_manifest_upload_bad_csv(client: FlaskClient, election_id: str,
                                        jurisdiction_ids: List[str]):
    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest",
        data={"manifest": (io.BytesIO(b"not a CSV file"), "random.txt")},
    )
    assert_ok(rv)

    bgcompute_update_ballot_manifest_file()

    rv = client.get(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/ballot-manifest"
    )
    compare_json(
        json.loads(rv.data),
        {
            "file": {
                "name": "random.txt",
                "uploadedAt": assert_is_date,
            },
            "processing": {
                "status":
                ProcessingStatus.ERRORED,
                "startedAt":
                assert_is_date,
                "completedAt":
                assert_is_date,
                "error":
                "Please submit a valid CSV file with columns separated by commas.",
            },
        },
    )
예제 #23
0
def test_batch_tallies_ballot_polling(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],
        contest_ids: List[str],  # pylint: disable=unused-argument
        manifests,  # pylint: disable=unused-argument
):
    # Hackily change the audit type
    election = Election.query.get(election_id)
    election.audit_type = AuditType.BALLOT_POLLING
    db_session.add(election)
    db_session.commit()

    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/batch-tallies",
        data={
            "batchTallies": (
                io.BytesIO(b"Batch Name,candidate 1,candidate 2,candidate 3\n"
                           b"Batch 1,300,10,100\n"
                           b"Batch 2,2,20,200\n"
                           b"Batch 3,3,30,300\n"),
                "batchTallies.csv",
            )
        },
    )
    assert rv.status_code == 409
    assert json.loads(rv.data) == {
        "errors": [{
            "errorType":
            "Conflict",
            "message":
            "Can only upload batch tallies file for batch comparison audits.",
        }]
    }
예제 #24
0
 def edit_project(self, client: FlaskClient, project_id: int, data: dict,
                  token: str) -> Response:
     query_string = {"token": token}
     response = client.put(f"/api/projects/{project_id}",
                           data=json.dumps(data),
                           query_string=query_string)
     return response
def test_update(test_client: FlaskClient, admin_headers: dict):
    first_ingredient, second_ingredient, first_step, second_step = prepare_create_receipt(
    )

    receipt = Receipt(
        name='Name',
        description='Cool',
        calories=200,
        ingredients=[first_ingredient, second_ingredient],
        steps=[first_step, second_step],
    )

    session.add(receipt)
    session.commit()

    data = ({
        "name": 'Name1',
        "description": 'Cool1',
        "calories": 201,
        "ingredients": [second_ingredient.id],
        "steps": [first_step],
    })

    response = test_client.put(f"/api/admin/v1/receipts/{receipt.id}/",
                               json=data,
                               headers=admin_headers)
    actual = response.json['result']
    expected = ReceiptClientSchema().dump(receipt)

    assert actual == expected
예제 #26
0
def cvrs(
        client: FlaskClient,
        election_id: str,
        jurisdiction_ids: List[str],
        manifests,  # pylint: disable=unused-argument
):
    j1_cvr_lines = [
        f"TABULATOR{tabulator},BATCH{batch},{ballot},{tabulator}-{batch}-{ballot},x,x,1,0,0,1,0"
        for tabulator in range(1, 3) for batch in range(1, 5)
        for ballot in range(1, 21)
    ]
    j1_cvr = """Test Audit CVR Upload,5.2.16.1,,,,,,,,,,
,,,,,,,Contest 1 (Vote For=1),Contest 1 (Vote For=1),Contest 2 (Vote For=2),Contest 2 (Vote For=2),Contest 2 (Vote For=2)
,,,,,,,Choice 1-1,Choice 1-2,Choice 2-1,Choice 2-2,Choice 2-3
CvrNumber,TabulatorNum,BatchId,RecordId,ImprintedId,PrecinctPortion,BallotType,REP,DEM,LBR,IND,,
    """ + "\n".join([f"{i},{line}" for i, line in enumerate(j1_cvr_lines)])

    set_logged_in_user(client, UserType.JURISDICTION_ADMIN, DEFAULT_JA_EMAIL)
    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[0]}/cvrs",
        data={"cvrs": (
            io.BytesIO(j1_cvr.encode()),
            "cvrs.csv",
        )},
    )
    assert_ok(rv)

    j2_cvr_lines = [
        f"TABULATOR{tabulator},BATCH{batch},{ballot},{tabulator}-{batch}-{ballot},x,x,0,0,0,0,0"
        for tabulator in range(1, 3) for batch in range(1, 3)
        for ballot in range(1, 51)
    ]
    j2_cvr = """Test Audit CVR Upload,5.2.16.1,,,,,,,,,,
,,,,,,,Contest 1 (Vote For=1),Contest 1 (Vote For=1),Contest 2 (Vote For=2),Contest 2 (Vote For=2),Contest 2 (Vote For=2)
,,,,,,,Choice 1-1,Choice 1-2,Choice 2-1,Choice 2-2,Choice 2-3
CvrNumber,TabulatorNum,BatchId,RecordId,ImprintedId,PrecinctPortion,BallotType,REP,DEM,LBR,IND,,
    """ + "\n".join([f"{i},{line}" for i, line in enumerate(j2_cvr_lines)])

    rv = client.put(
        f"/api/election/{election_id}/jurisdiction/{jurisdiction_ids[1]}/cvrs",
        data={"cvrs": (
            io.BytesIO(j2_cvr.encode()),
            "cvrs.csv",
        )},
    )
    assert_ok(rv)
    bgcompute_update_cvr_file()
예제 #27
0
def test_standardized_contests_replace(client: FlaskClient, election_id: str,
                                       jurisdiction_ids: List[str]):
    rv = client.put(
        f"/api/election/{election_id}/standardized-contests/file",
        data={
            "standardized-contests": (
                io.BytesIO(b"Contest Name,Jurisdictions\n"
                           b"Contest 1,all\n"
                           b'Contest 2,"J1, J3"\n'
                           b"Contest 3,J2 \n"),
                "standardized-contests.csv",
            )
        },
    )
    assert_ok(rv)

    file_id = Election.query.get(election_id).standardized_contests_file_id

    bgcompute_update_standardized_contests_file()

    rv = client.put(
        f"/api/election/{election_id}/standardized-contests/file",
        data={
            "standardized-contests": (
                io.BytesIO(b"Contest Name,Jurisdictions\n"
                           b"Contest 4,all\n"),
                "standardized-contests.csv",
            )
        },
    )
    assert_ok(rv)

    # The old file should have been deleted
    assert File.query.get(file_id) is None
    assert Election.query.get(
        election_id).standardized_contests_file_id != file_id
    assert Election.query.get(election_id).standardized_contests is None

    bgcompute_update_standardized_contests_file()

    rv = client.get(f"/api/election/{election_id}/standardized-contests")
    assert json.loads(rv.data) == [
        {
            "name": "Contest 4",
            "jurisdictionIds": jurisdiction_ids
        },
    ]
예제 #28
0
def test_update_dataobj(test_app, client: FlaskClient, note_fixture):
    lorem = "Updated note content"
    resp = client.put("/api/dataobjs/1", json={"content": lorem})

    assert resp.status_code == 200

    resp = client.get("/api/dataobjs/1")
    assert resp.json["content"] == lorem
예제 #29
0
def test_bad_operator_fail(client: FlaskClient, calc_url: str) -> None:
    # given

    # when (bad operator)
    response = client.put(calc_url, json={'operator': 'bad_oper'})

    # then
    assert 404 == response.status_code
예제 #30
0
def test_group_venues(client: FlaskClient):
    """
    check if group venues was set right

    Arguments:
        client {FlaskClient} -- client to access flask web ressource
    """
    # add one group without event
    groups_1: List[Group] = create_groups(search_query="v",
                                          valid_groups=True,
                                          amount=1)

    # test with one group without events
    response_1: JSONResponse = client.put(url_for("meetupsearchapi"),
                                          data=generate_search_dict(query="v"))
    assert response_1.status_code == 200
    assert len(response_1.json["results"][0]["venues"]) == 0
    assert isinstance(response_1, JSONResponse)

    # add mutile events without venue
    create_events_to_group(search_query="b",
                           valid_events=True,
                           group=groups_1[0],
                           amount=10,
                           venue=False)

    # test with one group with events without venues
    response_2: JSONResponse = client.put(url_for("meetupsearchapi"),
                                          data=generate_search_dict(query="v"))
    assert response_2.status_code == 200
    assert len(response_2.json["results"][0]["venues"]) == 0
    assert isinstance(response_2, JSONResponse)

    # add mutile events with venues
    create_events_to_group(search_query="b",
                           valid_events=True,
                           group=groups_1[0],
                           amount=10,
                           venue=True)

    # test with one group with events with venues
    response_3: JSONResponse = client.put(url_for("meetupsearchapi"),
                                          data=generate_search_dict(query="v"))
    assert response_3.status_code == 200
    assert len(response_3.json["results"][0]["venues"]) == 10
    assert isinstance(response_3, JSONResponse)