Example #1
0
    def test_clean_data(self):
        "Remove empty values and perform other cleaning (like stripping strings)"
        mapper = {
            "TO_KEEP": "0",
            "TO_KEEP_1": "1",
            "TO_KEEP_2": "2",
            "TO_KEEP_3": "3",
            "TO_KEEP_4": "4",
            "TO_REMOVE": "5",
            "TO_REMOVE_2": "6",
        }

        form_format = {
            "TO_KEEP_1":
            1,
            "TO_REMOVE":
            "",
            "TO_KEEP_2": [1, 2, ""],
            "TO_KEEP_3": {
                "TO_KEEP": 31,
                "TO_REMOVE": ""
            },
            "TO_KEEP_4": [
                {
                    "TO_KEEP": 441,
                    "TO_REMOVE": ""
                },
                {
                    "TO_REMOVE": "",
                    "TO_REMOVE_2": ""
                },
            ],
        }
        c = FormatConverter(mapper=mapper).add_form_format(form_format)
        c.clean_data()

        actual_output = c.get_form_format()
        expected_output = {
            "TO_KEEP_1": 1,
            "TO_KEEP_2": [1, 2],
            "TO_KEEP_3": {
                "TO_KEEP": 31
            },
            "TO_KEEP_4": [{
                "TO_KEEP": 441
            }, {}],
        }

        self.assertEqual(actual_output, expected_output)
def upload_study_related_entity(data, url, method, property_url, headers):
    """Send data to the API (study related entity) in form format"""
    entry_format = data.pop("entry_format", "form")

    # Format data (cleaning + conversion from "form format" to "api format")
    if entry_format == "form":
        prop_name_to_id = map_key_value(property_url, key="name", value="id")
        converter = FormatConverter(mapper=prop_name_to_id)
        converter.add_form_format(data["entries"])

    elif entry_format == "api":
        prop_id_to_name = map_key_value(property_url, key="id", value="name")
        converter = FormatConverter(mapper=prop_id_to_name)
        converter.add_api_format(data["entries"])

    converter.clean_data()
    data["entries"] = converter.get_api_format()
    data["entry_format"] = "api"

    # Send data to API
    if method == "post":
        res = requests.post(url=url, json=data, headers=headers)
        if res.status_code != 201:
            message = f"Failed to POST study related entity. {res.json()}"
            success = False
        else:
            message = "Succeded to POST study related entity"
            success = True

    elif method == "put":
        res = requests.put(url=url, json=data, headers=headers)
        if res.status_code != 200:
            message = f"Failed to PUT study related entity. {res.json()}"
            success = False
        else:
            message = "Succeded to PUT study related entity"
            success = True

    return (res.json(), message, success)