Пример #1
0
    def test_DELETE_basket_variables(self):
        """Can we delete a BasketVariable"""
        new_variable = VariableFactory(name="new-test-variable")
        new_variable.dataset = self.variable.dataset
        new_variable.save()
        post_data = {
            "basket": str(self.basket.id),
            "variables": [str(new_variable.id)]
        }

        self.client.force_authenticate(user=self.user)
        post_response = self.client.post(self.API_PATH,
                                         post_data,
                                         format="json")
        self.assertEqual(201, post_response.status_code)

        result = self.client.get(f"{self.API_PATH}")
        results = json.loads(result.content)["results"]

        self.assertIn(True, [
            result["variable_id"] == str(self.variable.id)
            for result in results
        ])

        basket_variable_id = BasketVariable.objects.get(
            basket_id=self.basket.id, variable_id=new_variable.id).id

        self.client.delete(self.API_PATH + f"{basket_variable_id}/")
        result = self.client.get(f"{self.API_PATH}")
        results = json.loads(result.content)["results"]

        self.assertNotIn(
            True,
            [result["variable_id"] == str(new_variable) for result in results])
Пример #2
0
def _related_variables_by_concept(variable, concept):
    """Two variables that are related by concept"""
    variable.concept = concept
    variable.save()
    other_variable = VariableFactory(name="other-variable")
    other_variable.concept = concept
    other_variable.save()
    return variable, other_variable
Пример #3
0
 def setUp(self) -> None:
     VariableFactory(name="some-variable")
     VariableFactory(name="some-other-variable")
     VariableFactory(name="some-third-variable")
     VariableFactory(name="alter_gr")
     VariableFactory(name="sex")
     VariableFactory(name="bula_h")
     VariableFactory(name="bildungsniveau")
     VariableFactory(name="sampreg")
     VariableFactory(name="migback")
     return super().setUp()
Пример #4
0
    def test_POST_basket_variables_no_permission(self):
        """Are permissions respected."""
        some_user = UserFactory(username="******")
        new_variable = VariableFactory(name="new-test-variable")
        new_variable.dataset = self.variable.dataset
        new_variable.save()
        post_data = {
            "basket": str(self.basket.id),
            "variables": [str(new_variable.id)]
        }

        self.client.force_authenticate(user=some_user)
        post_response = self.client.post(self.API_PATH,
                                         post_data,
                                         format="json")
        self.assertEqual(403, post_response.status_code)
Пример #5
0
    def test_backup(self, basket, variable):
        """Can we do a backup of existing Baskets."""
        basket.save()
        basket_id = basket.id
        basket_variable = BasketVariable(basket=basket, variable=variable)
        other_variable = VariableFactory(name="test-variable")
        other_basket_variable = BasketVariable(basket=basket,
                                               variable=other_variable)
        other_basket_variable.basket = basket
        other_basket_variable.variable = other_variable
        basket_variable.save()
        other_basket_variable.save()

        backup_file = Basket.backup()

        variable.delete()
        basket.delete()

        call_command("loaddata", backup_file)

        basket = Basket.objects.get(id=basket_id)
        basket_variables = list(basket.variables.all())

        TEST_CASE.assertIn(other_basket_variable.variable, basket_variables)
        TEST_CASE.assertNotIn(basket_variable.variable, basket_variables)
        remove(backup_file)
Пример #6
0
 def _init_self_variables(self):
     if self.variables:
         return None
     self.variables = []
     for number in range(1, 100):
         self.variables.append(VariableFactory(name=f"{number}"))
     return None
Пример #7
0
def _variable(request: FixtureRequest, db: pytest.fixture):
    """A variable in the database"""
    _factory = VariableFactory(
        name="some-variable",
        label="Some Variable",
        label_de="Eine Variable",
        description="This is some variable",
        statistics=dict(valid="1", invalid="0"),
        categories={
            "frequencies": [1, 0],
            "labels": [
                "[-6] Version of questionnaire with modified filtering",
                "[1] Yes",
            ],
            "labels_de": [
                "[-6] Fragebogenversion mit geaenderter Filterfuehrung",
                "[1] Ja",
            ],
            "values": ["-6", "1"],
            "missings": [True, False],
        },
    )
    if request.instance:
        request.instance.variable = _factory
    return _factory
Пример #8
0
 def test_import_transformations(self, study_import_manager, variable):
     TEST_CASE.assertEqual(0, Transformation.objects.count())
     other_variable = VariableFactory(name="some-other-variable")
     study_import_manager.import_single_entity("transformations")
     TEST_CASE.assertEqual(1, Transformation.objects.count())
     relation = Transformation.objects.first()
     TEST_CASE.assertEqual(variable, relation.origin)
     TEST_CASE.assertEqual(other_variable, relation.target)
Пример #9
0
 def test_scroll_limit(self):
     """There should be no scroll limit"""
     variable_amount = 101
     variables = []
     for number in range(1, variable_amount + 1):
         variables.append(VariableFactory(name=f"{number}"))
     response = self.client.get(self.API_PATH + "?paginate=False")
     self.assertEqual(200, response.status_code)
     content = json.loads(response.content)
     self.assertEqual(variable_amount, len(content))
Пример #10
0
    def test_DELETE_basket_variables_no_permission(self):
        """Can we fill a basket with variables?"""
        user = UserFactory(username="******")

        new_variable = VariableFactory(name="new-test-variable")
        new_variable.dataset = self.variable.dataset
        new_variable.save()
        post_data = {
            "basket": str(self.basket.id),
            "variables": [str(new_variable.id)]
        }

        self.client.force_authenticate(user=user)
        self.client.post(self.API_PATH, post_data, format="json")

        basket_variable = BasketVariable.objects.get(
            basket_id=self.basket.id, variable_id=self.variable.id)
        basket_variable_id = basket_variable.id

        response = self.client.delete(self.API_PATH + f"{basket_variable_id}/")
        self.assertEqual(403, response.status_code)
Пример #11
0
 def test_clean_method_fails(self, basket):
     """ BasketVariable clean method should raise an ValidationError when basket and variable study do not match """
     other_study = StudyFactory(name="some-other-study")
     other_dataset = DatasetFactory(name="some-other-dataset",
                                    study=other_study)
     other_variable = VariableFactory(name="some-other-variable",
                                      dataset=other_dataset)
     basket_variable = BasketVariable(basket_id=basket.id,
                                      variable_id=other_variable.id)
     with pytest.raises(ValidationError):
         basket_variable.clean()
     assert 0 == BasketVariable.objects.count()
Пример #12
0
    def test_POST_basket_variables(self):
        """Can we fill a basket with variables?"""
        new_variable = VariableFactory(name="new-test-variable")
        new_variable.dataset = self.variable.dataset
        new_variable.save()
        post_data = {
            "basket": str(self.basket.id),
            "variables": [str(new_variable.id)]
        }

        self.client.force_authenticate(user=self.user)
        post_response = self.client.post(self.API_PATH,
                                         post_data,
                                         format="json")
        self.assertEqual(201, post_response.status_code)

        result = self.client.get(f"{self.API_PATH}")
        results = json.loads(result.content)["results"]

        self.assertIn(True, [
            result["variable_id"] == str(new_variable.id) for result in results
        ])
Пример #13
0
    def test_POST_basket_variables_by_concept_name(self):
        """Define how basket variable creation by concept should work."""
        topic = TopicFactory(name="parent-topic")
        child_topic = TopicFactory(name="parent-topic", parent=topic)
        concept = ConceptFactory(name="some-concept")
        concept.topics.set([child_topic])
        concept.save()
        variables = [VariableFactory(name="1"), VariableFactory(name="2")]
        variables[1].concept = concept
        variables[1].save()

        post_data = {"basket": str(self.basket.id), "concept": concept.name}
        self.client.force_authenticate(user=self.user)
        post_response = self.client.post(self.API_PATH,
                                         post_data,
                                         format="json")
        self.assertEqual(201, post_response.status_code)
        get_response = self.client.get(self.API_PATH)
        content = json.loads(get_response.content)
        result_ids = [result["variable_id"] for result in content["results"]]
        self.assertIn(str(variables[1].id), result_ids)
        self.assertNotIn(str(variables[0].id), result_ids)
Пример #14
0
 def test_get_variable_GET_data(self):
     """Is the get response as expected?"""
     variable_amount = 10
     variables = []
     for number in range(1, variable_amount + 1):
         variables.append(VariableFactory(name=f"{number}"))
     response = self.client.get(self.API_PATH)
     self.assertEqual(200, response.status_code)
     content = json.loads(response.content)
     self.assertEqual(variable_amount, len(content))
     result_ids = [result["id"] for result in content]
     for variable in variables:
         self.assertIn(str(variable.id), result_ids)
Пример #15
0
    def test_basket_variable_limit_topic_and_concept_POST(self):
        """Define how the basket limit should work."""
        too_many_variables = []
        topic = TopicFactory(name="test-topic")
        concept = ConceptFactory(name="test-concept")
        concept.topics.set([topic])
        concept.save()
        for number in range(1, 12):
            variable = VariableFactory(name=str(number))
            variable.concept = concept
            variable.save()
            too_many_variables.append(variable)

        with patch(
                "ddionrails.api.views.user_tools.BasketVariableSet.basket_limit",
                new_callable=PropertyMock,
        ) as basket_limit:
            basket_limit.return_value = 10
            post_data = {"basket": str(self.basket.id), "topic": topic.name}
            self.client.force_authenticate(user=self.user)
            post_response = self.client.post(self.API_PATH,
                                             post_data,
                                             format="json")
            self.assertEqual(406, post_response.status_code)
            self.assertIn(b"basket size limit", post_response.content)

            BasketVariable.objects.all().delete()

            post_data = {
                "basket": str(self.basket.id),
                "concept": concept.name
            }
            self.client.force_authenticate(user=self.user)
            post_response = self.client.post(self.API_PATH,
                                             post_data,
                                             format="json")
            self.assertEqual(406, post_response.status_code)
            self.assertIn(b"basket size limit", post_response.content)
Пример #16
0
    def test_get_basket_variable_GET_with_url_param(self):
        """Can we get a basket variable with url params"""
        self.client.force_authenticate(user=self.user)
        new_basket_variable = BasketVariable()
        new_basket_variable.basket = self.basket
        new_basket_variable.variable = VariableFactory(name="new_variable")
        new_basket_variable.save()

        response = self.client.get(
            self.API_PATH +
            f"?variable={new_basket_variable.variable.id}&basket={self.basket.id}"
        )
        results = json.loads(response.content)["results"]
        basket = results[0]
        self.assertEqual(self.basket.id, basket["basket_id"])
        self.assertEqual(str(new_basket_variable.variable.id),
                         basket["variable_id"])
Пример #17
0
    def test_clean_method_fails(self):
        """Ensure the correct error raising of the BasketVariable clean method.

        BasketVariable clean method should raise a ValidationError
        when basket and variable study do not match.
        """
        other_study = StudyFactory(name="some-other-study")
        other_dataset = DatasetFactory(name="some-other-dataset",
                                       study=other_study)
        other_variable = VariableFactory(name="some-other-variable",
                                         dataset=other_dataset)
        basket_variable = BasketVariable(basket_id=self.basket.id,
                                         variable_id=other_variable.id)
        with pytest.raises(ValidationError):
            basket_variable.clean()
        expected = 0
        self.assertEqual(expected, BasketVariable.objects.count())
Пример #18
0
    def test_query_parameter_concept(self):
        concept_name = self.concept.name
        variable_list = []

        for number in range(1, 11):
            _variable = VariableFactory(name=str(number))
            _variable.concept = self.concept
            _variable.save()
            variable_list.append(_variable)

        for number in range(11, 21):
            _variable = VariableFactory(name=str(number))
            variable_list.append(_variable)

        response = self.client.get(self.API_PATH + f"?concept={concept_name}")
        content = json.loads(response.content)
        self.assertEqual(10, len(content))
Пример #19
0
 def test_returned_fields(self):
     """Define fields that should be provided."""
     expected_fields = [
         "id",
         "name",
         "label",
         "label_de",
         "dataset_name",
         "study_name",
         "study_label",
         "dataset",
         "study",
         "position",
     ]
     VariableFactory(name="test_variable")
     response = self.client.get(self.API_PATH)
     results = json.loads(response.content)
     variable = results[0]
     self.assertListEqual(expected_fields, list(variable.keys()))
Пример #20
0
 def test_basket_variable_limit(self):
     """Define how the basket limit should work."""
     too_many_variables = [
         VariableFactory(name=str(number)) for number in range(1, 11)
     ]
     too_many_variable_ids = [
         str(variable.id) for variable in too_many_variables
     ]
     with patch(
             "ddionrails.api.views.user_tools.BasketVariableSet.basket_limit",
             new_callable=PropertyMock,
     ) as basket_limit:
         basket_limit.return_value = 10
         post_data = {
             "basket": str(self.basket.id),
             "variables": too_many_variable_ids,
         }
         self.client.force_authenticate(user=self.user)
         post_response = self.client.post(self.API_PATH,
                                          post_data,
                                          format="json")
         self.assertEqual(406, post_response.status_code)
Пример #21
0
    def test_query_parameter_study(self):
        """Define study parameter behavior."""
        dataset = DatasetFactory(name="different-dataset")
        study = StudyFactory(name="different-study")
        study_name = study.name
        dataset.study = study
        dataset.save()
        variable_list = []

        for number in range(1, 11):
            _variable = VariableFactory(name=str(number))
            _variable.dataset = dataset
            _variable.save()
            variable_list.append(_variable)

        for number in range(11, 21):
            _variable = VariableFactory(name=str(number))
            variable_list.append(_variable)

        response = self.client.get(self.API_PATH + f"?study={study_name}")
        content = json.loads(response.content)
        self.assertEqual(10, len(content))
Пример #22
0
def variable(db):
    """ A variable in the database """
    return VariableFactory(name="some-variable",
                           label="Some Variable",
                           description="This is some variable")