id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
140,648
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestUsePropertyNameRepresentationForPartReferences
class TestUsePropertyNameRepresentationForPartReferences( Bases._TestPropertyRepresentation ): property_type = PropertyType.REFERENCES_VALUE representation_class = UsePropertyNameRepresentation value = True new_value = False def test_empty_config_value(self): # get the representation on the object repr = self.obj.representations[-1] # set it as an empty config object repr_json = repr.as_json() repr_json["config"] = {} new_value_options = dict(representations=[repr_json]) # edit options directly otherwise it would not 'stick' self.obj.edit(options=new_value_options) # reload from server the representations self.obj.refresh() repr = self.obj.representations[-1] # check sanity of the representation with the empty object. self.assertDictEqual(self.obj._options.get("representations")[0], repr_json) self.assertEqual(type(repr), UsePropertyNameRepresentation) self.assertIsNone(repr.value)
class TestUsePropertyNameRepresentationForPartReferences( Bases._TestPropertyRepresentation ): def test_empty_config_value(self): pass
2
0
19
3
11
5
1
0.28
1
3
1
0
1
0
1
85
27
4
18
10
14
5
16
8
14
1
5
0
1
140,649
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestUsePropertyNameRepresentationForScopeReferences
class TestUsePropertyNameRepresentationForScopeReferences( Bases._TestPropertyRepresentation ): property_type = PropertyType.SCOPE_REFERENCES_VALUE representation_class = UsePropertyNameRepresentation value = True new_value = False
class TestUsePropertyNameRepresentationForScopeReferences( Bases._TestPropertyRepresentation ): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
7
0
7
7
4
0
5
5
4
0
5
0
0
140,650
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestUsePropertyNameRepresentationForServiceReferences
class TestUsePropertyNameRepresentationForServiceReferences( Bases._TestPropertyRepresentation ): property_type = PropertyType.SERVICE_REFERENCES_VALUE representation_class = UsePropertyNameRepresentation value = True new_value = False
class TestUsePropertyNameRepresentationForServiceReferences( Bases._TestPropertyRepresentation ): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
7
0
7
7
4
0
5
5
4
0
5
0
0
140,651
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestUsePropertyNameRepresentationForUserReferences
class TestUsePropertyNameRepresentationForUserReferences( Bases._TestPropertyRepresentation ): property_type = PropertyType.USER_REFERENCES_VALUE representation_class = UsePropertyNameRepresentation value = True new_value = False
class TestUsePropertyNameRepresentationForUserReferences( Bases._TestPropertyRepresentation ): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
7
0
7
7
4
0
5
5
4
0
5
0
0
140,652
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestRepresentationJSON
class TestRepresentationJSON(TestCase): def test_valid_button_representation_json(self): validate(options_json_schema, options)
class TestRepresentationJSON(TestCase): def test_valid_button_representation_json(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
73
3
0
3
2
1
0
3
2
1
1
2
0
1
140,653
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestAlwaysAllowValidator
class TestAlwaysAllowValidator(TestCase): def test_always_allow_validator_without_settings(self): validator = AlwaysAllowValidator() self.assertTrue(validator.is_valid("some text")) self.assertTrue(validator.is_valid(42)) self.assertTrue(validator.is_valid(42.0)) self.assertTrue(validator.is_valid(["a", "b"])) self.assertTrue(validator.is_valid(True)) self.assertTrue(validator.is_valid(False)) self.assertTrue(validator.is_valid(None)) self.assertTrue(validator.is_valid({"a": "b"})) self.assertFalse(validator.is_invalid(None)) self.assertTrue(validator.is_valid(list())) self.assertTrue(validator.is_valid(set())) self.assertTrue(validator.is_valid(tuple())) self.assertIsNone(validator.validate_json())
class TestAlwaysAllowValidator(TestCase): def test_always_allow_validator_without_settings(self): pass
2
0
15
0
15
0
1
0
1
4
1
0
1
0
1
73
16
0
16
3
14
0
16
3
14
1
2
0
1
140,654
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.CardWidgetLinkTarget
class CardWidgetLinkTarget(LinkTargets): """Target for the CardWidget, remaining for backwards compatibility.""" pass
class CardWidgetLinkTarget(LinkTargets): '''Target for the CardWidget, remaining for backwards compatibility.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
2
4
1
2
1
1
1
2
1
1
0
2
0
0
140,655
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.CardWidgetLinkValue
class CardWidgetLinkValue(Enum): """ Link Value for the CardWidget. .. versionadded:: 3.0 :cvar EXTERNAL_LINK: "External link" :cvar TASK_LINK: "Task link" :cvar NO_LINK: "No link" """ EXTERNAL_LINK = "External link" TASK_LINK = "Task link" TREE_VIEW = "Tree view" NO_LINK = "No link"
class CardWidgetLinkValue(Enum): ''' Link Value for the CardWidget. .. versionadded:: 3.0 :cvar EXTERNAL_LINK: "External link" :cvar TASK_LINK: "Task link" :cvar NO_LINK: "No link" ''' pass
1
1
0
0
0
0
0
1.4
1
0
0
0
0
0
0
2
15
3
5
5
4
7
5
5
4
0
1
0
0
140,656
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.Category
class Category(Enum): """The various categories of Parts that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Part documentation`_. :cvar INSTANCE: Category of Instance :cvar MODEL: Category of Model """ INSTANCE = "INSTANCE" MODEL = "MODEL"
class Category(Enum): '''The various categories of Parts that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Part documentation`_. :cvar INSTANCE: Category of Instance :cvar MODEL: Category of Model ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
2
12
3
3
3
2
6
3
3
2
0
1
0
0
140,657
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.Classification
class Classification(Enum): """The various classification of Parts that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Part documentation`_. :cvar PRODUCT: Classification of the part object is Product :cvar CATALOG: Classification of the part object is a CATALOG .. _Part documentation: https://support.ke-chain.com/confluence/dosearchsite.action? queryString=concept+part """ PRODUCT = "PRODUCT" CATALOG = "CATALOG" FORM = "FORM"
class Classification(Enum): '''The various classification of Parts that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Part documentation`_. :cvar PRODUCT: Classification of the part object is Product :cvar CATALOG: Classification of the part object is a CATALOG .. _Part documentation: https://support.ke-chain.com/confluence/dosearchsite.action? queryString=concept+part ''' pass
1
1
0
0
0
0
0
2
1
0
0
0
0
0
0
2
16
4
4
4
3
8
4
4
3
0
1
0
0
140,658
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ContextGroup
class ContextGroup(Enum): """ Context may have a context_group. ..versionadded: 3.11 This is for context API versions 1.2.0 or later. :cvar UNDEFINED: UNDEFINED :cvar DISCIPLINE: Discipline, in nl: Discipline :cvar ASSET: Asset, in nl: Object, Kunstwerk :cvar DEPARTMENT: Department, in nl: Onderdeel, Afdeling :cvar PERIOD: Workperiod, in nl: Werkperiode :cvar LOCATION: Location, in nl: Locatie :cvar PHASE: Phase, in nl: Fase :cvar REQUIREMENT: Requirement, in nl: Eis :cvar EXTERNALID: External identifier, to be used to provide a generic link to an external application :cvar WORKPACKAGE: Workpackage, in nl: Werkpakket """ UNDEFINED = "UNDEFINED" DISCIPLINE = "DISCIPLINE" # nl: Discipline ASSET = "ASSET" # nl: Object, Kunstwerk DEPARTMENT = "DEPARTMENT" # nl: Onderdeel, Afdeling PERIOD = "WORKPERIOD" # nl: Werkperiode LOCATION = "LOCATION" # nl: Locatie PHASE = "PHASE" # nl: Fase REQUIREMENT = "REQUIREMENT" # nl: Eis EXTERNALID = "EXTERNALID" WORKPACKAGE = "WORKPACKAGE"
class ContextGroup(Enum): ''' Context may have a context_group. ..versionadded: 3.11 This is for context API versions 1.2.0 or later. :cvar UNDEFINED: UNDEFINED :cvar DISCIPLINE: Discipline, in nl: Discipline :cvar ASSET: Asset, in nl: Object, Kunstwerk :cvar DEPARTMENT: Department, in nl: Onderdeel, Afdeling :cvar PERIOD: Workperiod, in nl: Werkperiode :cvar LOCATION: Location, in nl: Locatie :cvar PHASE: Phase, in nl: Fase :cvar REQUIREMENT: Requirement, in nl: Eis :cvar EXTERNALID: External identifier, to be used to provide a generic link to an external application :cvar WORKPACKAGE: Workpackage, in nl: Werkpakket ''' pass
1
1
0
0
0
0
0
2.18
1
0
0
0
0
0
0
2
31
4
11
11
10
24
11
11
10
0
1
0
0
140,659
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ContextType
class ContextType(Enum): """Types of Contexts. :cvar STATIC_LOCATION: Geolocation / Featurecollection context with a geolocation. :cvar TIME_PERIOD: Time Period Context with start_date and due_date :cvar TEXT_LABEL: generic textual label """ STATIC_LOCATION = "STATIC_LOCATION" TIME_PERIOD = "TIME_PERIOD" TEXT_LABEL = "TEXT_LABEL"
class ContextType(Enum): '''Types of Contexts. :cvar STATIC_LOCATION: Geolocation / Featurecollection context with a geolocation. :cvar TIME_PERIOD: Time Period Context with start_date and due_date :cvar TEXT_LABEL: generic textual label ''' pass
1
1
0
0
0
0
0
1.25
1
0
0
0
0
0
0
2
11
2
4
4
3
5
4
4
3
0
1
0
0
140,660
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.Enum
class Enum: """Custom enumeration class to support class attributes as options. Example ------- >>> class Toppings(Enum): ... CHEESE = "Cheese" ... SALAMI = "Salami" >>> topping_choice = Toppings.CHEESE """ @classmethod def options(cls): """Provide a sorted list of options.""" return sorted( (value, name) for (name, value) in __dict__inherited__(cls=cls, stop=Enum).items() ) @classmethod def values(cls): """Provide a (sorted) list of values.""" return [value for (value, name) in cls.options()]
class Enum: '''Custom enumeration class to support class attributes as options. Example ------- >>> class Toppings(Enum): ... CHEESE = "Cheese" ... SALAMI = "Salami" >>> topping_choice = Toppings.CHEESE ''' @classmethod def options(cls): '''Provide a sorted list of options.''' pass @classmethod def values(cls): '''Provide a (sorted) list of values.''' pass
5
3
5
0
4
1
1
1
0
0
0
73
0
0
2
2
24
4
10
6
5
10
5
3
2
1
0
0
2
140,661
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.FileDisplayRepresentationValues
class FileDisplayRepresentationValues(Enum): """ Values that can be put in the FileDisplayRepresentationValues for representing stored files. :cvar CARDS: thumbnails of attachments inside stored files, when applicable. :cvar TEXT: name of the attachments inside stored files. """ CARDS = "CARDS" TEXT = "TEXT"
class FileDisplayRepresentationValues(Enum): ''' Values that can be put in the FileDisplayRepresentationValues for representing stored files. :cvar CARDS: thumbnails of attachments inside stored files, when applicable. :cvar TEXT: name of the attachments inside stored files. ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
2
10
2
3
3
2
5
3
3
2
0
1
0
0
140,662
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.FilterType
class FilterType(Enum): """The type of pre-filters that can be set on a Multi Reference Property. .. versionadded:: 3.0 :cvar GREATER_THAN_EQUAL: 'gte' :cvar LOWER_THAN_EQUAL: 'lte' :cvar CONTAINS: 'icontains' :cvar EXACT: 'exact' """ GREATER_THAN_EQUAL = "gte" LOWER_THAN_EQUAL = "lte" CONTAINS = "icontains" CONTAINS_SET = "contains" EXACT = "exact"
class FilterType(Enum): '''The type of pre-filters that can be set on a Multi Reference Property. .. versionadded:: 3.0 :cvar GREATER_THAN_EQUAL: 'gte' :cvar LOWER_THAN_EQUAL: 'lte' :cvar CONTAINS: 'icontains' :cvar EXACT: 'exact' ''' pass
1
1
0
0
0
0
0
1.17
1
0
0
0
0
0
0
2
16
3
6
6
5
7
6
6
5
0
1
0
0
140,663
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestBooleanFieldValidator
class TestBooleanFieldValidator(TestCase): def test_boolean_validator_without_settings(self): validator = BooleanFieldValidator() self.assertIsNone(validator.validate_json()) self.assertIsInstance(validator.as_json(), dict) self.assertDictEqual( validator.as_json(), {"config": {}, "vtype": "booleanFieldValidator"} )
class TestBooleanFieldValidator(TestCase): def test_boolean_validator_without_settings(self): pass
2
0
7
0
7
0
1
0
1
2
1
0
1
0
1
73
8
0
8
3
6
0
6
3
4
1
2
0
1
140,664
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.FormCategory
class FormCategory(Enum): """ Options for the Category of a Form. :cvar MODEL: Model :cvar INSTANCE: Instance """ MODEL = "MODEL" INSTANCE = "INSTANCE"
class FormCategory(Enum): ''' Options for the Category of a Form. :cvar MODEL: Model :cvar INSTANCE: Instance ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
2
10
2
3
3
2
5
3
3
2
0
1
0
0
140,665
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestRepresentation
class TestRepresentation(TestCase): def test_create(self): representation = BaseRepresentation() self.assertIsInstance(representation, BaseRepresentation) def test_create_with_value(self): representation = DecimalPlaces(value=3) self.assertEqual(3, representation.value) def test_create_with_object(self): empty_prop = Property(json={}, client=None) representation = ButtonRepresentation(empty_prop) self.assertIsInstance(representation, ButtonRepresentation) def test_parse(self): empty_slp = SelectListProperty(json={"value_options": {}}, client=None) BaseRepresentation.parse(obj=empty_slp, json=representation_config) def test_parse_incorrect_rtype(self): no_rtype_config = dict( config=dict( buttonRepresentation="dropdown", ) ) with self.assertRaises(ValueError): BaseRepresentation.parse(obj=None, json=no_rtype_config) def test_parse_unknown_rtype(self): no_rtype_config = dict( rtype="Not a representation type", config=dict( buttonRepresentation="dropdown", ), ) with self.assertRaises(TypeError): BaseRepresentation.parse(obj=None, json=no_rtype_config) def test_component_invalid_object(self): empty_activity = Activity(json={"id": "1234567890"}, client=None) representation = ThousandsSeparator(empty_activity) with self.assertRaises(IllegalArgumentError): empty_activity.representations = [representation] def test_component_invalid_property_type(self): empty_prop = Property( json={"id": "1234567890", "category": "MODEL"}, client=None ) representation = ThousandsSeparator(empty_prop) representation.rtype = "Broken rtype" with self.assertRaises(IllegalArgumentError): empty_prop.representations = [representation] def test_component_not_a_list(self): empty_activity = Activity(json={}, client=None) with self.assertRaises(IllegalArgumentError): empty_activity.representations = "Howdy!" def test_component_not_a_representation(self): empty_activity = Activity(json={}, client=None) with self.assertRaises(IllegalArgumentError): empty_activity.representations = ["Howdy again!"]
class TestRepresentation(TestCase): def test_create(self): pass def test_create_with_value(self): pass def test_create_with_object(self): pass def test_parse(self): pass def test_parse_incorrect_rtype(self): pass def test_parse_unknown_rtype(self): pass def test_component_invalid_object(self): pass def test_component_invalid_property_type(self): pass def test_component_not_a_list(self): pass def test_component_not_a_representation(self): pass
11
0
6
1
5
0
1
0
1
10
7
0
10
0
10
82
68
16
52
24
41
0
41
24
30
1
2
1
10
140,666
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprStoredFileDisplayRepresentationText
class TestReprStoredFileDisplayRepresentationText(Bases._TestPropertyRepresentation): property_type = PropertyType.STOREDFILE_REFERENCES_VALUE representation_class = StoredFilesDisplayRepresentation value = None new_value = FileDisplayRepresentationValues.TEXT
class TestReprStoredFileDisplayRepresentationText(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,667
KE-works/pykechain
KE-works_pykechain/tests/models/test_property_reference.py
tests.models.test_property_reference.TestPropertyUserReference
class TestPropertyUserReference(TestBetamax): def setUp(self): super().setUp() root = self.project.model(name="Product") self.part = self.project.create_model( name="Test part", parent=root, multiplicity=Multiplicity.ONE ) self.user_ref_prop = self.part.add_property( name="user ref", property_type=PropertyType.USER_REFERENCES_VALUE ) def tearDown(self): if self.part: self.part.delete() super().tearDown() def test_create(self): self.assertIsInstance(self.user_ref_prop, UserReferencesProperty) def test_value(self): user = self.client.user(name="User Test") self.user_ref_prop.value = [user] self.assertIsInstance(self.user_ref_prop, UserReferencesProperty) self.assertIsNotNone(self.user_ref_prop.value) self.assertEqual(user, self.user_ref_prop.value[0]) def test_value_ids(self): user = self.client.user(name="User Test") self.user_ref_prop.value = [user] self.user_ref_prop.refresh() ids = self.user_ref_prop.value_ids() self.assertIsInstance(ids, list) self.assertTrue(all(isinstance(v, int) for v in ids)) def test_no_value(self): self.assertIsInstance(self.user_ref_prop, UserReferencesProperty) self.assertIsNone(self.user_ref_prop.value) def test_reload(self): reloaded_prop = self.client.reload(obj=self.user_ref_prop) self.assertFalse( self.user_ref_prop is reloaded_prop, msg="Must be different Python objects, based on memory allocation", ) self.assertEqual( self.user_ref_prop, reloaded_prop, msg="Must be the same KE-chain prop, based on hashed UUID", )
class TestPropertyUserReference(TestBetamax): def setUp(self): pass def tearDown(self): pass def test_create(self): pass def test_value(self): pass def test_value_ids(self): pass def test_no_value(self): pass def test_reload(self): pass
8
0
7
1
6
0
1
0
1
6
3
0
7
2
7
82
57
14
43
15
35
0
32
15
24
2
3
1
8
140,668
KE-works/pykechain
KE-works_pykechain/tests/models/test_property_selectlist.py
tests.models.test_property_selectlist.SelectListBaseTests
class SelectListBaseTests: """This wrapping class is excluded from the test runs, but can be inherited from.""" class Tests(TestBetamax): """Tests for the select list properties.""" PROPERTY_TYPE = None OPTIONS = ["1", "3.14", "text"] def setUp(self): super().setUp() self.select_model = self.project.model("Bike").add_property( name=self.PROPERTY_TYPE, property_type=self.PROPERTY_TYPE, options={"value_choices": ["1", "3.14", "text"]}, ) self.select = self.project.part("Bike").property(self.PROPERTY_TYPE) def tearDown(self): self.select_model.delete() super().tearDown() def test_get_options_list(self): self.assertTrue(hasattr(self.select_model, "options")) self.assertIsInstance(self.select_model.options, list) for item in self.select_model.options: self.assertTrue(type(item), str) def test_set_options_list(self): # setUp current_options_list = [1, 3.14, "text"] new_options_list = ["some", "new", 4, "options"] self.select_model.options = new_options_list # testing self.assertListEqual( self.select_model.options, list(map(str, new_options_list)) ) # teardown self.select_model.options = current_options_list def test_illegal_options_are_not_set(self): """Test for several illegal lists to be set""" with self.assertRaises(IllegalArgumentError): # not a list self.select_model.options = 1 with self.assertRaises(IllegalArgumentError): self.select_model.options = None with self.assertRaises(IllegalArgumentError): # set self.select_model.options = {1, 2, 3} with self.assertRaises(IllegalArgumentError): # dict self.select_model.options = {"a": 1, "b": 2, "c": 3} with self.assertRaises(IllegalArgumentError): # tuple self.select_model.options = (1,) def test_fail_to_set_options_on_instance(self): """Test settings options on a property instance, only models are allowed options to be set""" self.assertTrue(hasattr(self.select, "options")) with self.assertRaises(IllegalArgumentError): self.select.options = [1, 3.14] def test_integrity_options_dict(self): # setUp original_options_dict = dict(self.select_model._options) self.select_model.options = list(self.select_model.options) # testing testing_options_dict = self.select_model._options self.assertEqual(original_options_dict, testing_options_dict)
class SelectListBaseTests: '''This wrapping class is excluded from the test runs, but can be inherited from.''' class Tests(TestBetamax): '''Tests for the select list properties.''' def setUp(self): pass def tearDown(self): pass def test_get_options_list(self): pass def test_set_options_list(self): pass def test_illegal_options_are_not_set(self): '''Test for several illegal lists to be set''' pass def test_fail_to_set_options_on_instance(self): '''Test settings options on a property instance, only models are allowed options to be set''' pass def test_integrity_options_dict(self): pass
9
4
9
1
6
2
1
0.27
0
0
0
0
0
0
0
0
79
18
48
18
39
13
42
18
33
2
0
1
8
140,669
KE-works/pykechain
KE-works_pykechain/tests/models/test_property_selectlist.py
tests.models.test_property_selectlist.TestPropertyMultiSelectListProperty
class TestPropertyMultiSelectListProperty(SelectListBaseTests.Tests): PROPERTY_TYPE = PropertyType.MULTI_SELECT_VALUE def test_value(self): self.select.value = self.OPTIONS[0:1] self.assertIsInstance(self.select, MultiSelectListProperty) # in 1.16 def test_set_value_in_options(self): # setUp current_options_list = self.select_model.options selection = current_options_list[1:2] self.select.value = selection # testing option_that_is_set = self.select.value self.assertEqual(selection, option_that_is_set) def test_set_value_not_in_options_raises_error(self): with self.assertRaises(IllegalArgumentError): self.select.value = [ "Some illegal value that is not inside the list of options for sure" ]
class TestPropertyMultiSelectListProperty(SelectListBaseTests.Tests): def test_value(self): pass def test_set_value_in_options(self): pass def test_set_value_not_in_options_raises_error(self): pass
4
0
6
0
5
1
1
0.19
1
2
2
0
3
0
3
85
23
4
16
8
12
3
14
8
10
1
4
1
3
140,670
KE-works/pykechain
KE-works_pykechain/tests/models/test_property_selectlist.py
tests.models.test_property_selectlist.TestPropertySelectListProperty
class TestPropertySelectListProperty(SelectListBaseTests.Tests): PROPERTY_TYPE = PropertyType.SINGLE_SELECT_VALUE def test_value(self): self.select.value = self.OPTIONS[0] self.assertIsInstance(self.select, SelectListProperty) def test_pend_value(self): self.select.value = None Property.set_bulk_update(True) self.select.value = self.OPTIONS[1] live_property = self.project.property(id=self.select.id) self.assertFalse(live_property.has_value()) Property.update_values(client=self.client) live_property.refresh() self.assertTrue(live_property.has_value()) # in 1.16 def test_set_value_in_options(self): # setUp current_options_list = self.select_model.options first_option = current_options_list[0] self.select.value = first_option # testing option_that_is_set = self.select.value self.assertEqual(first_option, option_that_is_set) # in 1.15 def test_set_value_not_in_options_raises_error(self): with self.assertRaises(IllegalArgumentError): self.select.value = ( "Some illegal value that is not inside the list of options for sure" )
class TestPropertySelectListProperty(SelectListBaseTests.Tests): def test_value(self): pass def test_pend_value(self): pass def test_set_value_in_options(self): pass def test_set_value_not_in_options_raises_error(self): pass
5
0
8
2
6
1
1
0.16
1
2
2
0
4
0
4
86
39
10
25
10
20
4
23
10
18
1
4
1
4
140,671
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.Bases
class Bases: """ Wrapping private test classes in this Base class allows some inheritance mechanisms to be used. If the _Test...() classes would not be wrapped, the test framework would try to run these abstract classes. """ class _TestRepresentationLive(TestBetamax): """ Specify these class attributes in every sub-class """ representation_class = None # type: type(BaseRepresentation) value = None new_value = None incorrect_value = None test_object_name = "__test object for representations" def setUp(self): super().setUp() self.obj = self._get_object() try: self.obj.representations = [ self.representation_class( obj=self.obj, value=self.value, ), ] except Exception as e: self.obj.part.delete() raise e def tearDown(self): if self.obj: try: self.obj.delete() except APIError: pass super().tearDown() @abstractmethod def _get_object(self) -> Union[Property, Scope, Activity]: pass def test_create_with_prop(self): representation = self.representation_class(prop=self.obj, value=self.value) self.assertIsInstance(representation, self.representation_class) def test_get_set(self): """Test representation accessor property of the Mixin class""" reloaded_obj = self.client.reload(self.obj) self.assertEqual(self.obj, reloaded_obj) # setUp: get representations first_representation = reloaded_obj.representations[0] self.assertIsInstance(first_representation, self.representation_class) self.assertEqual(self.value, first_representation.value) def test_set_value(self): """Test value accessor property of the Representation class""" # Set new value via the representation object first_repr = self.obj.representations[0] first_repr.value = self.new_value # Retrieve representation again reloaded_obj = self.client.reload(self.obj) self.assertEqual(self.obj, reloaded_obj) first_representation = reloaded_obj.representations[0] # testing self.assertEqual(first_repr.value, first_representation.value) def test_unsupported_value(self): with self.assertRaises(IllegalArgumentError): self.representation_class( obj=self.obj, value=self.incorrect_value, ) class _TestPropertyRepresentation(_TestRepresentationLive): property_type = None test_model_name = "__test model for representations" test_model = None incorrect_value = "Unsupported value" def tearDown(self): if self.test_model: try: self.test_model.delete() except APIError: pass super().tearDown() def _get_object(self): parent_model = self.project.model(name="Bike") self.test_model = parent_model.add_model( name=self.test_model_name, multiplicity=Multiplicity.ONE ) obj = self.test_model.add_property( name=self.test_object_name, property_type=self.property_type, ) # type: AnyProperty return obj class _TestCustomIconRepresentation(_TestRepresentationLive, ABC): representation_class = CustomIconRepresentation value = "university" new_value = "bat" incorrect_value = ["must be a string"] def test_set_mode(self): representation = self.obj.representations[ 0 ] # type: CustomIconRepresentation # Set mode representation.display_mode = FontAwesomeMode.SOLID reloaded_obj = self.client.reload(obj=self.obj) reloaded_repr = reloaded_obj.representations[0] # Test get of mode self.assertEqual(representation.display_mode, reloaded_repr.display_mode) def test_set_mode_incorrect(self): representation = self.obj.representations[ 0 ] # type: CustomIconRepresentation with self.assertRaises(IllegalArgumentError): representation.display_mode = "fancy colors"
class Bases: ''' Wrapping private test classes in this Base class allows some inheritance mechanisms to be used. If the _Test...() classes would not be wrapped, the test framework would try to run these abstract classes. ''' class _TestRepresentationLive(TestBetamax): ''' Specify these class attributes in every sub-class ''' def setUp(self): pass def tearDown(self): pass @abstractmethod def _get_object(self) -> Union[Property, Scope, Activity]: pass def test_create_with_prop(self): pass def test_get_set(self): '''Test representation accessor property of the Mixin class''' pass def test_set_value(self): '''Test value accessor property of the Representation class''' pass def test_unsupported_value(self): pass class _TestPropertyRepresentation(_TestRepresentationLive): def tearDown(self): pass def _get_object(self) -> Union[Property, Scope, Activity]: pass class _TestCustomIconRepresentation(_TestRepresentationLive, ABC): def test_set_mode(self): pass def test_set_mode_incorrect(self): pass
16
4
8
1
7
1
1
0.2
0
0
0
0
0
0
0
0
135
27
93
44
77
19
75
41
60
3
0
2
16
140,672
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestGeocoordinateRepresentation
class TestGeocoordinateRepresentation(Bases._TestPropertyRepresentation): property_type = PropertyType.GEOJSON_VALUE representation_class = GeoCoordinateRepresentation value = GeoCoordinateConfig.RD_AMERSFOORT new_value = GeoCoordinateConfig.APPROX_ADDRESS
class TestGeocoordinateRepresentation(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,673
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprActivity
class TestReprActivity(Bases._TestCustomIconRepresentation): def _get_object(self): return self.project.create_activity(name=self.test_object_name)
class TestReprActivity(Bases._TestCustomIconRepresentation): def _get_object(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
105
3
0
3
2
1
0
3
2
1
1
5
0
1
140,674
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprAutofill
class TestReprAutofill(Bases._TestPropertyRepresentation): property_type = PropertyType.DATETIME_VALUE representation_class = Autofill value = False new_value = True
class TestReprAutofill(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,675
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprAutofillUser
class TestReprAutofillUser(Bases._TestPropertyRepresentation): property_type = PropertyType.USER_REFERENCES_VALUE representation_class = Autofill value = False new_value = True
class TestReprAutofillUser(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,676
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprThousandsSeparator
class TestReprThousandsSeparator(Bases._TestPropertyRepresentation): property_type = PropertyType.FLOAT_VALUE representation_class = ThousandsSeparator value = None new_value = None
class TestReprThousandsSeparator(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,677
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprButton
class TestReprButton(Bases._TestPropertyRepresentation): property_type = PropertyType.SINGLE_SELECT_VALUE representation_class = ButtonRepresentation value = SelectListRepresentations.CHECK_BOXES new_value = SelectListRepresentations.BUTTONS def setUp(self): super().setUp() self.obj.options = ["alpha", "beta", "gamma", "omega"]
class TestReprButton(Bases._TestPropertyRepresentation): def setUp(self): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
0
1
85
9
1
8
6
6
0
8
6
6
1
5
0
1
140,678
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprLinkTarget
class TestReprLinkTarget(Bases._TestPropertyRepresentation): property_type = PropertyType.LINK_VALUE representation_class = LinkTarget value = LinkTargets.SAME_TAB new_value = LinkTargets.NEW_TAB
class TestReprLinkTarget(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,679
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprScope
class TestReprScope(Bases._TestCustomIconRepresentation): def _get_object(self): return self.client.create_scope(name=self.test_object_name)
class TestReprScope(Bases._TestCustomIconRepresentation): def _get_object(self): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
105
3
0
3
2
1
0
3
2
1
1
5
0
1
140,680
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprScopeMembersOnlyRepresentation
class TestReprScopeMembersOnlyRepresentation(Bases._TestPropertyRepresentation): property_type = PropertyType.USER_REFERENCES_VALUE representation_class = ScopeMembersOnlyRepresentation value = None new_value = None
class TestReprScopeMembersOnlyRepresentation(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,681
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprSignatureRepresentationClean
class TestReprSignatureRepresentationClean(Bases._TestPropertyRepresentation): property_type = PropertyType.ATTACHMENT_VALUE representation_class = SignatureRepresentation value = None new_value = SignatureRepresentationValues.CLEAN
class TestReprSignatureRepresentationClean(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,682
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprSignatureRepresentationFromCleanToNameAndDate
class TestReprSignatureRepresentationFromCleanToNameAndDate( Bases._TestPropertyRepresentation ): property_type = PropertyType.ATTACHMENT_VALUE representation_class = SignatureRepresentation value = SignatureRepresentationValues.CLEAN new_value = SignatureRepresentationValues.NAME_AND_DATE
class TestReprSignatureRepresentationFromCleanToNameAndDate( Bases._TestPropertyRepresentation ): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
7
0
7
7
4
0
5
5
4
0
5
0
0
140,683
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprSignatureRepresentationNameAndDate
class TestReprSignatureRepresentationNameAndDate(Bases._TestPropertyRepresentation): property_type = PropertyType.ATTACHMENT_VALUE representation_class = SignatureRepresentation value = None new_value = SignatureRepresentationValues.NAME_AND_DATE
class TestReprSignatureRepresentationNameAndDate(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,684
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprSignificantDigits
class TestReprSignificantDigits(Bases._TestPropertyRepresentation): property_type = PropertyType.FLOAT_VALUE representation_class = SignificantDigits value = 3 new_value = 1
class TestReprSignificantDigits(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,685
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprStoredFileDisplayRepresentationCards
class TestReprStoredFileDisplayRepresentationCards(Bases._TestPropertyRepresentation): property_type = PropertyType.STOREDFILE_REFERENCES_VALUE representation_class = StoredFilesDisplayRepresentation value = None new_value = FileDisplayRepresentationValues.CARDS
class TestReprStoredFileDisplayRepresentationCards(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,686
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprStoredFileDisplayRepresentationFromCardsToText
class TestReprStoredFileDisplayRepresentationFromCardsToText( Bases._TestPropertyRepresentation ): property_type = PropertyType.STOREDFILE_REFERENCES_VALUE representation_class = StoredFilesDisplayRepresentation value = FileDisplayRepresentationValues.CARDS new_value = FileDisplayRepresentationValues.TEXT
class TestReprStoredFileDisplayRepresentationFromCardsToText( Bases._TestPropertyRepresentation ): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
7
0
7
7
4
0
5
5
4
0
5
0
0
140,687
KE-works/pykechain
KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.TestReprDecimalPlaces
class TestReprDecimalPlaces(Bases._TestPropertyRepresentation): property_type = PropertyType.FLOAT_VALUE representation_class = DecimalPlaces value = 3 new_value = 5
class TestReprDecimalPlaces(Bases._TestPropertyRepresentation): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
84
5
0
5
5
4
0
5
5
4
0
5
0
0
140,688
KE-works/pykechain
KE-works_pykechain/tests/test_client.py
tests.test_client.TestClientAppVersions
class TestClientAppVersions(TestBetamax): def test_retrieve_versions(self): """Test to retrieve the app versions from KE-chain""" app_versions = self.project._client.app_versions self.assertTrue(isinstance(app_versions, list)) self.assertTrue(isinstance(app_versions[0], dict)) self.assertTrue( set(app_versions[0].keys()), {"app", "label", "version", "major", "minor", "patch", "prerelease"}, ) def test_compare_versions(self): """Multitest to check all the matchings versions""" self.assertTrue( self.client.match_app_version(app="kechain2.core.wim", version=">=1.0.0") ) self.assertTrue(self.client.match_app_version(label="wim", version=">=1.0.0")) self.assertFalse(self.client.match_app_version(label="wim", version="==0.0.1")) # value error # wrong version string (no semver string) to check against with self.assertRaises(ValueError): self.client.match_app_version(app="kechain2.core.wim", version="1.0") with self.subTest( "right version, no operand in version, works as equality ops, should return False" ): self.assertFalse( self.client.match_app_version(app="kechain2.core.wim", version="99.99.99") ) with self.subTest("wrong operand (should be ==)"): with self.assertRaises(ValueError): self.client.match_app_version(app="kechain2.core.wim", version="=1.0.0") with self.subTest("not found a match version"): with self.assertRaises(IllegalArgumentError): self.client.match_app_version(app="kechain2.core.wim", version="") with self.subTest("no version found on the app kechain2.metrics"): with self.assertRaises(NotFoundError): self.client.match_app_version( app="kechain2.core.activitylog", version=">0.0.0", default=None ) with self.subTest( "no version found on the app kechain2.metrics, default = True, returns True" ): self.assertTrue( self.client.match_app_version( app="kechain2.core.activitylog", version=">0.0.0", default=True ) ) with self.subTest( "no version found on the app kechain2.metrics, default = False, returns False" ): self.assertFalse( self.client.match_app_version( app="kechain2.core.activitylog", version=">0.0.0", default=False ) ) with self.subTest( "no version found on the app kechain2.metrics, default = False, returns False. " "default is set to return False in the method" ): self.assertFalse( self.client.match_app_version( app="kechain2.core.activitylog", version=">0.0.0" ) ) with self.subTest("did not find the app"): with self.assertRaises(NotFoundError): self.client.match_app_version( app="nonexistingapp", version=">0.0.0", default=None ) with self.subTest("did not find the app, but the default returns a False"): self.assertFalse( self.client.match_app_version( app="nonexistingapp", version=">0.0.0", default=False ) ) with self.subTest( "did not find the app, but the default returns a False, without providing the " "default, as the default is False" ): self.assertFalse( self.client.match_app_version(app="nonexistingapp", version=">0.0.0") )
class TestClientAppVersions(TestBetamax): def test_retrieve_versions(self): '''Test to retrieve the app versions from KE-chain''' pass def test_compare_versions(self): '''Multitest to check all the matchings versions''' pass
3
2
46
6
38
2
1
0.05
1
6
2
0
2
0
2
77
94
13
77
4
74
4
36
4
33
1
3
2
2
140,689
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestPropertyWithValidator
class TestPropertyWithValidator(TestCase): def test_property_without_validator(self): prop = Property(json={}, client=None) self.assertIsNone(prop.is_valid) self.assertIsNone(prop.is_invalid) self.assertEqual(prop._validators, list()) self.assertEqual(prop.validate(), list()) def test_property_with_numeric_range_validator(self): prop_json = dict( value=1, value_options=dict( validators=[NumericRangeValidator(minvalue=0, maxvalue=10).as_json()] ), ) prop = Property(json=prop_json, client=None) self.assertTrue(prop.is_valid) self.assertFalse(prop.is_invalid) self.assertTrue(prop.validate()) def test_property_with_numeric_range_validator_value_is_none(self): prop_json = dict( value=None, value_options=dict( validators=[NumericRangeValidator(minvalue=0, maxvalue=10).as_json()] ), ) prop = Property(json=prop_json, client=None) self.assertIsNone(prop.is_valid) self.assertIsNone(prop.is_invalid) self.assertListEqual([(None, "No reason")], prop.validate()) def test_property_with_filesize_validator(self): prop_json = dict( value="attachments/12345678-1234-5678-1234-567812345678/some_file.txt", value_options=dict(validators=[FileSizeValidator(max_size=100).as_json()]), ) prop = AttachmentProperty(json=prop_json, client=None) self.assertTrue(prop.is_valid) self.assertFalse(prop.is_invalid) self.assertTrue(prop.validate()) def test_property_without_value_with_filesize_validator(self): prop_json = dict( value=None, value_options=dict(validators=[FileSizeValidator(max_size=100).as_json()]), ) prop = AttachmentProperty(json=prop_json, client=None) self.assertIsNone(prop.is_valid) self.assertIsNone(prop.is_invalid) self.assertListEqual([(None, "No reason")], prop.validate()) def test_property_with_fileextension_validator(self): prop_json = dict( value="attachments/12345678-1234-5678-1234-567812345678/some_file.txt", value_options=dict( validators=[ FileExtensionValidator(accept=[".txt", "application/pdf"]).as_json() ] ), ) prop = AttachmentProperty(json=prop_json, client=None) self.assertTrue(prop.is_valid) self.assertFalse(prop.is_invalid) self.assertTrue(prop.validate()) def test_property_without_value_with_fileextension_validator(self): prop_json = dict( value=None, value_options=dict( validators=[ FileExtensionValidator(accept=[".txt", "application/pdf"]).as_json() ] ), ) prop = AttachmentProperty(json=prop_json, client=None) self.assertIsNone(prop.is_valid) self.assertIsNone(prop.is_invalid) self.assertListEqual([(None, "No reason")], prop.validate())
class TestPropertyWithValidator(TestCase): def test_property_without_validator(self): pass def test_property_with_numeric_range_validator(self): pass def test_property_with_numeric_range_validator_value_is_none(self): pass def test_property_with_filesize_validator(self): pass def test_property_without_value_with_filesize_validator(self): pass def test_property_with_fileextension_validator(self): pass def test_property_without_value_with_fileextension_validator(self): pass
8
0
10
0
10
0
1
0
1
7
5
0
7
0
7
79
79
6
73
21
65
0
43
21
35
1
2
0
7
140,690
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.LinkTarget
class LinkTarget(BaseRepresentation): """Representation for HTML link reference properties.""" rtype = PropertyRepresentation.LINK_TARGET _config_value_key = "target" def validate_representation(self, value: LinkTargets) -> None: """ Validate whether the representation value can be set. :param value: representation value to set. :type value: LinkTargets :return: None """ if value not in LinkTargets.values(): raise IllegalArgumentError( '{} value "{}" is not correct: Not a CardWidgetLinkTarget option.'.format( self.__class__.__name__, value ) )
class LinkTarget(BaseRepresentation): '''Representation for HTML link reference properties.''' def validate_representation(self, value: LinkTargets) -> None: ''' Validate whether the representation value can be set. :param value: representation value to set. :type value: LinkTargets :return: None ''' pass
2
2
14
1
7
6
2
0.7
1
2
2
0
1
0
1
9
20
3
10
4
8
7
6
4
4
2
1
1
2
140,691
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/models/test_property_reference.py
tests.models.test_property_reference.TestStoredFileReferenceProperty
class TestStoredFileReferenceProperty(TestBetamax): def setUp(self): super().setUp() root = self.project.model(name="Product") self.part = self.project.create_model( name="__TEST_STOREDFILE_REFERENCE_PART", parent=root, multiplicity=Multiplicity.ONE, ) self.storedfile_ref_prop_model = self.part.add_property( name="storedfile ref", property_type=PropertyType.STOREDFILE_REFERENCES_VALUE, ) self.storedfile_ref_prop_instance = self.part.instance().property( name=self.storedfile_ref_prop_model.name ) self.test_files_dir = os.path.dirname( os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") ) self.filename = "test_upload_image.png" self.upload_path = os.path.join( self.test_files_dir, "files", "test_upload_image_to_attachment_property", self.filename, ) self.name = "__STORED_FILE_TEMPORARY" self.stored_file = self.client.create_stored_file( name=self.name, scope=self.project, classification=StoredFileClassification.SCOPED, filepath=self.upload_path, ) self.stored_file_2 = self.client.create_stored_file( name=self.name + "2", scope=self.project, classification=StoredFileClassification.SCOPED, filepath=self.upload_path, ) def tearDown(self): if self.stored_file: self.stored_file.delete() if self.stored_file_2: self.stored_file_2.delete() if self.part: self.part.delete() try: self.uploaded_files = self.client.stored_files(name=self.filename) for uploaded_file in self.uploaded_files: uploaded_file.delete() except NotFoundError: pass super().tearDown() def test_create(self): self.assertIsInstance( self.storedfile_ref_prop_model, StoredFilesReferencesProperty ) def test_value_model(self): self.storedfile_ref_prop_model.value = [self.stored_file] self.storedfile_ref_prop_model.refresh() self.assertIsNotNone(self.storedfile_ref_prop_model.value) self.assertEqual( self.storedfile_ref_prop_model.value[0].id, self.stored_file.id ) self.assertEqual(len(self.storedfile_ref_prop_model.value), 1) def test_no_value_model(self): self.assertIsNone(self.storedfile_ref_prop_model.value) def test_value_instance(self): self.storedfile_ref_prop_instance.value = [self.stored_file] self.assertIsNotNone(self.storedfile_ref_prop_instance.value) self.assertEqual( self.storedfile_ref_prop_instance.value[0].id, self.stored_file.id ) self.assertEqual(len(self.storedfile_ref_prop_instance.value), 1) def test_no_value_instance(self): self.assertEqual(self.storedfile_ref_prop_instance.value, None) def test_multiple_values(self): self.storedfile_ref_prop_instance.value = [ self.stored_file, self.stored_file_2] self.assertEqual(len(self.storedfile_ref_prop_instance.value), 2) self.assertIn( self.stored_file.id, [value.id for value in self.storedfile_ref_prop_instance.value], ) self.assertIn( self.stored_file_2.id, [value.id for value in self.storedfile_ref_prop_instance.value], ) def test_edit_property_model_description(self): self.storedfile_ref_prop_model.edit( description="Test edit description") self.assertIsNotNone(self.storedfile_ref_prop_model.description) def test_edit_property_model_validators(self): self.storedfile_ref_prop_model.validators = [ SingleReferenceValidator(), FileSizeValidator(max_size=200), FileExtensionValidator(accept=".csv,.pdf"), ] self.assertEqual(len(self.storedfile_ref_prop_model.validators), 3) self.assertTrue( any( isinstance(v, FileSizeValidator) for v in self.storedfile_ref_prop_model.validators ) ) self.assertTrue( any( isinstance(v, SingleReferenceValidator) for v in self.storedfile_ref_prop_model.validators ) ) self.assertTrue( any( isinstance(v, FileExtensionValidator) for v in self.storedfile_ref_prop_model.validators ) ) def test_clear_stored_files_from_value(self): self.storedfile_ref_prop_instance.value = [ self.stored_file, self.stored_file_2, ] self.storedfile_ref_prop_instance.clear() self.assertIsNone(self.storedfile_ref_prop_instance.value) def test_filename_of_stored_reference_property_multiple_stored_files(self): self.storedfile_ref_prop_instance.value = [ self.stored_file, self.stored_file_2, ] self.assertIsInstance(self.storedfile_ref_prop_instance.filename, list) self.assertEqual(len(self.storedfile_ref_prop_instance.filename), 2) self.assertEqual( self.storedfile_ref_prop_instance.filename[0], self.filename) self.assertEqual( self.storedfile_ref_prop_instance.filename[1], self.filename) def test_filename_of_stored_reference_property_one_stored_file(self): self.storedfile_ref_prop_instance.value = [ self.stored_file, ] self.assertIsInstance(self.storedfile_ref_prop_instance.filename, str) self.assertEqual( self.storedfile_ref_prop_instance.filename, self.filename) def test_filename_of_stored_reference_property_no_stored_file(self): self.assertEqual(self.storedfile_ref_prop_instance.filename, None) @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as stored_files " "download links have time limited access keys in the uri", ) def test_download_files_from_stored_reference_property(self): self.storedfile_ref_prop_instance.value = [ self.stored_file, self.stored_file_2, ] with temp_chdir() as target_dir: self.storedfile_ref_prop_instance.download(directory=target_dir) self.assertEqual( len( [ entry for entry in os.listdir(target_dir) if os.path.isfile(os.path.join(target_dir, entry)) ] ), 2, ) def test_upload_file_to_empty_value_stored_reference_property(self): self.storedfile_ref_prop_instance.upload(self.upload_path) self.assertEqual(len(self.storedfile_ref_prop_instance.value), 1) self.assertIsInstance( self.storedfile_ref_prop_instance.value[0], StoredFile) self.assertEqual( self.storedfile_ref_prop_instance.value[0].name, self.filename) def test_upload_file_to_already_filled_in_stored_reference_property(self): self.storedfile_ref_prop_instance.value = [ self.stored_file, self.stored_file_2] self.storedfile_ref_prop_instance.upload(self.upload_path) self.assertEqual(len(self.storedfile_ref_prop_instance.value), 3) for stored_file in self.storedfile_ref_prop_instance.value: self.assertIsInstance(stored_file, StoredFile) self.assertEqual( self.storedfile_ref_prop_instance.value[2].name, self.filename)
class TestStoredFileReferenceProperty(TestBetamax): def setUp(self): pass def tearDown(self): pass def test_create(self): pass def test_value_model(self): pass def test_no_value_model(self): pass def test_value_instance(self): pass def test_no_value_instance(self): pass def test_multiple_values(self): pass def test_edit_property_model_description(self): pass def test_edit_property_model_validators(self): pass def test_clear_stored_files_from_value(self): pass def test_filename_of_stored_reference_property_multiple_stored_files(self): pass def test_filename_of_stored_reference_property_one_stored_file(self): pass def test_filename_of_stored_reference_property_no_stored_file(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as stored_files " "download links have time limited access keys in the uri", ) def test_download_files_from_stored_reference_property(self): pass def test_upload_file_to_empty_value_stored_reference_property(self): pass def test_upload_file_to_already_filled_in_stored_reference_property(self): pass
19
0
10
0
10
0
1
0
1
12
9
0
17
11
17
92
194
21
173
38
150
0
91
31
73
6
3
2
23
140,692
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/models/test_property_attachment.py
tests.models.test_property_attachment.TestAttachment
class TestAttachment(TestBetamax): test_dict = {"a": 1, "b": 3} project_root = os.path.dirname( os.path.dirname(os.path.dirname( os.path.abspath(__file__)).replace("\\", "/")) ) def setUp(self): super().setUp() self.test_assets_dir = os.path.dirname( os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") ) self.property_name = "Plot Attachment" self.root_model = self.project.model(name="Product") self.part_model = self.root_model.add_model( name="__Testing attachments", multiplicity=Multiplicity.ONE_MANY ) self.property_model = self.part_model.add_property( name=self.property_name, property_type=PropertyType.ATTACHMENT_VALUE ) # type: AttachmentProperty self.property = self.part_model.instance().property( name=self.property_name ) # type: AttachmentProperty def tearDown(self): self.part_model.delete() super().tearDown() def test_retrieve_attachment(self): data = ("data.json", json.dumps(self.test_dict), "application/json") self.property._upload(data) r = self.property.json_load() self.assertDictEqual(r, self.test_dict) def test_retrieve_value(self): self.assertIsNone(self.property.value) self.property.upload(self.project_root + "/requirements.txt") self.assertIsNotNone(self.property.value) def test_set_value_none(self): self.property.value = None self.assertFalse(self.property.has_value()) def test_set_value_not_a_path(self): with self.assertRaises(FileNotFoundError): self.property.value = "String must be a filepath" def test_upload(self): self.property.upload(self.project_root + "/requirements.txt") requirements = self.project_root + "/requirements.txt" self.property.upload(requirements) # 1.11.1 def test_clear_an_attachment_property(self): # setUp self.property.upload(self.project_root + "/requirements.txt") # testing self.assertTrue(self.property.has_value()) self.property.clear() self.assertIsNone(self.property.value) self.assertIsNone(self.property._value) def test_retrieve_filename_from_value(self): # setUp self.property.upload(self.project_root + "/requirements.txt") # testing self.assertEqual(self.property.filename, "requirements.txt") def test_has_value_true(self): # setUp self.property.upload(self.project_root + "/requirements.txt") # testing self.assertTrue(self.property.has_value()) def test_has_value_false(self): self.assertFalse(self.property.has_value()) def test_add_with_properties(self): # setUp self.new_wheel = self.root_model.instance().add_with_properties( self.part_model, "new part", update_dict={self.property_name: self.project_root + "/requirements.txt"}, ) @unittest.skip("Saving the image cannot be executed when recording cassettes") def test_save_as_attachment(self): upload_path = os.path.join( self.test_assets_dir, "files", "test_upload_image_to_attachment_property", "test_upload_image.png", ) self.property.upload(upload_path) with temp_chdir() as target_dir: filepath = os.path.join(target_dir, "image_sqxs.png") self.property.save_as(filename=filepath, size=ImageSize.SQXS) path = os.path.join(target_dir, filepath) image_sqxs = Image.open(path) self.assertEqual(image_sqxs.width, 100) self.assertEqual(image_sqxs.height, 100)
class TestAttachment(TestBetamax): def setUp(self): pass def tearDown(self): pass def test_retrieve_attachment(self): pass def test_retrieve_value(self): pass def test_set_value_none(self): pass def test_set_value_not_a_path(self): pass def test_upload(self): pass def test_clear_an_attachment_property(self): pass def test_retrieve_filename_from_value(self): pass def test_has_value_true(self): pass def test_has_value_false(self): pass def test_add_with_properties(self): pass @unittest.skip("Saving the image cannot be executed when recording cassettes") def test_save_as_attachment(self): pass
15
0
7
1
6
1
1
0.13
1
5
3
0
13
7
13
88
113
26
79
32
64
10
59
30
45
1
3
1
13
140,693
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.AlwaysAllowValidator
class AlwaysAllowValidator(PropertyValidator): """ An always allow Validator. Will always return True. """ vtype = PropertyVTypes.ALWAYSALLOW def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: """Process the inner logic of the validator. The validation results are returned as tuple (boolean (true/false), reasontext) """ return True, "Always True"
class AlwaysAllowValidator(PropertyValidator): ''' An always allow Validator. Will always return True. ''' def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: '''Process the inner logic of the validator. The validation results are returned as tuple (boolean (true/false), reasontext) ''' pass
2
2
6
1
2
3
1
1.75
1
3
0
0
1
0
1
14
15
4
4
3
2
7
4
3
2
1
2
0
1
140,694
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.BooleanFieldValidator
class BooleanFieldValidator(PropertyValidator): """A boolean field validator. This is a stub implementation. Should validate if a value is either 'truthy' or 'falsy'. """ vtype = PropertyVTypes.BOOLEANFIELD
class BooleanFieldValidator(PropertyValidator): '''A boolean field validator. This is a stub implementation. Should validate if a value is either 'truthy' or 'falsy'. ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
13
7
2
2
2
1
3
2
2
1
0
2
0
0
140,695
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.EmailValidator
class EmailValidator(RegexStringValidator): """ A email string validator. :cvar pattern: the email regex pattern to which the provided value is matched against. """ pattern = EMAIL_REGEX_PATTERN def __init__(self, json=None, **kwargs): """Construct an email string validator. :param json: (optional) dict (json) object to construct the object from :type json: dict :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict """ super().__init__(json=json, pattern=self.pattern, **kwargs)
class EmailValidator(RegexStringValidator): ''' A email string validator. :cvar pattern: the email regex pattern to which the provided value is matched against. ''' def __init__(self, json=None, **kwargs): '''Construct an email string validator. :param json: (optional) dict (json) object to construct the object from :type json: dict :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict ''' pass
2
2
9
1
2
6
1
2.5
1
1
0
0
1
0
1
16
18
4
4
3
2
10
4
3
2
1
3
0
1
140,696
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.EvenNumberValidator
class EvenNumberValidator(PropertyValidator): """An even number validator that validates `True` when the number is even. Even numbers are scalar numbers which can be diveded by 2 and return a scalar. Floating point numbers are converted to integer first. So `int(4.5)` = 4. .. versionadded:: 2.2 Example ------- >>> validator = EvenNumberValidator() >>> validator.is_valid(4) True >>> validator.is_valid(4.5) # float is converted to integer first True """ vtype = PropertyVTypes.EVENNUMBER def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: if value is None: self._validation_result, self.validation_reason = None, "No reason" return self._validation_result, self._validation_reason if not isinstance(value, (int, float)): self._validation_result, self.validation_reason = ( False, "Value should be an integer, or float (floored)", ) return self._validation_result, self._validation_reason basereason = f"Value '{value}' should be an even number" self._validation_result = int(value) % 2 < self.accuracy if self._validation_result: self._validation_reason = basereason.replace("should be", "is") return self._validation_result, self._validation_reason else: self._validation_reason = basereason return self._validation_result, self._validation_reason
class EvenNumberValidator(PropertyValidator): '''An even number validator that validates `True` when the number is even. Even numbers are scalar numbers which can be diveded by 2 and return a scalar. Floating point numbers are converted to integer first. So `int(4.5)` = 4. .. versionadded:: 2.2 Example ------- >>> validator = EvenNumberValidator() >>> validator.is_valid(4) True >>> validator.is_valid(4.5) # float is converted to integer first True ''' def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: pass
2
1
20
2
18
0
4
0.6
1
5
0
0
1
3
1
14
40
8
20
6
18
12
16
6
14
4
2
1
4
140,697
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.FileExtensionValidator
class FileExtensionValidator(PropertyValidator): """A file extension Validator. It checks the value of the property attachment against a list of acceptable mime types or file extensions. Example ------- >>> validator = FileExtensionValidator(accept=[".png", ".jpg"]) >>> validator.is_valid("picture.jpg") True >>> validator.is_valid("document.pdf") False >>> validator.is_valid("attachments/12345678-1234-5678-1234-567812345678/some_file.txt") False >>> validator = FileExtensionValidator(accept=["application/pdf", ... "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]) >>> validator.is_valid("document.pdf") True >>> validator.is_valid("comma-separated-values.csv") False >>> validator.is_valid("attachments/12345678-1234-5678-1234-567812345678/modern_excel.xlsx") True """ vtype = PropertyVTypes.FILEEXTENSION jsonschema = fileextensionvalidator_schema mimetype_regex = r"^[-\w.]+/[-\w.\*]+$" def __init__( self, json: Optional[Dict] = None, accept: Optional[Union[str, List[str]]] = None, **kwargs, ): """Construct a file extension validator. :param json: (optional) dict (json) object to construct the object from :type json: Optional[Dict] :param accept: (optional) list of mimetypes or file extensions (including a `.`, eg `.csv`, `.pdf`) :type accept: Optional[List[Text]] :param kwargs: (optional) additional kwargs to pass down """ super().__init__(json=json, **kwargs) if accept is not None: if isinstance(accept, str): self._config["accept"] = accept.split(",") elif isinstance(accept, List): self._config["accept"] = accept else: raise ValueError( "`accept` should be a commaseparated list or a list of strings." ) self.accept = self._config.get("accept", None) self._accepted_mimetypes = self._convert_to_mimetypes(self.accept) def _convert_to_mimetypes(self, accept: List[str]) -> Optional[List[str]]: """ Convert accept array to array of mimetypes. 1. convert accept list to array of mimetypes 2. convert aggregator (if inside mime_types_defaults) to list of mimetypes :param accept: list of mimetypes or extensions :type accept: List[Text] :return: array of mimetypes: :rtype: List[Text] """ if accept is None: return None marray = [] for item in accept: # check if the item in the accept array is a mimetype on its own. if re.match(self.mimetype_regex, item): if item in predefined_mimes: marray.extend(predefined_mimes.get(item)) else: marray.append(item) else: # we assume this is an extension. # we can only guess a url, we make a url like: "file.ext" to check. fake_filename = ( f"file{item}" if item.startswith(".") else f"file.{item}" ) # do guess guess, _ = mimetypes.guess_type(fake_filename) marray.append(guess) if guess is not None else print(guess) return marray def _logic( self, value: Optional[str] = None ) -> Tuple[Optional[bool], Optional[str]]: """Based on the filename of the property (value), the type is checked. 1. convert filename to mimetype 3. check if the filename is inside the array of mimetypes. self._accepted_mimetypes """ if value is None: return None, "No reason" basereason = f"Value '{value}' should match the mime types '{self.accept}'" guessed_type, _ = mimetypes.guess_type(value) if guessed_type is None: return False, f"Could not determine the mimetype of '{value}'" elif guessed_type in self._accepted_mimetypes: return True, basereason.replace("match", "matches") return False, basereason
class FileExtensionValidator(PropertyValidator): '''A file extension Validator. It checks the value of the property attachment against a list of acceptable mime types or file extensions. Example ------- >>> validator = FileExtensionValidator(accept=[".png", ".jpg"]) >>> validator.is_valid("picture.jpg") True >>> validator.is_valid("document.pdf") False >>> validator.is_valid("attachments/12345678-1234-5678-1234-567812345678/some_file.txt") False >>> validator = FileExtensionValidator(accept=["application/pdf", ... "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]) >>> validator.is_valid("document.pdf") True >>> validator.is_valid("comma-separated-values.csv") False >>> validator.is_valid("attachments/12345678-1234-5678-1234-567812345678/modern_excel.xlsx") True ''' def __init__( self, json: Optional[Dict] = None, accept: Optional[Union[str, List[str]]] = None, **kwargs, ): '''Construct a file extension validator. :param json: (optional) dict (json) object to construct the object from :type json: Optional[Dict] :param accept: (optional) list of mimetypes or file extensions (including a `.`, eg `.csv`, `.pdf`) :type accept: Optional[List[Text]] :param kwargs: (optional) additional kwargs to pass down ''' pass def _convert_to_mimetypes(self, accept: List[str]) -> Optional[List[str]]: ''' Convert accept array to array of mimetypes. 1. convert accept list to array of mimetypes 2. convert aggregator (if inside mime_types_defaults) to list of mimetypes :param accept: list of mimetypes or extensions :type accept: List[Text] :return: array of mimetypes: :rtype: List[Text] ''' pass def _logic( self, value: Optional[str] = None ) -> Tuple[Optional[bool], Optional[str]]: '''Based on the filename of the property (value), the type is checked. 1. convert filename to mimetype 3. check if the filename is inside the array of mimetypes. self._accepted_mimetypes ''' pass
4
4
27
4
16
8
5
0.86
1
4
0
0
3
2
3
16
114
19
51
22
40
44
35
15
31
7
2
3
15
140,698
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.FileSizeValidator
class FileSizeValidator(PropertyValidator): """A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar max_size: maximum size to check, in MB :type max_size: Union[int,float] Example ------- >>> validator = FileSizeValidator(max_size=100) >>> validator.is_valid(100) True >>> validator.is_valid(-1) False >>> validator.is_valid("attachments/12345678-1234-5678-1234-567812345678/some_file.txt") True >>> validator.get_reason() We determine the filesize of 'some_file.txt' to be valid. We cannot check it at this end. """ vtype = PropertyVTypes.FILESIZE jsonschema = filesizevalidator_schema def __init__( self, json: Optional[Dict] = None, max_size: Optional[Union[int, float]] = None, **kwargs, ): """Construct a file size validator. :param json: (optional) dict (json) object to construct the object from :type json: Optional[Dict] :param max_size: (optional) number that counts as maximum size of the file, in MB :type accept: Optional[Union[int,float]] :param kwargs: (optional) additional kwargs to pass down """ super().__init__(json=json, **kwargs) if max_size is not None: if isinstance(max_size, (int, float)): self._config["maxSize"] = int(max_size) * 1024**2 # converting from bytes to MB else: raise ValueError("`max_size` should be a number.") self.max_size = self._config.get("maxSize", float("inf")) def _logic( self, value: Optional[Union[int, float]] = None ) -> Tuple[Optional[bool], Optional[str]]: """Based on a filesize (numeric) or filepath of the property (value), the filesize is checked.""" if value is None: return None, "No reason" basereason = f"Value '{value}' should be of a size less then '{self.max_size}'" if isinstance(value, (int, float)): if int(value) <= self.max_size and int(value) >= 0: return True, basereason.replace("should", "is") else: return False, basereason return ( True, f"We determine the filesize of '{value}' to be valid. We cannot check it at this end.", )
class FileSizeValidator(PropertyValidator): '''A file size Validator. The actual size of the file cannot be checked in pykechain without downloading this from the server, hence when the validator is used inside an attachment property, the validator returns always being valid. :ivar max_size: maximum size to check, in MB :type max_size: Union[int,float] Example ------- >>> validator = FileSizeValidator(max_size=100) >>> validator.is_valid(100) True >>> validator.is_valid(-1) False >>> validator.is_valid("attachments/12345678-1234-5678-1234-567812345678/some_file.txt") True >>> validator.get_reason() We determine the filesize of 'some_file.txt' to be valid. We cannot check it at this end. ''' def __init__( self, json: Optional[Dict] = None, max_size: Optional[Union[int, float]] = None, **kwargs, ): '''Construct a file size validator. :param json: (optional) dict (json) object to construct the object from :type json: Optional[Dict] :param max_size: (optional) number that counts as maximum size of the file, in MB :type accept: Optional[Union[int,float]] :param kwargs: (optional) additional kwargs to pass down ''' pass def _logic( self, value: Optional[Union[int, float]] = None ) -> Tuple[Optional[bool], Optional[str]]: '''Based on a filesize (numeric) or filepath of the property (value), the filesize is checked.''' pass
3
3
20
2
14
5
4
0.84
1
6
0
0
2
1
2
15
67
11
31
14
21
26
19
7
16
4
2
2
7
140,699
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.NumericRangeValidator
class NumericRangeValidator(PropertyValidator): """ A numeric range validator, which validates a number between a range. The range validates positively upto and **including** the minvalue and maxvalue. An added ability is the check if the number conforms to a step within that range. The validation checks for both integer and floats. The stepsize is only enforced when the :attr:`enforce_stepsize` is set to `True`. This enforcement is accurate to an accuracy set in the :const:`.accuracy` (normally set to be 1E-6). .. versionadded:: 2.2 :ivar minvalue: minimum value of the range :type minvalue: float or int :ivar maxvalue: maximum value of the range :type maxvalue: float or int :ivar stepsize: stepsize :type stepsize: float or int :ivar enforce_stepsize: flag to ensure that the stepsize is enforced :type enforce_stepsize: bool Examples -------- >>> validator = NumericRangeValidator(minvalue=0, maxvalue=50) >>> validator.is_valid(42) True >>> validator.is_valid(50) True >>> validator.is_valid(50.0001) False >>> validator.is_valid(-1) False >>> validator.get_reason() Value '-1' should be between 0 and 50 >>> stepper = NumericRangeValidator(stepsize=1000, enforce_stepsize=True) >>> stepper.is_valid(2000) True """ vtype = PropertyVTypes.NUMERICRANGE def __init__( self, json=None, minvalue=None, maxvalue=None, stepsize=None, enforce_stepsize=None, **kwargs, ): """Construct the numeric range validator.""" super().__init__(json=json, **kwargs) if minvalue is not None: self._config["minvalue"] = minvalue if maxvalue is not None: self._config["maxvalue"] = maxvalue if stepsize is not None: self._config["stepsize"] = stepsize if enforce_stepsize is not None: self._config["enforce_stepsize"] = enforce_stepsize if self._config.get("minvalue") is None: self.minvalue = float("-inf") else: self.minvalue = self._config.get("minvalue") if self._config.get("maxvalue") is None: self.maxvalue = float("inf") else: self.maxvalue = self._config.get("maxvalue") self.stepsize = self._config.get("stepsize", None) self.enforce_stepsize = self._config.get("enforce_stepsize", None) if self.minvalue > self.maxvalue: raise Exception( "The minvalue ({}) should be smaller than the maxvalue ({}) of the numeric " "range validation".format(self.minvalue, self.maxvalue) ) if self.enforce_stepsize and self.stepsize is None: raise Exception("The stepsize should be provided when enforcing stepsize") def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: basereason = ( f"Value '{value}' should be between {self.minvalue} and {self.maxvalue}" ) self._validation_result, self._validation_reason = None, "No reason" if value is not None: self._validation_result = value >= self.minvalue and value <= self.maxvalue if not self._validation_result: self._validation_reason = basereason else: self._validation_reason = basereason.replace("should be", "is") if self.stepsize != 1 and self.enforce_stepsize: # to account also for floating point stepsize checks: https://stackoverflow.com/a/30445184/246235 if self.minvalue == float("-inf"): self._validation_result = ( abs(value / self.stepsize - round(value / self.stepsize)) < self.accuracy ) else: self._validation_result = ( abs( (value - self.minvalue) / self.stepsize - round((value - self.minvalue) / self.stepsize) ) < self.accuracy ) if not self._validation_result: self._validation_reason = ( "Value '{}' is not in alignment with a stepsize of {}".format( value, self.stepsize ) ) return self._validation_result, self._validation_reason
class NumericRangeValidator(PropertyValidator): ''' A numeric range validator, which validates a number between a range. The range validates positively upto and **including** the minvalue and maxvalue. An added ability is the check if the number conforms to a step within that range. The validation checks for both integer and floats. The stepsize is only enforced when the :attr:`enforce_stepsize` is set to `True`. This enforcement is accurate to an accuracy set in the :const:`.accuracy` (normally set to be 1E-6). .. versionadded:: 2.2 :ivar minvalue: minimum value of the range :type minvalue: float or int :ivar maxvalue: maximum value of the range :type maxvalue: float or int :ivar stepsize: stepsize :type stepsize: float or int :ivar enforce_stepsize: flag to ensure that the stepsize is enforced :type enforce_stepsize: bool Examples -------- >>> validator = NumericRangeValidator(minvalue=0, maxvalue=50) >>> validator.is_valid(42) True >>> validator.is_valid(50) True >>> validator.is_valid(50.0001) False >>> validator.is_valid(-1) False >>> validator.get_reason() Value '-1' should be between 0 and 50 >>> stepper = NumericRangeValidator(stepsize=1000, enforce_stepsize=True) >>> stepper.is_valid(2000) True ''' def __init__( self, json=None, minvalue=None, maxvalue=None, stepsize=None, enforce_stepsize=None, **kwargs, ): '''Construct the numeric range validator.''' pass def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: pass
3
2
39
4
34
1
8
0.51
1
6
0
0
2
6
2
15
122
18
69
18
58
35
39
10
36
9
2
2
15
140,700
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.OddNumberValidator
class OddNumberValidator(PropertyValidator): """A odd number validator that validates `True` when the number is odd. Example ------- >>> validator = OddNumberValidator() >>> validator.is_valid(3) True >>> validator.is_valid(3.5) # float is converted to integer first True """ vtype = PropertyVTypes.ODDNUMBER def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: if value is None: self._validation_result, self.validation_reason = None, "No reason" return self._validation_result, self._validation_reason if not isinstance(value, (int, float)): self._validation_result, self.validation_reason = ( False, "Value should be an integer, or float (floored)", ) return self._validation_result, self._validation_reason basereason = f"Value '{value}' should be a odd number" self._validation_result = int(value) % 2 > self.accuracy if self._validation_result: self._validation_reason = basereason.replace("should be", "is") return self._validation_result, self._validation_reason else: self._validation_reason = basereason return self._validation_result, self._validation_reason
class OddNumberValidator(PropertyValidator): '''A odd number validator that validates `True` when the number is odd. Example ------- >>> validator = OddNumberValidator() >>> validator.is_valid(3) True >>> validator.is_valid(3.5) # float is converted to integer first True ''' def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: pass
2
1
20
2
18
0
4
0.45
1
5
0
0
1
3
1
14
35
6
20
6
18
9
16
6
14
4
2
1
4
140,701
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/models/test_property_selectlist.py
tests.models.test_property_selectlist.SelectListBaseTests.Tests
class Tests(TestBetamax): """Tests for the select list properties.""" PROPERTY_TYPE = None OPTIONS = ["1", "3.14", "text"] def setUp(self): super().setUp() self.select_model = self.project.model("Bike").add_property( name=self.PROPERTY_TYPE, property_type=self.PROPERTY_TYPE, options={"value_choices": ["1", "3.14", "text"]}, ) self.select = self.project.part( "Bike").property(self.PROPERTY_TYPE) def tearDown(self): self.select_model.delete() super().tearDown() def test_get_options_list(self): self.assertTrue(hasattr(self.select_model, "options")) self.assertIsInstance(self.select_model.options, list) for item in self.select_model.options: self.assertTrue(type(item), str) def test_set_options_list(self): # setUp current_options_list = [1, 3.14, "text"] new_options_list = ["some", "new", 4, "options"] self.select_model.options = new_options_list # testing self.assertListEqual( self.select_model.options, list(map(str, new_options_list)) ) # teardown self.select_model.options = current_options_list def test_illegal_options_are_not_set(self): """Test for several illegal lists to be set""" with self.assertRaises(IllegalArgumentError): # not a list self.select_model.options = 1 with self.assertRaises(IllegalArgumentError): self.select_model.options = None with self.assertRaises(IllegalArgumentError): # set self.select_model.options = {1, 2, 3} with self.assertRaises(IllegalArgumentError): # dict self.select_model.options = {"a": 1, "b": 2, "c": 3} with self.assertRaises(IllegalArgumentError): # tuple self.select_model.options = (1,) def test_fail_to_set_options_on_instance(self): """Test settings options on a property instance, only models are allowed options to be set""" self.assertTrue(hasattr(self.select, "options")) with self.assertRaises(IllegalArgumentError): self.select.options = [1, 3.14] def test_integrity_options_dict(self): # setUp original_options_dict = dict(self.select_model._options) self.select_model.options = list(self.select_model.options) # testing testing_options_dict = self.select_model._options self.assertEqual(original_options_dict, testing_options_dict)
class Tests(TestBetamax): '''Tests for the select list properties.''' def setUp(self): pass def tearDown(self): pass def test_get_options_list(self): pass def test_set_options_list(self): pass def test_illegal_options_are_not_set(self): '''Test for several illegal lists to be set''' pass def test_fail_to_set_options_on_instance(self): '''Test settings options on a property instance, only models are allowed options to be set''' pass def test_integrity_options_dict(self): pass
8
3
9
1
6
2
1
0.26
1
7
1
2
7
2
7
82
76
17
47
17
39
12
41
17
33
2
3
1
8
140,702
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.RegexStringValidator
class RegexStringValidator(PropertyValidator): """ A regular expression string validator. With a configured regex pattern, a string value is compared and matched against this pattern. If there is a positive match, the validator validates correctly. For more information on constructing regex strings, see the `python documentation`_, `regex101.com`_, or `regexr.com`_. .. versionadded:: 2.2 :ivar pattern: the regex pattern to which the provided value is matched against. Example ------- >>> validator = RegexStringValidator(pattern=r"Yes|Y|1|Ok") >>> validator.is_valid("Yes") True >>> validator.is_valid("No") False .. _python documentation: https://docs.python.org/2/library/re.html .. _regex101.com: https://regex101.com/ .. _regexr.com: https://regexr.com/ """ vtype = PropertyVTypes.REGEXSTRING def __init__(self, json=None, pattern=None, **kwargs): """Construct an regex string validator. If no pattern is provided than the regexstring `'.+'` will be used, which matches all provided text with at least a single character. Does not match `''` (empty string). :param json: (optional) dict (json) object to construct the object from :type json: dict :param pattern: (optional) valid regex string, defaults to r'.+' which matches all text. :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict """ super().__init__(json=json, **kwargs) if pattern is not None: self._config["pattern"] = pattern self.pattern = self._config.get("pattern", r".+") self._re = re.compile(self.pattern) def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: if value is None: self._validation_result, self.validation_reason = None, "No reason" return self._validation_result, self._validation_reason basereason = f"Value '{value}' should match the regex pattern '{self.pattern}'" self._validation_result = re.match(self._re, value) is not None if not self._validation_result: self._validation_reason = basereason else: self._validation_reason = basereason.replace("should match", "matches") return self._validation_result, self._validation_reason
class RegexStringValidator(PropertyValidator): ''' A regular expression string validator. With a configured regex pattern, a string value is compared and matched against this pattern. If there is a positive match, the validator validates correctly. For more information on constructing regex strings, see the `python documentation`_, `regex101.com`_, or `regexr.com`_. .. versionadded:: 2.2 :ivar pattern: the regex pattern to which the provided value is matched against. Example ------- >>> validator = RegexStringValidator(pattern=r"Yes|Y|1|Ok") >>> validator.is_valid("Yes") True >>> validator.is_valid("No") False .. _python documentation: https://docs.python.org/2/library/re.html .. _regex101.com: https://regex101.com/ .. _regexr.com: https://regexr.com/ ''' def __init__(self, json=None, pattern=None, **kwargs): '''Construct an regex string validator. If no pattern is provided than the regexstring `'.+'` will be used, which matches all provided text with at least a single character. Does not match `''` (empty string). :param json: (optional) dict (json) object to construct the object from :type json: dict :param pattern: (optional) valid regex string, defaults to r'.+' which matches all text. :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict ''' pass def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: pass
3
2
17
4
9
5
3
1.53
1
4
0
1
2
5
2
15
65
17
19
9
16
29
18
9
15
3
2
1
5
140,703
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.SingleReferenceValidator
class SingleReferenceValidator(PropertyValidator): """A single reference validator, ensuring that only a single reference is selected. .. versionadded:: 2.2 """ vtype = PropertyVTypes.SINGLEREFERENCE def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: if value is None: self._validation_result, self.validation_reason = None, "No reason" return self._validation_result, self._validation_reason if not isinstance(value, (list, tuple, set)): self._validation_result, self.validation_reason = ( False, "Value should be a list, tuple or set", ) return self._validation_result, self._validation_reason self._validation_result = len(value) == 1 or len(value) == 0 if self._validation_result: self._validation_reason = "A single or no value is selected" return self._validation_result, self._validation_reason else: self._validation_reason = "More than a single instance is selected" return self._validation_result, self._validation_reason
class SingleReferenceValidator(PropertyValidator): '''A single reference validator, ensuring that only a single reference is selected. .. versionadded:: 2.2 ''' def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: pass
2
1
18
1
17
0
4
0.16
1
6
0
0
1
3
1
14
26
4
19
5
17
3
15
5
13
4
2
1
4
140,704
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators_base.py
pykechain.models.validators.validators_base.PropertyValidator
class PropertyValidator(BaseValidator): """Base class for all property validators. If json is provided, the validator is instantiated based on that json. .. versionadded:: 2.2 :cvar vtype: Validator type, one of :class:`pykechain.enums.PropertyVTypes` :type vtype: basestring :cvar jsonschema: jsonschema to validate the structure of the json representation of the effect against :type jsonschema: dict """ vtype: str = PropertyVTypes.NONEVALIDATOR jsonschema = validator_jsonschema_stub def __init__(self, json=None, *args, **kwargs): """Construct a Property Validator.""" super().__init__(json=json, *args, **kwargs) self._json = json or {"vtype": self.vtype, "config": {}} self._validation_result = None self._validation_reason = None self._value = None if self._config.get("on_valid"): self.on_valid = self._parse_effects(self._config.get("on_valid")) else: self.on_valid = kwargs.get("on_valid") or [] if self._config.get("on_invalid"): self.on_invalid = self._parse_effects(self._config.get("on_invalid")) else: self.on_invalid = kwargs.get("on_invalid") or [] @staticmethod def _parse_effects(effects_json: Optional[Dict] = None) -> Any: """Parse multiple effects from an effects(list) json.""" if isinstance(effects_json, list): return [ValidatorEffect.parse(effect) for effect in effects_json] elif isinstance(effects_json, dict): return ValidatorEffect.parse(effects_json) else: raise Exception( "The provided json, should be a list of valid effects, " "or a single effect. Got '{}'".format(effects_json) ) @classmethod def parse(cls, json: Dict) -> "PropertyValidator": """Parse a json dict and return the correct subclass of :class:`PropertyValidator`. It uses the 'effect' key to determine which :class:`PropertyValidator` to instantiate. Please refer to :class:`pykechain.enums.PropertyVTypes` for the supported effects. :param json: dictionary containing the specific keys to parse into a :class:`PropertyValidator` :type json: dict :returns: the instantiated subclass of :class:`PropertyValidator` :rtype: :class:`PropertyValidator` or subclass thereof """ if "vtype" in json: vtype = json.get("vtype") if vtype not in PropertyVTypes.values(): raise Exception(f"Validator unknown, incorrect json: '{json}'") from pykechain.models.validators import validators vtype_implementation_classname = f"{vtype[0].upper()}{vtype[1:]}" # type: ignore if hasattr(validators, vtype_implementation_classname): return getattr(validators, vtype_implementation_classname)(json=json) else: raise Exception("unknown vtype in json") raise Exception(f"Validator unknown, incorrect json: '{json}'") def as_json(self) -> Dict: """JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict """ new_json = dict(vtype=self.vtype, config=self._config) if self.on_valid: new_json["config"]["on_valid"] = [ effect.as_json() for effect in self.on_valid ] if self.on_invalid: new_json["config"]["on_invalid"] = [ effect.as_json() for effect in self.on_invalid ] self._json = new_json return self._json def __call__(self, value: Any) -> bool: """Trigger the validation of the validator. The reason may retrieved by the :func:`get_reason()` method. :param value: The value to check against :type value: Any :return: bool """ self._validation_result, self._validation_reason = self._logic(value) if self._validation_result is not None and self._validation_result: for effect in self.on_valid: effect() elif self._validation_result is not None and not self._validation_result: for effect in self.on_invalid: effect() return self._validation_result def is_valid(self, value: Any) -> bool: """Check if the validation against a value, returns a boolean. This is the logical inverse of the :func:`is_invalid()` method. :param value: The value to check against :type value: Any :return: True if valid, False if invalid :rtype: bool """ return self.__call__(value) def is_invalid(self, value: Any) -> bool: """Check if the validation against a value, returns a boolean. This is the logical inverse of the :func:`is_valid()` method. :param value: The value to check against :type value: Any :return: True if INvalid, False if valid :rtype: bool """ return not self.is_valid(value) def get_reason(self) -> AnyStr: """Retrieve the reason of the (in)validation. :return: reason text :rtype: basestring """ return self._validation_reason def _logic(self, value: Optional[Any] = None) -> Tuple[Optional[bool], str]: """Process the inner logic of the validator. The validation results are returned as tuple (boolean (true/false), reasontext) """ self._validation_result, self._validation_reason = None, "No reason" return self._validation_result, self._validation_reason
class PropertyValidator(BaseValidator): '''Base class for all property validators. If json is provided, the validator is instantiated based on that json. .. versionadded:: 2.2 :cvar vtype: Validator type, one of :class:`pykechain.enums.PropertyVTypes` :type vtype: basestring :cvar jsonschema: jsonschema to validate the structure of the json representation of the effect against :type jsonschema: dict ''' def __init__(self, json=None, *args, **kwargs): '''Construct a Property Validator.''' pass @staticmethod def _parse_effects(effects_json: Optional[Dict] = None) -> Any: '''Parse multiple effects from an effects(list) json.''' pass @classmethod def parse(cls, json: Dict) -> "PropertyValidator": '''Parse a json dict and return the correct subclass of :class:`PropertyValidator`. It uses the 'effect' key to determine which :class:`PropertyValidator` to instantiate. Please refer to :class:`pykechain.enums.PropertyVTypes` for the supported effects. :param json: dictionary containing the specific keys to parse into a :class:`PropertyValidator` :type json: dict :returns: the instantiated subclass of :class:`PropertyValidator` :rtype: :class:`PropertyValidator` or subclass thereof ''' pass def as_json(self) -> Dict: '''JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict ''' pass def __call__(self, value: Any) -> bool: '''Trigger the validation of the validator. The reason may retrieved by the :func:`get_reason()` method. :param value: The value to check against :type value: Any :return: bool ''' pass def is_valid(self, value: Any) -> bool: '''Check if the validation against a value, returns a boolean. This is the logical inverse of the :func:`is_invalid()` method. :param value: The value to check against :type value: Any :return: True if valid, False if invalid :rtype: bool ''' pass def is_invalid(self, value: Any) -> bool: '''Check if the validation against a value, returns a boolean. This is the logical inverse of the :func:`is_valid()` method. :param value: The value to check against :type value: Any :return: True if INvalid, False if valid :rtype: bool ''' pass def get_reason(self) -> AnyStr: '''Retrieve the reason of the (in)validation. :return: reason text :rtype: basestring ''' pass def _logic(self, value: Optional[Any] = None) -> Tuple[Optional[bool], str]: '''Process the inner logic of the validator. The validation results are returned as tuple (boolean (true/false), reasontext) ''' pass
12
10
14
2
7
5
2
0.7
1
9
2
10
7
6
9
13
152
32
71
25
58
50
56
23
45
5
1
2
22
140,705
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators_base.py
pykechain.models.validators.validators_base.ValidatorEffect
class ValidatorEffect(BaseValidator): """ A Validator Effect. This is an effect that can be associated with the :attr:`PropertyValidator.on_valid` or :attr:`PropertyValidator.on_invalid`. The effects associated are called based on the results of the validation of the :class:`PropertyValidator`. .. versionadded:: 2.2 :cvar effect: Effect type, one of :class:`pykechain.enums.ValidatorEffectTypes` :cvar jsonschema: jsonschema to validate the structure of the json representation of the effect against """ effect = ValidatorEffectTypes.NONE_EFFECT jsonschema = effects_jsonschema_stub def __init__(self, json=None, *args, **kwargs): """Construct a Validator Effect.""" super().__init__(json=json, *args, **kwargs) self._json = json or {"effect": self.effect, "config": {}} def __call__(self, **kwargs): """Execute the effect.""" return True @classmethod def parse(cls, json: Dict) -> "ValidatorEffect": """Parse a json dict and return the correct subclass of :class:`ValidatorEffect`. It uses the 'effect' key to determine which :class:`ValidatorEffect` to instantiate. Please refer to :class:`enums.ValidatorEffectTypes` for the supported effects. :param json: dictionary containing the specific keys to parse into a :class:`ValidatorEffect` :type json: dict :returns: the instantiated subclass of :class:`ValidatorEffect` :rtype: :class:`ValidatorEffect` or subclass """ effect = json.get("effect") if effect: from pykechain.models.validators import effects effect_implementation_classname = effect[0].upper() + effect[1:] if hasattr(effects, effect_implementation_classname): return getattr(effects, effect_implementation_classname)(json=json) else: raise Exception("unknown effect in json") raise Exception(f"Effect unknown, incorrect json: '{json}'") def as_json(self) -> Dict: """JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict """ self._json = dict(effect=self.effect, config=self._config) return self._json
class ValidatorEffect(BaseValidator): ''' A Validator Effect. This is an effect that can be associated with the :attr:`PropertyValidator.on_valid` or :attr:`PropertyValidator.on_invalid`. The effects associated are called based on the results of the validation of the :class:`PropertyValidator`. .. versionadded:: 2.2 :cvar effect: Effect type, one of :class:`pykechain.enums.ValidatorEffectTypes` :cvar jsonschema: jsonschema to validate the structure of the json representation of the effect against ''' def __init__(self, json=None, *args, **kwargs): '''Construct a Validator Effect.''' pass def __call__(self, **kwargs): '''Execute the effect.''' pass @classmethod def parse(cls, json: Dict) -> "ValidatorEffect": '''Parse a json dict and return the correct subclass of :class:`ValidatorEffect`. It uses the 'effect' key to determine which :class:`ValidatorEffect` to instantiate. Please refer to :class:`enums.ValidatorEffectTypes` for the supported effects. :param json: dictionary containing the specific keys to parse into a :class:`ValidatorEffect` :type json: dict :returns: the instantiated subclass of :class:`ValidatorEffect` :rtype: :class:`ValidatorEffect` or subclass ''' pass def as_json(self) -> Dict: '''JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict ''' pass
6
5
9
1
5
4
2
1.05
1
3
0
4
3
1
4
8
57
12
22
12
15
23
20
11
14
3
1
2
6
140,706
KE-works/pykechain
KE-works_pykechain/pykechain/models/value_filter.py
pykechain.models.value_filter.PropertyValueFilter
class PropertyValueFilter(BaseFilter): """ Property value filter, used for Part reference properties and filtered grid widgets. :ivar id: property model UUID :ivar value: value of the filter :ivar type: filter type """ def __init__( self, property_model: Union[str, "Property"], value: Any, filter_type: FilterType, ): """Create PropertyValueFilter instance.""" from pykechain.models import Property property_model_id = check_base(property_model, Property, "property_model") check_enum(filter_type, FilterType, "filter_type") self.id = property_model_id if isinstance(value, str): self.value = unquote(value) else: self.value = value self.type = filter_type def __repr__(self): return f"PropertyValueFilter {self.type}: {self.value} ({self.id})" def format(self) -> str: """Format PropertyValueFilter as a string.""" if isinstance(self.value, str): value = urllib.parse.quote(self.value) elif isinstance(self.value, bool): value = str(self.value).lower() else: value = self.value return f"{self.id}:{value}:{self.type}" def validate(self, part_model: "Part") -> None: """ Validate data of the PropertyValueFilter. :param part_model: Part model to which the filter will be applied. :returns None """ from pykechain.models import Part check_base(part_model, Part, "part_model") try: prop = part_model.property(self.id) except NotFoundError: raise IllegalArgumentError( "Property value filters can only be set on properties belonging to the selected " "Part model." ) if prop.category != Category.MODEL: raise IllegalArgumentError( f'Property value filters can only be set on Property models, received "{prop}".' ) else: property_type = prop.type if ( property_type in ( PropertyType.BOOLEAN_VALUE, PropertyType.REFERENCES_VALUE, PropertyType.ACTIVITY_REFERENCES_VALUE, ) and self.type != FilterType.EXACT ): warnings.warn( "A PropertyValueFilter on a `{}` property should use " "filter type `{}`, not `{}`".format( property_type, FilterType.EXACT, self.type ), Warning, ) elif ( property_type in ( PropertyType.TEXT_VALUE, PropertyType.CHAR_VALUE, PropertyType.LINK_VALUE, PropertyType.SINGLE_SELECT_VALUE, PropertyType.USER_REFERENCES_VALUE, PropertyType.SCOPE_REFERENCES_VALUE, ) and self.type != FilterType.CONTAINS ): warnings.warn( "A PropertyValueFilter on a `{}` property should use " "filter type `{}`, not `{}`".format( property_type, FilterType.CONTAINS, self.type ), Warning, ) elif property_type in ( PropertyType.INT_VALUE, PropertyType.FLOAT_VALUE, PropertyType.DATE_VALUE, PropertyType.DATETIME_VALUE, ) and self.type not in ( FilterType.LOWER_THAN_EQUAL, FilterType.GREATER_THAN_EQUAL, ): warnings.warn( "A PropertyValueFilter on a `{}` property should use " "filter type `{}` or `{}`, not `{}`".format( property_type, FilterType.LOWER_THAN_EQUAL, FilterType.GREATER_THAN_EQUAL, self.type, ), Warning, ) elif ( property_type in (PropertyType.MULTI_SELECT_VALUE,) and self.type != FilterType.CONTAINS_SET ): warnings.warn( "A PropertyValueFilter on a `{}` property should use " "filter type `{}`, not `{}`".format( property_type, FilterType.CONTAINS_SET, self.type ), Warning, ) else: pass @classmethod def parse_options(cls, options: Dict) -> List["PropertyValueFilter"]: """ Convert dict and string filters to PropertyValueFilter objects. :param options: options dict from a multi-reference property or meta dict from a filtered grid widget. :return: list of PropertyValueFilter objects :rtype list """ check_type(options, dict, "options") prefilter_string = options.get(MetaWidget.PREFILTERS, {}).get("property_value") prefilter_string_list = prefilter_string.split(",") if prefilter_string else [] prefilters = list() for pf_string in prefilter_string_list: prefilter_raw = pf_string.split(":") if len(prefilter_raw) == 1: # FIXME encoding problem KE-chain prefilter_raw = pf_string.split("%3A") prefilters.append(PropertyValueFilter(*prefilter_raw)) return prefilters @classmethod def write_options(cls, filters: List) -> Dict: """ Convert the list of Filter objects to a dict. :param filters: List of BaseFilter objects :returns options dict to be used to update the options dict of a property """ super().write_options(filters=filters) prefilters = {"property_value": ",".join([pf.format() for pf in filters])} options = {MetaWidget.PREFILTERS: prefilters} return options
class PropertyValueFilter(BaseFilter): ''' Property value filter, used for Part reference properties and filtered grid widgets. :ivar id: property model UUID :ivar value: value of the filter :ivar type: filter type ''' def __init__( self, property_model: Union[str, "Property"], value: Any, filter_type: FilterType, ): '''Create PropertyValueFilter instance.''' pass def __repr__(self): pass def format(self) -> str: '''Format PropertyValueFilter as a string.''' pass def validate(self, part_model: "Part") -> None: ''' Validate data of the PropertyValueFilter. :param part_model: Part model to which the filter will be applied. :returns None ''' pass @classmethod def parse_options(cls, options: Dict) -> List["PropertyValueFilter"]: ''' Convert dict and string filters to PropertyValueFilter objects. :param options: options dict from a multi-reference property or meta dict from a filtered grid widget. :return: list of PropertyValueFilter objects :rtype list ''' pass @classmethod def write_options(cls, filters: List) -> Dict: ''' Convert the list of Filter objects to a dict. :param filters: List of BaseFilter objects :returns options dict to be used to update the options dict of a property ''' pass
9
6
26
2
21
3
3
0.2
1
13
6
0
4
3
6
9
173
21
127
30
111
26
50
23
41
7
1
2
18
140,707
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestPropertyWithValidatorFromLiveServer
class TestPropertyWithValidatorFromLiveServer(TestBetamax): def setUp(self): super().setUp() self.part_model = self.project.model(name="Model") self.numeric_range_prop_model = self.part_model.add_property( name="numericrange_validatortest", property_type=PropertyType.FLOAT_VALUE ) self.numeric_range_prop_model.validators = [ NumericRangeValidator(min=0.0, max=42.0) ] self.part = self.project.part(name__startswith="Catalog").add( self.part_model, name="Model Instance for tests" ) self.numeric_range_prop_instance = self.part.property( name="numericrange_validatortest" ) def tearDown(self): if self.numeric_range_prop_model: self.numeric_range_prop_model.delete() if self.part: self.part.delete() super().tearDown() def test_numeric_property_with_validator_parses(self): self.assertIsInstance(self.numeric_range_prop_instance._validators, list) self.assertIsInstance( self.numeric_range_prop_instance._validators[0], PropertyValidator ) def test_numeric_property_add_requiredvalidator_on_model(self): # test validators = self.numeric_range_prop_model.validators validators.append(RequiredFieldValidator()) self.numeric_range_prop_model.validators = validators for validator in self.numeric_range_prop_model.validators: self.assertIsInstance( validator, (NumericRangeValidator, RequiredFieldValidator) ) def test_numeric_property_add_requiredvalidator_on_instance(self): # test validators = self.numeric_range_prop_instance.validators validators.append(RequiredFieldValidator()) with self.assertRaisesRegex( IllegalArgumentError, "To update the list of validators, it can only work on `Property` of category 'MODEL'", ): self.numeric_range_prop_instance.validators = validators
class TestPropertyWithValidatorFromLiveServer(TestBetamax): def setUp(self): pass def tearDown(self): pass def test_numeric_property_with_validator_parses(self): pass def test_numeric_property_add_requiredvalidator_on_model(self): pass def test_numeric_property_add_requiredvalidator_on_instance(self): pass
6
0
9
0
8
0
2
0.05
1
7
5
0
5
4
5
80
51
6
43
13
37
2
28
13
22
3
3
1
8
140,708
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestRegexValidator
class TestRegexValidator(TestCase): def test_regex_validator_without_settings(self): validator = RegexStringValidator() self.assertIsNone(validator.validate_json()) self.assertIsInstance(validator.as_json(), dict) self.assertDictEqual( validator.as_json(), {"config": {}, "vtype": "regexStringValidator"} ) def test_regex_validator_with_pattern_match(self): validator = RegexStringValidator(pattern=r".*") self.assertTrue(validator("mr cactus is tevree")) def test_regex_validator_without_pattern_match(self): validator = RegexStringValidator() # per default the regex string matches everything self.assertEqual(validator.pattern, ".+") self.assertTrue(validator("mr cactus is tevree")) self.assertFalse(validator("")) def test_regex_validator_fails_on_none_value(self): validator = RegexStringValidator(pattern=r".*") self.assertFalse(validator.is_valid(None)) def test_regex_validator_complex_email_regex(self): validator = EmailValidator() self.assertTrue(validator.is_valid("support@ke-works.com")) self.assertFalse(validator.is_valid("___")) self.assertIsNone(validator.is_valid(None)) self.assertFalse(validator.is_valid("user@domain"))
class TestRegexValidator(TestCase): def test_regex_validator_without_settings(self): pass def test_regex_validator_with_pattern_match(self): pass def test_regex_validator_without_pattern_match(self): pass def test_regex_validator_fails_on_none_value(self): pass def test_regex_validator_complex_email_regex(self): pass
6
0
6
1
5
0
1
0.04
1
3
2
0
5
0
5
77
34
8
25
11
19
1
23
11
17
1
2
0
5
140,709
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestRequiredFieldValidator
class TestRequiredFieldValidator(TestCase): def test_requiredfield_validator_without_settings(self): validator = RequiredFieldValidator() self.assertIsNone(validator.validate_json()) self.assertIsInstance(validator.as_json(), dict) self.assertDictEqual( validator.as_json(), {"config": {}, "vtype": "requiredFieldValidator"} ) def test_requiredfield_validator_is_false_on_nonevalue(self): validator = RequiredFieldValidator() self.assertFalse(validator.is_valid(None)) self.assertFalse(validator.is_valid("")) self.assertFalse(validator.is_valid([])) self.assertFalse(validator.is_valid(list())) self.assertFalse(validator.is_valid(tuple())) self.assertFalse(validator.is_valid(set())) # the value 'False' is not a None value so that is True (placed in other test) # self.assertFalse(validator.is_valid(False)) def test_requiredfield_validator_is_true_on_value(self): validator = RequiredFieldValidator() self.assertTrue(validator.is_valid(1)) self.assertTrue(validator.is_valid(0)) self.assertTrue(validator.is_valid(0.0)) self.assertTrue(validator.is_valid(float("inf"))) self.assertTrue(validator.is_valid("string")) self.assertTrue(validator.is_valid({"key": "val"})) self.assertTrue(validator.is_valid([1, 2, 3])) self.assertTrue(validator.is_valid((1,))) self.assertTrue(validator.is_valid({1, 2, 3})) self.assertTrue(validator.is_valid(False))
class TestRequiredFieldValidator(TestCase): def test_requiredfield_validator_without_settings(self): pass def test_requiredfield_validator_is_false_on_nonevalue(self): pass def test_requiredfield_validator_is_true_on_value(self): pass
4
0
9
0
9
0
1
0.07
1
6
1
0
3
0
3
75
33
3
28
7
24
2
26
7
22
1
2
0
3
140,710
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestSingleReferenceValidator
class TestSingleReferenceValidator(TestCase): def test_singlereference_validator_without_settings(self): validator = SingleReferenceValidator() self.assertIsNone(validator.validate_json()) self.assertIsInstance(validator.as_json(), dict) self.assertDictEqual( validator.as_json(), {"config": {}, "vtype": "singleReferenceValidator"} ) def test_singlereference_validator_is_valid(self): validator = SingleReferenceValidator() self.assertIsNone(validator.is_valid(None)) self.assertTrue(validator.is_valid(list())) self.assertTrue(validator.is_valid(set())) self.assertTrue(validator.is_valid(tuple())) self.assertTrue(validator.is_valid(("first selection",))) def test_singlereference_validator_is_invalid(self): validator = SingleReferenceValidator() self.assertFalse(validator.is_valid(["first", "second"])) self.assertFalse(validator.is_valid((1, 2))) def test_singlerefence_validator_is_invalid_with_invalid_values(self): validator = SingleReferenceValidator() self.assertFalse(validator.is_valid("a string")) self.assertFalse(validator.is_valid(1.0)) self.assertFalse(validator.is_valid(dict()))
class TestSingleReferenceValidator(TestCase): def test_singlereference_validator_without_settings(self): pass def test_singlereference_validator_is_valid(self): pass def test_singlereference_validator_is_invalid(self): pass def test_singlerefence_validator_is_invalid_with_invalid_values(self): pass
5
0
6
0
6
0
1
0
1
5
1
0
4
0
4
76
27
3
24
9
19
0
22
9
17
1
2
0
4
140,711
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestValidatorDumping
class TestValidatorDumping(TestCase): def test_valid_numeric_range_validator_dumped(self): validator_json = dict( vtype="numericRangeValidator", config=dict( minvalue=2, maxvalue=10, stepsize=2, enforce_stepsize=False, on_valid=[dict(effect="visualEffect", config=dict(applyCss="valid"))], on_invalid=[ dict(effect="visualEffect", config=dict(applyCss="invalid")), dict( effect="errorTextEffect", config=dict( text="Range should be between 2 and 10 with step 2." ), ), ], ), ) validator = PropertyValidator.parse(validator_json) self.assertIsInstance(validator, NumericRangeValidator) dumped_json = validator.as_json() self.assertIsNone(validate(dumped_json, validator_jsonschema_stub)) self.assertIsNone(validator.validate_json())
class TestValidatorDumping(TestCase): def test_valid_numeric_range_validator_dumped(self): pass
2
0
27
2
25
0
1
0
1
3
2
0
1
0
1
73
28
2
26
5
24
0
8
5
6
1
2
0
1
140,712
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestValidatorEffects
class TestValidatorEffects(TestCase): def test_validator_effect_produces_valid_json(self): ve = ValidatorEffect() ve.validate_json() def test_visual_effect_produces_valid_json(self): ve = VisualEffect() self.assertTrue("applyCss" in ve.as_json().get("config")) ve.validate_json() def test_valid_visualeffect_produces_valid_json(self): ve = ValidVisualEffect() self.assertTrue("applyCss" in ve.as_json().get("config")) ve.validate_json() def test_invalid_visualeffect_productes_valid_json(self): ve = InvalidVisualEffect() self.assertTrue("applyCss" in ve.as_json().get("config")) ve.validate_json()
class TestValidatorEffects(TestCase): def test_validator_effect_produces_valid_json(self): pass def test_visual_effect_produces_valid_json(self): pass def test_valid_visualeffect_produces_valid_json(self): pass def test_invalid_visualeffect_productes_valid_json(self): pass
5
0
4
0
4
0
1
0
1
4
4
0
4
0
4
76
19
3
16
9
11
0
16
9
11
1
2
0
4
140,713
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/validators.py
pykechain.models.validators.validators.RequiredFieldValidator
class RequiredFieldValidator(PropertyValidator): """ Required field validator ensures that a value is provided. Does validate all values. Does not validate `None` or `''` (empty string). .. versionadded:: 2.2 Examples -------- >>> validator = RequiredFieldValidator() >>> validator.is_valid("A value") True >>> validator.is_valid("") False >>> validator.is_valid(None) False >>> validator.get_reason() "Value is required" """ vtype = PropertyVTypes.REQUIREDFIELD def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: basereason = "Value is required" self._validation_result, self._validation_reason = None, "No reason" if ( value is not None and value != "" and value != list() and value != tuple() and value != set() ): self._validation_result = True self._validation_reason = "Value is provided" else: self._validation_result = False self._validation_reason = basereason return self._validation_result, self._validation_reason
class RequiredFieldValidator(PropertyValidator): ''' Required field validator ensures that a value is provided. Does validate all values. Does not validate `None` or `''` (empty string). .. versionadded:: 2.2 Examples -------- >>> validator = RequiredFieldValidator() >>> validator.is_valid("A value") True >>> validator.is_valid("") False >>> validator.is_valid(None) False >>> validator.get_reason() "Value is required" ''' def _logic(self, value: Any = None) -> Tuple[Union[bool, None], str]: pass
2
1
18
2
16
0
2
0.89
1
6
0
0
1
2
1
14
42
8
18
5
16
16
11
5
9
2
2
1
2
140,714
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestValidatorJSON
class TestValidatorJSON(TestCase): def test_valid_numeric_range_validator_json(self): options = dict( validators=[ dict( vtype="numericRangeValidator", config=dict( minvalue=2, maxvalue=10, stepsize=2, on_valid=[ dict(effect="CssEffect", config=dict(applyCss="valid")) ], on_invalid=[ dict(effect="CssEffect", config=dict(applyCss="invalid")), dict( effect="ErrorText", config=dict( text="Range should be between 2 and 10 with step 2." ), ), ], ), ) ] ) validate(options_json_schema, options) def test_valid_requiredfield_validator_json(self): options = { "validators": [ { "vtype": "requiredFieldValidator", "config": { "effects_when_valid": [], "effects_when_invalid": [ { "effect": "ErrorText", "config": {"Text": "This field is required."}, } ], }, }, {"vtype": "numericRangeValidator", "config": {"minValue": 0}}, ] } validate(options_json_schema, options) def test_valid_booleanfield_validator_json(self): options = { "validators": [ { "vtype": "booleanFieldValidator", "config": { "is_valid": False, "is_invalid": [True, None], "effects_when_valid": [], "effects_when_invalid": [ { "effect": "ErrorText", "text": "Value of the field should be False", } ], }, } ] } validate(options_json_schema, options) def test_validator_invalid_vtype(self): validator_json = {"vtype": "invalid", "config": {}} with self.assertRaisesRegex(ValidationError, "'invalid' is not one of"): validate(validator_json, validator_jsonschema_stub) def test_validator_missing_vtype(self): validator_json = {"config": {}} with self.assertRaisesRegex(ValidationError, "'vtype' is a required property"): validate(validator_json, validator_jsonschema_stub) def test_validator_config_not_a_dict(self): v = {"vtype": PropertyVTypes.NUMERICRANGE, "config": []} with self.assertRaisesRegex(ValidationError, "is not of type 'object'"): validate(v, validator_jsonschema_stub) def test_validator_on_valid_not_a_list(self): v = {"vtype": PropertyVTypes.NUMERICRANGE, "config": {"on_valid": {}}} with self.assertRaisesRegex(ValidationError, "is not of type 'array'"): validate(v, validator_jsonschema_stub) def test_validator_on_invalid_not_a_list(self): v = {"vtype": PropertyVTypes.NUMERICRANGE, "config": {"on_invalid": {}}} with self.assertRaisesRegex(ValidationError, "is not of type 'array'"): validate(v, validator_jsonschema_stub) def test_validator_on_valid_list_with_obj(self): v = { "vtype": PropertyVTypes.NUMERICRANGE, "config": {"on_valid": [{"effect": "", "config": {}}]}, } validate(v, validator_jsonschema_stub) def test_validator_on_invalid_list_with_obj(self): v = { "vtype": PropertyVTypes.NUMERICRANGE, "config": {"on_invalid": [{"effect": "", "config": {}}]}, } validate(v, validator_jsonschema_stub) def test_validatoreffect_requires_effect_property(self): v = {} with self.assertRaisesRegex(ValidationError, "'effect' is a required property"): validate(v, effects_jsonschema_stub) def test_validatoreffect_requires_config_property(self): v = {"effect": ""} with self.assertRaisesRegex(ValidationError, "'config' is a required property"): validate(v, effects_jsonschema_stub) def test_validatoreffect_not_allows_additional_properties(self): v = {"effect": "", "config": {}, "additional_option": None} with self.assertRaisesRegex( ValidationError, r"Additional properties are not allowed \('additional_option' was unexpected\)", ): validate(v, effects_jsonschema_stub)
class TestValidatorJSON(TestCase): def test_valid_numeric_range_validator_json(self): pass def test_valid_requiredfield_validator_json(self): pass def test_valid_booleanfield_validator_json(self): pass def test_validator_invalid_vtype(self): pass def test_validator_missing_vtype(self): pass def test_validator_config_not_a_dict(self): pass def test_validator_on_valid_not_a_list(self): pass def test_validator_on_invalid_not_a_list(self): pass def test_validator_on_valid_list_with_obj(self): pass def test_validator_on_invalid_list_with_obj(self): pass def test_validatoreffect_requires_effect_property(self): pass def test_validatoreffect_requires_config_property(self): pass def test_validatoreffect_not_allows_additional_properties(self): pass
14
0
9
0
9
0
1
0
1
3
1
0
13
0
13
85
128
15
113
27
99
0
48
27
34
1
2
1
13
140,715
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/models/test_representations.py
tests.models.test_representations.Bases._TestPropertyRepresentation
class _TestPropertyRepresentation(_TestRepresentationLive): property_type = None test_model_name = "__test model for representations" test_model = None incorrect_value = "Unsupported value" def tearDown(self): if self.test_model: try: self.test_model.delete() except APIError: pass super().tearDown() def _get_object(self): parent_model = self.project.model(name="Bike") self.test_model = parent_model.add_model( name=self.test_model_name, multiplicity=Multiplicity.ONE ) obj = self.test_model.add_property( name=self.test_object_name, property_type=self.property_type, ) # type: AnyProperty return obj
class _TestPropertyRepresentation(_TestRepresentationLive): def tearDown(self): pass def _get_object(self): pass
3
0
9
0
9
1
2
0.05
1
3
2
24
2
1
2
84
24
2
22
10
19
1
17
9
14
3
4
2
4
140,716
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/test_property_value_filter.py
tests.test_property_value_filter.BaseTest._TestScopeFilter
class _TestScopeFilter(TestCase): VALUE = None VALUE_2 = None INVALID_VALUE = None FIELD = None ATTR = None @classmethod def setUpClass(cls) -> None: super().setUpClass() if cls.VALUE == cls.VALUE_2: # pragma: no cover raise ValueError( f"Test needs 2 different values ({cls.VALUE}, {cls.VALUE_2})") def setUp(self) -> None: super().setUp() self.filter = ScopeFilter(**{self.ATTR: self.VALUE}) def test__repr__(self): representation = self.filter.__repr__() self.assertIsInstance(representation, str) def test__eq__(self): second_filter = ScopeFilter(**{self.ATTR: self.VALUE}) third_filter = ScopeFilter(**{self.ATTR: self.VALUE_2}) self.assertEqual(self.filter, second_filter) self.assertNotEqual(self.filter, third_filter) def test_write_options(self): filter_2 = ScopeFilter(**{self.ATTR: self.VALUE_2}) filters = [self.filter, filter_2] options_dict = ScopeFilter.write_options(filters=filters) self.assertIsInstance(options_dict, dict) with self.assertRaises(IllegalArgumentError): PropertyValueFilter.write_options(filters=[self.filter]) def test_parse_options(self): options = ScopeFilter.write_options(filters=[self.filter]) scope_filters = ScopeFilter.parse_options(options=options) self.assertTrue(scope_filters) self.assertIsInstance(scope_filters, list) self.assertTrue(all(isinstance(sf, ScopeFilter) for sf in scope_filters)) def test_creation(self): if self.INVALID_VALUE is not None: with self.assertRaises(IllegalArgumentError): ScopeFilter(**{self.ATTR: self.INVALID_VALUE}) with self.assertRaises(IllegalArgumentError): ScopeFilter(tag="My scope tag", status=ScopeStatus.ACTIVE)
class _TestScopeFilter(TestCase): @classmethod def setUpClass(cls) -> None: pass def setUpClass(cls) -> None: pass def test__repr__(self): pass def test__eq__(self): pass def test_write_options(self): pass def test_parse_options(self): pass def test_creation(self): pass
9
0
6
1
5
0
1
0.02
1
9
4
11
6
1
7
79
57
16
41
23
32
1
40
22
32
2
2
2
9
140,717
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.SignificantDigits
class SignificantDigits(DecimalPlaces): """Representation for floating-point value properties.""" rtype = PropertyRepresentation.SIGNIFICANT_DIGITS
class SignificantDigits(DecimalPlaces): '''Representation for floating-point value properties.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
9
4
1
2
2
1
1
2
2
1
0
2
0
0
140,718
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.SimpleConfigValueKeyRepresentation
class SimpleConfigValueKeyRepresentation(BaseRepresentation): """A simple representation object where the _config_value keys is the same as the rtype. This representations have the following basic json representation: ``` { "rtype": "<simpleRepr>", "config": { "<simpleRepr>": <some value> } } ``` This class is used in several very simplified 'boolean' type representation types. Such as, ao: UsePropertyNameRepresentation, the _config_value_type = "usePropertyName" CameraScannerInputRepresentation, the _config_value_type = "cameraScannerInput" What you need to do is to set the class variable `rtype` when you override. """ rtype = None _config_value_key = None def validate_representation(self, value: bool) -> None: """ Validate whether the representation value can be set. :param value: representation value to set. :type value: a boolean :return: None """ check_type(value, bool, self._config_value_key)
class SimpleConfigValueKeyRepresentation(BaseRepresentation): '''A simple representation object where the _config_value keys is the same as the rtype. This representations have the following basic json representation: ``` { "rtype": "<simpleRepr>", "config": { "<simpleRepr>": <some value> } } ``` This class is used in several very simplified 'boolean' type representation types. Such as, ao: UsePropertyNameRepresentation, the _config_value_type = "usePropertyName" CameraScannerInputRepresentation, the _config_value_type = "cameraScannerInput" What you need to do is to set the class variable `rtype` when you override. ''' def validate_representation(self, value: bool) -> None: ''' Validate whether the representation value can be set. :param value: representation value to set. :type value: a boolean :return: None ''' pass
2
2
9
1
2
6
1
4.2
1
1
0
5
1
0
1
9
34
8
5
4
3
21
5
4
3
1
1
0
1
140,719
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.StoredFilesDisplayRepresentation
class StoredFilesDisplayRepresentation(SimpleConfigValueKeyRepresentation): """Representation for the stored files display inside a `StoredFilesReferencesProperty`.""" rtype = PropertyRepresentation.FILE_DISPLAY _config_value_key = "mode" def validate_representation(self, value: Any) -> None: """ Validate whether the representation value can be set. :param value: representation value to set. :type value: Any :raises IllegalArgumentError :return: None """ check_enum( value, FileDisplayRepresentationValues, "file display representation values" )
class StoredFilesDisplayRepresentation(SimpleConfigValueKeyRepresentation): '''Representation for the stored files display inside a `StoredFilesReferencesProperty`.''' def validate_representation(self, value: Any) -> None: ''' Validate whether the representation value can be set. :param value: representation value to set. :type value: Any :raises IllegalArgumentError :return: None ''' pass
2
2
12
1
4
7
1
1.14
1
2
1
0
1
0
1
10
18
3
7
4
5
8
5
4
3
1
2
0
1
140,720
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.ThousandsSeparator
class ThousandsSeparator(BaseRepresentation): """Representation for integer or floating-point value properties.""" rtype = PropertyRepresentation.THOUSANDS_SEPARATOR def validate_representation(self, value): """ Validate whether the representation value can be set. :param value: representation value to set. :type value: int or float :return: None """ if not (isinstance(value, type(None))): raise IllegalArgumentError( '{} value "{}" is not correct: not NoneType'.format( self.__class__.__name__, value ) )
class ThousandsSeparator(BaseRepresentation): '''Representation for integer or floating-point value properties.''' def validate_representation(self, value): ''' Validate whether the representation value can be set. :param value: representation value to set. :type value: int or float :return: None ''' pass
2
2
14
1
7
6
2
0.78
1
2
1
0
1
0
1
9
19
3
9
3
7
7
5
3
3
2
1
1
2
140,721
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.UsePropertyNameRepresentation
class UsePropertyNameRepresentation(SimpleConfigValueKeyRepresentation): """Representation for the use of Property Names in a reference property.""" rtype = PropertyRepresentation.USE_PROPERTY_NAME _config_value_key = PropertyRepresentation.USE_PROPERTY_NAME
class UsePropertyNameRepresentation(SimpleConfigValueKeyRepresentation): '''Representation for the use of Property Names in a reference property.''' pass
1
1
0
0
0
0
0
0.33
1
0
0
0
0
0
0
9
5
1
3
3
2
1
3
3
2
0
2
0
0
140,722
KE-works/pykechain
KE-works_pykechain/pykechain/models/service.py
pykechain.models.service.Service
class Service(BaseInScope): """ A virtual object representing a KE-chain Service. .. versionadded:: 1.13 :ivar id: id of the service :type id: uuid :ivar name: name of the service :type name: str :ivar description: description of the service :type description: str :ivar version: version number of the service, as provided by uploaded :type version: str :ivar type: type of the service. One of the :class:`ServiceType` :type type: str :ivar filename: filename of the service :type filename: str :ivar environment: environment in which the service will execute. One of :class:`ServiceEnvironmentVersion` :type environment: str :ivar updated_at: datetime in UTC timezone when the Service was last updated :type updated_at: datetime .. versionadded:: 3.0 :ivar trusted: Trusted flag. If the kecpkg is trusted. :ivar run_as: User to run the script as. One of :class:`ServiceScriptUser`. :ivar verified_on: Date when the kecpkg was verified by KE-chain (if verification pipeline is enabled) :ivar verification_results: Results of the verification (if verification pipeline is enabled) """ def __init__(self, json, **kwargs): """Construct a service from provided json data.""" super().__init__(json, **kwargs) del self.created_at self.description = json.get("description", "") self.version = json.get("script_version", "") self.filename = json.get("script_file_name") self.type = json.get("script_type") self.environment = json.get("env_version") # for SIM3 version self.trusted: bool = json.get("trusted") self.run_as: str = json.get("run_as") self.verified_on: Optional[datetime] = parse_datetime(json.get("verified_on")) self.verification_results: Dict = json.get("verification_results") def __repr__(self): # pragma: no cover return f"<pyke Service '{self.name}' id {self.id[-8:]}>" def execute( self, interactive: Optional[bool] = False, **kwargs ) -> "ServiceExecution": """ Execute the service. For interactive (notebook) service execution, set interactive to True, defaults to False. .. versionadded:: 1.13 :param interactive: (optional) True if the notebook service should execute in interactive mode. :type interactive: bool or None :return: ServiceExecution when successful. :raises APIError: when unable to execute """ request_params = dict( interactive=check_type(interactive, bool, "interactive"), format="json", **kwargs, ) url = self._client._build_url("service_execute", service_id=self.id) response = self._client._request("GET", url, params=request_params) if response.status_code == requests.codes.conflict: # pragma: no cover raise APIError( f"Conflict: Could not execute Service {self} as it is already running.", response=response, ) elif response.status_code != requests.codes.accepted: # pragma: no cover raise APIError(f"Could not execute Service {self}", response=response) data = response.json() return ServiceExecution(json=data.get("results")[0], client=self._client) def edit( self, name: Optional[Union[str, Empty]] = empty, description: Optional[Union[str, Empty]] = empty, version: Optional[Union[str, Empty]] = empty, type: Optional[Union[ServiceType, Empty]] = empty, environment_version: Optional[Union[ServiceEnvironmentVersion, Empty]] = empty, run_as: Optional[Union[ServiceScriptUser, Empty]] = empty, trusted: Optional[Union[bool, Empty]] = empty, **kwargs, ) -> None: """ Edit Service details. Setting an input to None will clear out the value (exception being name). .. versionadded:: 1.13 :param name: (optional) name of the service to change. Cannot be cleared. :type name: basestring or None or Empty :param description: (optional) description of the service. Can be cleared. :type description: basestring or None or Empty :param version: (optional) version number of the service. Can be cleared. :type version: basestring or None or Empty :param type: (optional) script type (Python or Notebook). Cannot be cleared. :type type: ServiceType or None or Empty :param environment_version: (optional) environment version of the service. Cannot be cleared. :type environment_version: ServiceEnvironmentVersion or None or Empty :param run_as: (optional) user to run the service as. Defaults to kenode user (bound to scope). Cannot be cleared. :type run_as: ServiceScriptUser or None or Empty :param trusted: (optional) flag whether the service is trusted, default if False. Cannot be cleared. :type trusted: bool or None or Empty :raises IllegalArgumentError: when you provide an illegal argument. :raises APIError: if the service could not be updated. Example ------- >>> service.edit(name='Car service',version='203') Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will clear its value (where that is possible). The example below will clear the description and edit the name. >>> service.edit(name="Plane service",description=None) """ update_dict = { "id": self.id, "name": check_text(name, "name") or self.name, "description": check_text(description, "description") or "", "trusted": check_type(trusted, bool, "trusted") or self.trusted, "script_type": check_enum(type, ServiceType, "type") or self.type, "env_version": check_enum( environment_version, ServiceEnvironmentVersion, "environment version" ) or self.environment, "run_as": check_enum(run_as, ServiceScriptUser, "run_as") or self.run_as, "script_version": check_text(version, "version") or "", } if kwargs: # pragma: no cover update_dict.update(**kwargs) update_dict = clean_empty_values(update_dict=update_dict) response = self._client._request( "PUT", self._client._build_url("service", service_id=self.id), json=update_dict, ) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError(f"Could not update Service {self}", response=response) self.refresh(json=response.json()["results"][0]) def delete(self) -> None: """Delete this service. :raises APIError: if delete was not successful. """ response = self._client._request( "DELETE", self._client._build_url("service", service_id=self.id) ) if response.status_code != requests.codes.no_content: # pragma: no cover raise APIError(f"Could not delete Service {self}", response=response) def upload(self, pkg_path): """ Upload a python script (or kecpkg) to the service. .. versionadded:: 1.13 :param pkg_path: path to the python script or kecpkg to upload. :type pkg_path: basestring :raises APIError: if the python package could not be uploaded. :raises OSError: if the python package could not be located on disk. """ if os.path.exists(pkg_path): self._upload(pkg_path=pkg_path) else: raise OSError(f"Could not locate python package to upload in '{pkg_path}'") def _upload(self, pkg_path): url = self._client._build_url("service_upload", service_id=self.id) with open(pkg_path, "rb") as pkg: response = self._client._request( "POST", url, files={"attachment": (os.path.basename(pkg_path), pkg)} ) if response.status_code != requests.codes.accepted: # pragma: no cover raise APIError( f"Could not upload script file (or kecpkg) to Service {self}", response=response, ) self.refresh(json=response.json()["results"][0]) def save_as(self, target_dir=None): """ Save the kecpkg service script to an (optional) target dir. Retains the filename of the service as known in KE-chain. .. versionadded:: 1.13 :param target_dir: (optional) target dir. If not provided will save to current working directory. :type target_dir: basestring or None :raises APIError: if unable to download the service. :raises OSError: if unable to save the service kecpkg file to disk. """ full_path = os.path.join(target_dir or os.getcwd(), self.filename) url = self._client._build_url("service_download", service_id=self.id) response = self._client._request("GET", url) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError( f"Could not download script file from Service {self}", response=response ) with open(full_path, "w+b") as f: for chunk in response: f.write(chunk) def get_executions(self, **kwargs): """ Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of ServiceExecutions associated to the current service. """ return self._client.service_executions( service=self.id, scope=self.scope_id, **kwargs )
class Service(BaseInScope): ''' A virtual object representing a KE-chain Service. .. versionadded:: 1.13 :ivar id: id of the service :type id: uuid :ivar name: name of the service :type name: str :ivar description: description of the service :type description: str :ivar version: version number of the service, as provided by uploaded :type version: str :ivar type: type of the service. One of the :class:`ServiceType` :type type: str :ivar filename: filename of the service :type filename: str :ivar environment: environment in which the service will execute. One of :class:`ServiceEnvironmentVersion` :type environment: str :ivar updated_at: datetime in UTC timezone when the Service was last updated :type updated_at: datetime .. versionadded:: 3.0 :ivar trusted: Trusted flag. If the kecpkg is trusted. :ivar run_as: User to run the script as. One of :class:`ServiceScriptUser`. :ivar verified_on: Date when the kecpkg was verified by KE-chain (if verification pipeline is enabled) :ivar verification_results: Results of the verification (if verification pipeline is enabled) ''' def __init__(self, json, **kwargs): '''Construct a service from provided json data.''' pass def __repr__(self): pass def execute( self, interactive: Optional[bool] = False, **kwargs ) -> "ServiceExecution": ''' Execute the service. For interactive (notebook) service execution, set interactive to True, defaults to False. .. versionadded:: 1.13 :param interactive: (optional) True if the notebook service should execute in interactive mode. :type interactive: bool or None :return: ServiceExecution when successful. :raises APIError: when unable to execute ''' pass def edit( self, name: Optional[Union[str, Empty]] = empty, description: Optional[Union[str, Empty]] = empty, version: Optional[Union[str, Empty]] = empty, type: Optional[Union[ServiceType, Empty]] = empty, environment_version: Optional[Union[ServiceEnvironmentVersion, Empty]] = empty, run_as: Optional[Union[ServiceScriptUser, Empty]] = empty, trusted: Optional[Union[bool, Empty]] = empty, **kwargs, ) -> None: ''' Edit Service details. Setting an input to None will clear out the value (exception being name). .. versionadded:: 1.13 :param name: (optional) name of the service to change. Cannot be cleared. :type name: basestring or None or Empty :param description: (optional) description of the service. Can be cleared. :type description: basestring or None or Empty :param version: (optional) version number of the service. Can be cleared. :type version: basestring or None or Empty :param type: (optional) script type (Python or Notebook). Cannot be cleared. :type type: ServiceType or None or Empty :param environment_version: (optional) environment version of the service. Cannot be cleared. :type environment_version: ServiceEnvironmentVersion or None or Empty :param run_as: (optional) user to run the service as. Defaults to kenode user (bound to scope). Cannot be cleared. :type run_as: ServiceScriptUser or None or Empty :param trusted: (optional) flag whether the service is trusted, default if False. Cannot be cleared. :type trusted: bool or None or Empty :raises IllegalArgumentError: when you provide an illegal argument. :raises APIError: if the service could not be updated. Example ------- >>> service.edit(name='Car service',version='203') Not mentioning an input parameter in the function will leave it unchanged. Setting a parameter as None will clear its value (where that is possible). The example below will clear the description and edit the name. >>> service.edit(name="Plane service",description=None) ''' pass def delete(self) -> None: '''Delete this service. :raises APIError: if delete was not successful. ''' pass def upload(self, pkg_path): ''' Upload a python script (or kecpkg) to the service. .. versionadded:: 1.13 :param pkg_path: path to the python script or kecpkg to upload. :type pkg_path: basestring :raises APIError: if the python package could not be uploaded. :raises OSError: if the python package could not be located on disk. ''' pass def _upload(self, pkg_path): pass def save_as(self, target_dir=None): ''' Save the kecpkg service script to an (optional) target dir. Retains the filename of the service as known in KE-chain. .. versionadded:: 1.13 :param target_dir: (optional) target dir. If not provided will save to current working directory. :type target_dir: basestring or None :raises APIError: if unable to download the service. :raises OSError: if unable to save the service kecpkg file to disk. ''' pass def get_executions(self, **kwargs): ''' Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of ServiceExecutions associated to the current service. ''' pass
10
8
23
4
12
8
2
0.93
1
12
6
0
9
10
9
16
245
47
107
47
85
99
59
32
49
3
2
2
18
140,723
KE-works/pykechain
KE-works_pykechain/pykechain/models/service.py
pykechain.models.service.ServiceExecution
class ServiceExecution(Base): """ A virtual object representing a KE-chain Service Execution. .. versionadded:: 1.13 :ivar id: id of the service execution :type id: uuid :ivar name: name of the service to which the execution is associated :type name: str :ivar status: status of the service. One of :class:`ServiceExecutionStatus` :type status: str :ivar service: the :class:`Service` object associated to this service execution :type service: :class:`Service` :ivar service_id: the uuid of the associated Service object :type service_id: uuid :ivar user: (optional) username of the user that executed the service :type user: str or None :ivar activity_id: (optional) the uuid of the activity where the service was executed from :type activity_id: uuid or None """ def __init__(self, json, **kwargs): """Construct a scope from provided json data.""" super().__init__(json, **kwargs) del self.created_at del self.updated_at self.name = json.get("service_name") self.service_id = json.get("service") self.status: ServiceExecutionStatus = json.get("status", "") self.user = json.get("username") if json.get("activity") is not None: self.activity_id: Optional[str] = json["activity"].get("id") else: self.activity_id = None self.started_at: Optional[datetime] = parse_datetime(json.get("started_at")) self.finished_at: Optional[datetime] = parse_datetime(json.get("finished_at")) self._service: Optional[Service] = None def __repr__(self): # pragma: no cover return f"<pyke ServiceExecution '{self.name}' id {self.id[-8:]}>" @property def service(self) -> Service: """Retrieve the `Service` object to which this execution is associated.""" if not self._service: self._service = self._client.service(id=self.service_id) return self._service def terminate(self): """ Terminate the Service execution. .. versionadded:: 1.13 :return: None if the termination request was successful :raises APIError: When the service execution could not be terminated. """ url = self._client._build_url( "service_execution_terminate", service_execution_id=self.id ) response = self._client._request("GET", url, params=dict(format="json")) if response.status_code != requests.codes.accepted: # pragma: no cover raise APIError(f"Could not terminate Service {self}", response=response) def get_log(self, target_dir=None, log_filename="log.txt"): """ Retrieve the log of the service execution. .. versionadded:: 1.13 :param target_dir: (optional) directory path name where the store the log.txt to. :type target_dir: basestring or None :param log_filename: (optional) log filename to write the log to, defaults to `log.txt`. :type log_filename: basestring or None :raises APIError: if the logfile could not be found. :raises OSError: if the file could not be written. """ full_path = os.path.join(target_dir or os.getcwd(), log_filename) url = self._client._build_url( "service_execution_log", service_execution_id=self.id ) response = self._client._request("GET", url) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError( f"Could not download execution log of Service {self}", response=response ) with open(full_path, "w+b") as f: for chunk in response: f.write(chunk) def get_notebook_url(self): """ Get the url of the notebook, if the notebook is executed in interactive mode. .. versionadded:: 1.13 :return: full url to the interactive running notebook as `basestring` :raises APIError: when the url cannot be retrieved. """ url = self._client._build_url( "service_execution_notebook_url", service_execution_id=self.id ) response = self._client._request("GET", url, params=dict(format="json")) if response.status_code != requests.codes.ok: raise APIError( f"Could not retrieve notebook url of Service {self}", response=response ) data = response.json() url = data.get("results")[0].get("url") return url
class ServiceExecution(Base): ''' A virtual object representing a KE-chain Service Execution. .. versionadded:: 1.13 :ivar id: id of the service execution :type id: uuid :ivar name: name of the service to which the execution is associated :type name: str :ivar status: status of the service. One of :class:`ServiceExecutionStatus` :type status: str :ivar service: the :class:`Service` object associated to this service execution :type service: :class:`Service` :ivar service_id: the uuid of the associated Service object :type service_id: uuid :ivar user: (optional) username of the user that executed the service :type user: str or None :ivar activity_id: (optional) the uuid of the activity where the service was executed from :type activity_id: uuid or None ''' def __init__(self, json, **kwargs): '''Construct a scope from provided json data.''' pass def __repr__(self): pass @property def service(self) -> Service: '''Retrieve the `Service` object to which this execution is associated.''' pass def terminate(self): ''' Terminate the Service execution. .. versionadded:: 1.13 :return: None if the termination request was successful :raises APIError: When the service execution could not be terminated. ''' pass def get_log(self, target_dir=None, log_filename="log.txt"): ''' Retrieve the log of the service execution. .. versionadded:: 1.13 :param target_dir: (optional) directory path name where the store the log.txt to. :type target_dir: basestring or None :param log_filename: (optional) log filename to write the log to, defaults to `log.txt`. :type log_filename: basestring or None :raises APIError: if the logfile could not be found. :raises OSError: if the file could not be written. ''' pass def get_notebook_url(self): ''' Get the url of the notebook, if the notebook is executed in interactive mode. .. versionadded:: 1.13 :return: full url to the interactive running notebook as `basestring` :raises APIError: when the url cannot be retrieved. ''' pass
8
6
15
3
9
5
2
0.82
1
7
3
0
6
8
6
11
120
23
55
26
47
45
43
24
36
3
1
2
12
140,724
KE-works/pykechain
KE-works_pykechain/pykechain/models/sidebar/sidebar_button.py
pykechain.models.sidebar.sidebar_button.SideBarButton
class SideBarButton(SideBarItem): """ Side-bar button class. Every custom button in the side-bar is maintained as an object of this class. The original KE-chain buttons for the project detail, tasks and work breakdown structure are not separate buttons. :cvar allowed_attributes: allowed additional attributed provided as options alongside the specifically allowed ones. :cvar item_type: the item type of this class. Defaults to a BUTTON. """ _allowed_attributes = [ "displayName_nl", "displayName_en", "displayName_de", "displayName_fr", "displayName_it", ] _item_type = SidebarType.BUTTON def __init__( self, side_bar_manager: "SideBarManager", json: Optional[Dict] = None, title: Optional[str] = None, icon: Optional[str] = None, uri: Optional[str] = None, alignment: SidebarItemAlignment = SidebarItemAlignment.TOP, minimum_access_level: SidebarAccessLevelOptions = SidebarAccessLevelOptions.IS_MEMBER, uri_target: URITarget = URITarget.INTERNAL, icon_mode: FontAwesomeMode = FontAwesomeMode.REGULAR, **kwargs, ): """ Create a side-bar button. :param side_bar_manager: Manager object to which the button is linked. :param json: the json response to construct the :class:`SideBarButton` from :param title: visible label of the button :param icon: FontAwesome icon of the button :param uri: Uniform Resource Identifier, the address of the linked page :param uri_target: type of URI, either internal or external :param alignment: alignment of the button top or bottom :param minimum_access_level: the minimum permission needed to see the button :param icon_mode: FontAwesome display mode of the icon :returns None :raises IllegalArgumentError: When the provided Argument is not according to the type. """ super().__init__() if json is None: json = {} title = title if title else json.get("displayName") icon = icon if icon else json.get("displayIcon") uri = uri if uri else json.get("uri") uri_target = json.get("uriTarget", uri_target) icon_mode = json.get("displayIconMode", icon_mode) alignment = json.get("align", alignment) minimum_access_level = json.get("minimumAccessLevel", minimum_access_level) if not isinstance(title, str): raise IllegalArgumentError(f'title must be a string, "{title}" is not.') if not isinstance(icon, str): raise IllegalArgumentError(f'icon must be a string, "{icon}" is not.') if not isinstance(uri, str): raise IllegalArgumentError(f'uri must be a string, "{uri}" is not.') if uri_target not in URITarget.values(): raise IllegalArgumentError( f'uri_target must be a URITarget option, "{uri_target}" is not.' ) if icon_mode not in FontAwesomeMode.values(): raise IllegalArgumentError( f'icon_mode must be a FontAwesomeMode option, "{icon_mode}" is not.' ) for key in kwargs.keys(): if key not in self._allowed_attributes: raise IllegalArgumentError( f'Attribute "{key}" is not supported in the configuration of a side-bar' " card." ) self._manager: "SideBarManager" = side_bar_manager self.display_name: str = title self.display_icon: str = icon self.uri: str = uri self.uri_target: URITarget = uri_target self.display_icon_mode: FontAwesomeMode = icon_mode self.alignment: SidebarItemAlignment = alignment self.minimum_access_level: SidebarAccessLevelOptions = minimum_access_level self._other_attributes = kwargs for key in self._allowed_attributes: if key in json: self._other_attributes[key] = json[key] def as_dict(self) -> Dict: """ Retrieve the configuration data, or `meta`, of the side-bar button. :return: dictionary of the configuration data :rtype dict """ config = { "itemType": self._item_type, "displayName": self.display_name, "displayIcon": self.display_icon, "uriTarget": self.uri_target, "uri": self.uri, "displayIconMode": self.display_icon_mode, "align": self.alignment, "minimumAccessLevel": self.minimum_access_level, } config.update(self._other_attributes) config = {k: v for k, v in config.items() if v is not None} return config
class SideBarButton(SideBarItem): ''' Side-bar button class. Every custom button in the side-bar is maintained as an object of this class. The original KE-chain buttons for the project detail, tasks and work breakdown structure are not separate buttons. :cvar allowed_attributes: allowed additional attributed provided as options alongside the specifically allowed ones. :cvar item_type: the item type of this class. Defaults to a BUTTON. ''' def __init__( self, side_bar_manager: "SideBarManager", json: Optional[Dict] = None, title: Optional[str] = None, icon: Optional[str] = None, uri: Optional[str] = None, alignment: SidebarItemAlignment = SidebarItemAlignment.TOP, minimum_access_level: SidebarAccessLevelOptions = SidebarAccessLevelOptions.IS_MEMBER, uri_target: URITarget = URITarget.INTERNAL, icon_mode: FontAwesomeMode = FontAwesomeMode.REGULAR, **kwargs, ): ''' Create a side-bar button. :param side_bar_manager: Manager object to which the button is linked. :param json: the json response to construct the :class:`SideBarButton` from :param title: visible label of the button :param icon: FontAwesome icon of the button :param uri: Uniform Resource Identifier, the address of the linked page :param uri_target: type of URI, either internal or external :param alignment: alignment of the button top or bottom :param minimum_access_level: the minimum permission needed to see the button :param icon_mode: FontAwesome display mode of the icon :returns None :raises IllegalArgumentError: When the provided Argument is not according to the type. ''' pass def as_dict(self) -> Dict: ''' Retrieve the configuration data, or `meta`, of the side-bar button. :return: dictionary of the configuration data :rtype dict ''' pass
3
3
49
5
35
10
8
0.36
1
7
5
0
2
9
2
7
120
14
78
28
63
28
44
16
41
14
1
2
15
140,725
KE-works/pykechain
KE-works_pykechain/pykechain/models/sidebar/sidebar_card.py
pykechain.models.sidebar.sidebar_card.SideBarCard
class SideBarCard(SideBarItem): """ Side-bar card class. Every side-bar can have one or more cards and is maintained as an object of this class. :cvar allowed_attributes: allowed additional attributed provided as options alongside the specifically allowed ones. :cvar item_type: the item type of this class. Defaults to a BUTTON. """ _allowed_attributes = [ "displayText_nl", "displayText_en", "displayText_de", "displayText_fr", "displayText_it", "actionButtonName_nl", "actionButtonName_en", "actionButtonName_de", "actionButtonName_fr", "actionButtonName_it", ] _item_type = SidebarType.CARD def __init__( self, side_bar_manager: "SideBarManager", json: Optional[Dict] = None, alignment: SidebarItemAlignment = SidebarItemAlignment.TOP, minimum_access_level: SidebarAccessLevelOptions = SidebarAccessLevelOptions.IS_MEMBER, maximum_access_level: SidebarAccessLevelOptions = SidebarAccessLevelOptions.IS_MANAGER, display_text: str = None, show_close_action: bool = True, show_background: bool = True, show_action_button: bool = False, action_button_name: Optional[str] = None, action_button_uri: Optional[str] = None, action_button_uri_target: Optional[str] = None, display_text_align: Optional[Alignment] = Alignment.CENTER, **kwargs: dict, ) -> None: """ Create a side-bar card. :param side_bar_manager: Manager object to which the button is linked. :param json: the json response to construct the :class:`SideBarButton` from :param title: visible label of the button :param icon: FontAwesome icon of the button :param uri: Uniform Resource Identifier, the address of the linked page :param uri_target: type of URI, either internal or external :param alignment: alignment of the button top or bottom :param minimum_access_level: the minimum permission needed to see the button :param maximum_access_level: the maximum permission needed to see the button :param icon_mode: FontAwesome display mode of the icon :returns None :raises IllegalArgumentError: When the provided Argument is not according to the type. """ super().__init__() if json is None: json = {} self._manager: "SideBarManager" = side_bar_manager self.align = json.get("align", alignment) self.minimum_access_level = json.get("minimumAccessLevel", minimum_access_level) self.maximum_access_level = json.get("maximumAccessLevel", maximum_access_level) self.display_text = json.get("displayText", display_text) self.display_text_align = json.get("displayTextAlign", display_text_align) self.show_close_action = json.get("showCloseaction", show_close_action) self.show_background = json.get("showBackground", show_background) self.show_action_button = json.get("showActionButton", show_action_button) self.action_button_name = json.get("actionButtonName", action_button_name) self.action_button_uri = json.get("actionButtonUri", action_button_uri) self.action_button_uri_target = json.get( "actionButtonUriTarget", action_button_uri_target ) if ( self.action_button_uri_target is not None and self.action_button_uri_target not in URITarget.values() ): raise IllegalArgumentError( f'uri_target must be a URITarget option, "{self.action_button_uri_target}" is not.' ) if self.align not in SidebarItemAlignment.values(): raise IllegalArgumentError( f"alignment must be a proper `SidebarButtonAlgment` type, '{self.align} is not.'" ) for key in kwargs.keys(): if key not in self._allowed_attributes: raise IllegalArgumentError( f'Attribute "{key}" is not supported in the configuration of a side-bar' " card." ) self._other_attributes = kwargs for key in self._allowed_attributes: if key in json: self._other_attributes[key] = json[key] def as_dict(self) -> Dict: """ Retrieve the configuration data, or `meta`, of the side-bar button. :return: dictionary of the configuration data Example ------- ```{ "itemType": "CARD", "order": 5, "align": "top", "showCloseAction": true, "showActionButton": true, "actionButtonUri": "https://asdasdas", "actionButtonUriTarget": "_new", "actionButtonName": "Discover more", "displayText": "This project ...", "displayText_nl": "Dit project ...", "displayTextAlign": "left", "showBackground": true, "minimumAccessLevel": "is_member", "maximumAccessLevel": "is_supervisor", }``` """ config = { "itemType": self._item_type, "displayText": self.display_text, "displayTextAlign": self.display_text_align, "align": self.align, "minimumAccessLevel": self.minimum_access_level, "maximumAccessLevel": self.maximum_access_level, "showBackground": self.show_background, "showCloseAction": self.show_close_action, "showActionButton": self.show_action_button, "actionButtonName": self.action_button_name, "actionButtonUri": self.action_button_uri, "actionButtonUriTarget": self.action_button_uri_target, } config.update(self._other_attributes) config = {k: v for k, v in config.items() if v is not None} return config
class SideBarCard(SideBarItem): ''' Side-bar card class. Every side-bar can have one or more cards and is maintained as an object of this class. :cvar allowed_attributes: allowed additional attributed provided as options alongside the specifically allowed ones. :cvar item_type: the item type of this class. Defaults to a BUTTON. ''' def __init__( self, side_bar_manager: "SideBarManager", json: Optional[Dict] = None, alignment: SidebarItemAlignment = SidebarItemAlignment.TOP, minimum_access_level: SidebarAccessLevelOptions = SidebarAccessLevelOptions.IS_MEMBER, maximum_access_level: SidebarAccessLevelOptions = SidebarAccessLevelOptions.IS_MANAGER, display_text: str = None, show_close_action: bool = True, show_background: bool = True, show_action_button: bool = False, action_button_name: Optional[str] = None, action_button_uri: Optional[str] = None, action_button_uri_target: Optional[str] = None, display_text_align: Optional[Alignment] = Alignment.CENTER, **kwargs: dict, ) -> None: ''' Create a side-bar card. :param side_bar_manager: Manager object to which the button is linked. :param json: the json response to construct the :class:`SideBarButton` from :param title: visible label of the button :param icon: FontAwesome icon of the button :param uri: Uniform Resource Identifier, the address of the linked page :param uri_target: type of URI, either internal or external :param alignment: alignment of the button top or bottom :param minimum_access_level: the minimum permission needed to see the button :param maximum_access_level: the maximum permission needed to see the button :param icon_mode: FontAwesome display mode of the icon :returns None :raises IllegalArgumentError: When the provided Argument is not according to the type. ''' pass def as_dict(self) -> Dict: ''' Retrieve the configuration data, or `meta`, of the side-bar button. :return: dictionary of the configuration data Example ------- ```{ "itemType": "CARD", "order": 5, "align": "top", "showCloseAction": true, "showActionButton": true, "actionButtonUri": "https://asdasdas", "actionButtonUriTarget": "_new", "actionButtonName": "Discover more", "displayText": "This project ...", "displayText_nl": "Dit project ...", "displayTextAlign": "left", "showBackground": true, "minimumAccessLevel": "is_member", "maximumAccessLevel": "is_supervisor", }``` ''' pass
3
3
60
5
37
19
5
0.51
1
9
5
0
2
13
2
7
147
16
87
36
68
44
35
20
32
8
1
2
9
140,726
KE-works/pykechain
KE-works_pykechain/pykechain/models/sidebar/sidebar_manager.py
pykechain.models.sidebar.sidebar_manager.SideBarManager
class SideBarManager(Iterable): """ Sidebar manager class. :ivar scope: Scope object for which the side-bar is managed. :ivar bulk_creation: boolean to create buttons in bulk, postponing updating of KE-chain until the manager is deleted from memory (end of your function) """ __existing_managers = ( dict() ) # storage of manager objects to enforce 1 manager object per Scope def __new__(cls, scope: "Scope", *args, **kwargs): """Overwrite superclass method to enforce singleton manager per Scope object.""" instance = super().__new__(cls) # Singleton manager per scope: this is required to support bulk_creation if scope.id in cls.__existing_managers: instance = cls.__existing_managers[scope.id] else: cls.__existing_managers[scope.id] = instance return instance def __init__(self, scope: "Scope", **kwargs): """ Create a side-bar manager object for the Scope object. :param scope: Scope for which to create the side-bar manager. :param bulk_creation: flag whether to update once (True) or continuously (False, default) """ super().__init__(**kwargs) from pykechain.models import Scope check_type(scope, Scope, "scope") self.scope: Scope = scope self._override: bool = scope.options.get("overrideSideBar", False) self._scope_uri = f"#/scopes/{self.scope.id}" self._perform_bulk_creation = False self._items: List[SideBarItem] = [] # Load existing buttons from the scope for item_dict in scope.options.get("customNavigation", []): if item_dict.get("itemType", SidebarType.BUTTON) == SidebarType.BUTTON: self._items.append(SideBarButton(side_bar_manager=self, json=item_dict)) elif item_dict.get("itemType") == SidebarType.CARD: self._items.append(SideBarCard(side_bar_manager=self, json=item_dict)) self._iter = iter(self._items) def __repr__(self) -> str: # pragma: no cover return f"<pyke {self.__class__.__name__}: {self.__len__()} items>" def __iter__(self): return self def __len__(self) -> int: return len(self._items) def __next__(self) -> SideBarItem: return next(self._iter) def __getitem__(self, key: Any) -> SideBarItem: found = None if isinstance(key, SideBarItem): found = find(self._items, lambda b: b == key) if isinstance(key, int): found = self._items[key] elif isinstance(key, str): found = find(self._items, lambda p: key == p.display_name) if found is not None: return found raise NotFoundError(f"Could not find button with index or name '{key}'") def __enter__(self): """ Open context manager using the `with` keyword to postpone updates to KE-chain. >>> with scope.side_bar() as manager: >>> button = manager.add_ke_chain_page(page_name=KEChainPages.EXPLORER) >>> manager.insert(index=0, button=button) """ self._perform_bulk_creation = True return self def __exit__(self, exc_type, exc_val, exc_tb): self._perform_bulk_creation = False self._update() def refresh(self) -> None: """Reload the scope options from KE-chain to refresh the side-bar data.""" self.scope.refresh() self.__init__(scope=self.scope) def remove(self, key: Any) -> None: """ Remove a button from the side-bar. :param key: either a button, index, or name. :returns None """ self.delete_button(key=key) def insert(self, index: int, button: SideBarItem) -> None: """ Place a button at index `index` of the button-list. :param index: location index of the new button :param button: a side-bar button object """ if button in self._items: self._items.remove(button) self._items.insert(check_type(index, int, "index"), button) def create_card(self, order: Optional[int] = None, *args, **kwargs) -> SideBarCard: """Create a side bar card. :param order: Optional input to specify where the button is injected in the list of items. :return: new side-bar card """ if order is None: index = len(self._items) else: index = check_type(order, int, "order") card = SideBarCard(side_bar_manager=self, *args, **kwargs) # insert the button on a certain position in the list of items. self._items.insert(index, card) self._update() return card def create_button( self, order: Optional[int] = None, *args, **kwargs ) -> SideBarButton: """ Create a side-bar button. :param order: Optional input to specify where the button is injected in the list of items. :return: new side-bar button """ if order is None: index = len(self._items) else: index = check_type(order, int, "order") button = SideBarButton(side_bar_manager=self, *args, **kwargs) # insert the button on a certain position in the list of items. self._items.insert(index, button) self._update() return button def add_task_button( self, activity: "Activity", title: Optional[str] = None, task_display_mode: Optional[ SubprocessDisplayMode ] = SubprocessDisplayMode.ACTIVITIES, *args, **kwargs, ) -> SideBarButton: """ Add a side-bar button to a KE-chain activity. :param activity: Activity object :param title: Title of the side-bar button, defaults to the activity name :param task_display_mode: for sub-processes, vary the display mode in KE-chain :return: new side-bar button """ from pykechain.models import Activity check_type(activity, Activity, "activity") check_enum(task_display_mode, SubprocessDisplayMode, "task_display_mode") title = check_text(title, "title") or activity.name uri = f"{self._scope_uri}/{task_display_mode}/{activity.id}" uri_target = ( URITarget.INTERNAL if activity.scope_id == self.scope.id else URITarget.EXTERNAL ) return self.create_button( uri=uri, uri_target=uri_target, title=title, *args, **kwargs ) def add_ke_chain_page( self, page_name: KEChainPages, title: Optional[str] = None, *args, **kwargs ) -> SideBarButton: """ Add a side-bar button to a built-in KE-chain page. :param page_name: name of the KE-chain page :param title: Title of the side-bar button, defaults to the page_name :return: new side-bar button """ page_name = check_enum(page_name, KEChainPages, "page_name") title = check_text(title, "title") or KEChainPageLabels[page_name] icon = KEChainPageIcons[page_name] if "icon" in kwargs: icon = kwargs.pop("icon") uri = f"{self._scope_uri}/{page_name}" return self.create_button( uri=uri, uri_target=URITarget.INTERNAL, title=title, icon=icon, *args, **kwargs, ) def add_external_button( self, url: str, title: str, *args, **kwargs ) -> SideBarButton: """ Add a side-bar button to an external page defined by an URL. :param title: title of the button :param url: URL to an external page :return: new side-bar button """ button = self.create_button( title=check_text(title, "title"), uri=check_url(url), uri_target=URITarget.EXTERNAL, *args, **kwargs, ) return button def add_buttons( self, buttons: List[Dict], override_sidebar: bool ) -> List[SideBarItem]: """ Create a list of buttons in bulk. Each button is defined by a dict, provided in a sorted list. :param buttons: list of dicts :param override_sidebar: whether to override the default sidebar menu items. :return: list of SideBarButton objects """ check_list_of_dicts(buttons, "buttons") check_type(override_sidebar, bool, "override_sidebar") for index, button in enumerate(buttons): button = SideBarButton(side_bar_manager=self, json=button) self._items.append(button) self.override_sidebar = override_sidebar self._update() return self._items def delete_button(self, key: Any) -> None: """ Similar to the `remove` method, deletes a button. :param key: either a button, index or name :return: None """ item = self[key] self._items.remove(item) self._update() @property def override_sidebar(self) -> bool: """ Flag to indicate whether the original KE-chain side-bar is still shown. :return: boolean, True if original side-bar is not visible """ return self._override @override_sidebar.setter def override_sidebar(self, value: bool) -> None: """ Flag to indicate whether the original KE-chain side-bar is still shown. :param value: new boolean value :return: None """ check_type(value, bool, "override_sidebar") self._override = value self._update() def _update(self) -> None: """ Update the side-bar using the scope.options attribute. :return: None """ if self._perform_bulk_creation: # Update will proceed during deletion of the manager. return options = dict(self.scope.options) custom_navigation = list() for item in self._items: custom_navigation.append(item.as_dict()) options.update( customNavigation=custom_navigation, overrideSideBar=self._override, ) self.scope.options = options
class SideBarManager(Iterable): ''' Sidebar manager class. :ivar scope: Scope object for which the side-bar is managed. :ivar bulk_creation: boolean to create buttons in bulk, postponing updating of KE-chain until the manager is deleted from memory (end of your function) ''' def __new__(cls, scope: "Scope", *args, **kwargs): '''Overwrite superclass method to enforce singleton manager per Scope object.''' pass def __init__(self, scope: "Scope", **kwargs): ''' Create a side-bar manager object for the Scope object. :param scope: Scope for which to create the side-bar manager. :param bulk_creation: flag whether to update once (True) or continuously (False, default) ''' pass def __repr__(self) -> str: pass def __iter__(self): pass def __len__(self) -> int: pass def __next__(self) -> SideBarItem: pass def __getitem__(self, key: Any) -> SideBarItem: pass def __enter__(self): ''' Open context manager using the `with` keyword to postpone updates to KE-chain. >>> with scope.side_bar() as manager: >>> button = manager.add_ke_chain_page(page_name=KEChainPages.EXPLORER) >>> manager.insert(index=0, button=button) ''' pass def __exit__(self, exc_type, exc_val, exc_tb): pass def refresh(self) -> None: '''Reload the scope options from KE-chain to refresh the side-bar data.''' pass def remove(self, key: Any) -> None: ''' Remove a button from the side-bar. :param key: either a button, index, or name. :returns None ''' pass def insert(self, index: int, button: SideBarItem) -> None: ''' Place a button at index `index` of the button-list. :param index: location index of the new button :param button: a side-bar button object ''' pass def create_card(self, order: Optional[int] = None, *args, **kwargs) -> SideBarCard: '''Create a side bar card. :param order: Optional input to specify where the button is injected in the list of items. :return: new side-bar card ''' pass def create_button( self, order: Optional[int] = None, *args, **kwargs ) -> SideBarButton: ''' Create a side-bar button. :param order: Optional input to specify where the button is injected in the list of items. :return: new side-bar button ''' pass def add_task_button( self, activity: "Activity", title: Optional[str] = None, task_display_mode: Optional[ SubprocessDisplayMode ] = SubprocessDisplayMode.ACTIVITIES, *args, **kwargs, ) -> SideBarButton: ''' Add a side-bar button to a KE-chain activity. :param activity: Activity object :param title: Title of the side-bar button, defaults to the activity name :param task_display_mode: for sub-processes, vary the display mode in KE-chain :return: new side-bar button ''' pass def add_ke_chain_page( self, page_name: KEChainPages, title: Optional[str] = None, *args, **kwargs ) -> SideBarButton: ''' Add a side-bar button to a built-in KE-chain page. :param page_name: name of the KE-chain page :param title: Title of the side-bar button, defaults to the page_name :return: new side-bar button ''' pass def add_external_button( self, url: str, title: str, *args, **kwargs ) -> SideBarButton: ''' Add a side-bar button to an external page defined by an URL. :param title: title of the button :param url: URL to an external page :return: new side-bar button ''' pass def add_buttons( self, buttons: List[Dict], override_sidebar: bool ) -> List[SideBarItem]: ''' Create a list of buttons in bulk. Each button is defined by a dict, provided in a sorted list. :param buttons: list of dicts :param override_sidebar: whether to override the default sidebar menu items. :return: list of SideBarButton objects ''' pass def delete_button(self, key: Any) -> None: ''' Similar to the `remove` method, deletes a button. :param key: either a button, index or name :return: None ''' pass @property def override_sidebar(self) -> bool: ''' Flag to indicate whether the original KE-chain side-bar is still shown. :return: boolean, True if original side-bar is not visible ''' pass @override_sidebar.setter def override_sidebar(self) -> bool: ''' Flag to indicate whether the original KE-chain side-bar is still shown. :param value: new boolean value :return: None ''' pass def _update(self) -> None: ''' Update the side-bar using the scope.options attribute. :return: None ''' pass
25
17
13
2
7
4
2
0.54
1
16
8
0
22
6
22
44
318
66
166
68
122
89
118
49
93
5
4
2
38
140,727
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/test_expiring_downloads.py
tests.test_expiring_downloads.TestExpiringDownloads
class TestExpiringDownloads(TestBetamax): def setUp(self): super().setUp() self.test_assets_dir = os.path.dirname( os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") ) self.test_content_path = os.path.join( self.test_assets_dir, "tests", "files", "test_upload_content_to_expiring_download", "test_upload_content.pdf", ) self.now = datetime.datetime.now() self.test_expiring_download = self.client.create_expiring_download( expires_in=56000, expires_at=datetime.datetime.now(), ) def tearDown(self): self.test_expiring_download.delete() super().tearDown() def test_create_expiring_download_with_content(self): content_path = os.path.join( self.test_assets_dir, "tests", "files", "test_upload_content_to_expiring_download", "test_upload_content.pdf", ) new_expiring_download = self.client.create_expiring_download( expires_at=datetime.datetime.now(), expires_in=42000, content_path=content_path, ) self.assertTrue(isinstance(new_expiring_download, ExpiringDownload)) new_expiring_download.delete() def test_retrieve_expiring_downloads(self): expiring_downloads = self.client.expiring_downloads() self.assertTrue(expiring_downloads) def test_update_expiring_download(self): self.test_expiring_download.edit(expires_in=42000) self.assertEqual(self.test_expiring_download.expires_in, 42000) def test_upload_expiring_download(self): upload_path = os.path.join( self.test_assets_dir, "tests", "files", "test_upload_content_to_expiring_download", "test_upload_content.pdf", ) self.test_expiring_download.upload(content_path=upload_path) self.assertIsNotNone(self.test_expiring_download.filename) self.assertEqual( self.test_expiring_download.filename, "test_upload_content.pdf" ) def test_upload_wrong_content_path(self): upload_path = os.path.join( self.test_assets_dir, "tests", "files", "test_upload_content_to_expiring_download", "test_upload_content.py", ) with self.assertRaises(OSError): self.test_expiring_download.upload(content_path=upload_path) @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, Downloads cannot be provided", ) def test_save_expiring_download_content(self): upload_path = os.path.join( self.test_assets_dir, "tests", "files", "test_upload_content_to_expiring_download", "test_upload_content.pdf", ) self.test_expiring_download.upload(content_path=upload_path) with temp_chdir() as target_dir: self.test_expiring_download.save_as(target_dir=target_dir) self.assertEqual(len(os.listdir(target_dir)), 1)
class TestExpiringDownloads(TestBetamax): def setUp(self): pass def tearDown(self): pass def test_create_expiring_download_with_content(self): pass def test_retrieve_expiring_downloads(self): pass def test_update_expiring_download(self): pass def test_upload_expiring_download(self): pass def test_upload_wrong_content_path(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, Downloads cannot be provided", ) def test_save_expiring_download_content(self): pass
10
0
10
0
10
0
1
0
1
4
1
0
8
4
8
83
89
8
81
24
68
0
36
19
27
1
3
1
8
140,728
KE-works/pykechain
KE-works_pykechain/pykechain/models/stored_file.py
pykechain.models.stored_file.StoredFile
class StoredFile( BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin ): """Stored File object.""" url_upload_name = "upload_stored_file" url_detail_name = "stored_file" url_list_name = "stored_files" url_pk_name = "file_id" def __init__(self, json, **kwargs): """Initialize a Stored File Object.""" super().__init__(json, **kwargs) self.category = json.get("category", "") self.classification = json.get("classification", "") self.content_type = json.get("content_type") self.description = json.get("description") self.file = json.get("file") self.name = json.get("name") def __repr__(self): # pragma: no cover return f"<pyke StoredFile '{self.name}' id {self.id[-8:]}>" @property def filename(self): """Filename of the file inside a StoredFile, without the full path.""" if self.file: if self.file.get("full_size"): return os.path.basename(self.file.get("full_size").split("?", 1)[0]) if self.file.get("source"): return os.path.basename(self.file.get("source").split("?", 1)[0]) return None def edit( self, name: str = Empty(), description: str = Empty(), scope: Union["Scope", ObjectID] = Empty(), category: StoredFileCategory = Empty(), classification: StoredFileClassification = Empty(), *args, **kwargs, ) -> None: """ Change the StoredFile object. Change the name, description, scope, category and classification of a StoredFile. :type name: name of the StoredFile is required. :type description: (optional) description of the StoredFile :type category: (optional) if left empty, it will not be affected :type classification: (optional) if left empty, it will not be affected :type scope: (optional) if left empty, it will not be affected """ from pykechain.models import Scope if isinstance(name, Empty): name = self.name data = { "name": check_text(name, "name"), "scope": check_base(scope, Scope, "scope"), "description": check_text(description, "description"), "category": check_enum(category, StoredFileCategory, "category"), "classification": check_enum( classification, StoredFileClassification, "classification" ), } url = self._client._build_url("stored_file", file_id=self.id) response = self._client._request( method="PATCH", url=url, json=clean_empty_values(data, nones=True), ) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError("Could not edit the stored file", response=response) self.refresh(json=response.json()["results"][0]) @classmethod def list(cls, client: "Client", **kwargs) -> List["StoredFile"]: """Retrieve a list of StoredFiles objects through the client.""" return super().list(client=client, **kwargs) @classmethod def get(cls, client: "Client", **kwargs) -> "StoredFile": """Retrieve a single StoredFile object using the client.""" return super().get(client=client, **kwargs) @classmethod def create( cls, client: "Client", name: str, filepath: str, scope: Union["Scope", ObjectID], category: StoredFileCategory = StoredFileCategory.GLOBAL, classification: StoredFileClassification = StoredFileClassification.GLOBAL, description: str = None, **kwargs, ) -> "StoredFile": """ Create a new StoredFile object using the client. :param client: Client object. :param name: Name of the StoredFile :param scope: Scope of the StoredFile :param filepath: mandatory, a StoredFile must have an attachment :param category: (optional) category of the StoredFile, defaults to StoredFileCategory.GLOBAL :param classification: (optional) classification of the StoredFile, defaults to StoredFileClassification.GLOBAL :param description: (optional) description of the StoredFile :param kwargs: (optional) additional kwargs. :return: a StoredFile object :raises APIError: When the StoredFile could not be created. """ from pykechain.models import Scope # avoiding circular imports here. data = { "name": check_text(name, "name"), "scope": check_base(scope, Scope, "scope"), "description": check_text(description, "description"), "category": check_enum(category, StoredFileCategory, "category"), "classification": check_enum( classification, StoredFileClassification, "classification" ), } if filepath and isinstance(filepath, str) and os.path.isfile(filepath): files = {"file": open(filepath, "rb")} elif filepath and isinstance(filepath, (bytes, bytearray, BytesIO)): files = {"file": filepath} else: files = {} kwargs.update(API_EXTRA_PARAMS[cls.url_upload_name]) response = client._request( method="POST", url=client._build_url(cls.url_upload_name), data=data, files=files, ) if response.status_code != requests.codes.created: # pragma: no cover raise APIError(f"Could not create {cls.__name__}", response=response) return cls(json=response.json()["results"][0], client=client) def delete(self): """Delete StoredFile.""" return super().delete() def upload(self, data: Any, **kwargs: Any) -> None: """ Upload a file to the StoredFile object. When providing a :class:`matplotlib.figure.Figure` object as data, the figure is uploaded as PNG. For this, `matplotlib`_ should be installed. :param data: File path :type data: basestring :raises APIError: When unable to upload the file to KE-chain :raises OSError: When the path to the file is incorrect or file could not be found . _matplotlib: https://matplotlib.org/ """ try: import matplotlib.figure if isinstance(data, matplotlib.figure.Figure): self._upload_plot(data, **kwargs) return except ImportError: pass if isinstance(data, str): with open(data, "rb") as fp: self._upload(data=fp) else: self._upload_json(data, **kwargs) def _upload_json(self, content, name="data.json"): data = (name, json.dumps(content), "application/json") self._upload(data=data) def _upload_plot(self, figure, name="plot.png"): buffer = io.BytesIO() figure.savefig(buffer, format="png") data = (name, buffer.getvalue(), "image/png") self._upload(data=data) self._value = name def _upload( self, data: Any, ): """ Upload a file to the StoredFile object. :param data: file object :type data: BufferedReader :raises APIError: When unable to upload the file to KE-chain :raises OSError: When the path to the file is incorrect or file could not be found """ files = {"file": data} response = self._client._request( method="PATCH", url=self._client._build_url(self.url_detail_name, file_id=self.id), files=files, ) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError("Could not upload file", response=response) self.refresh(json=response.json()["results"][0]) def save_as( self, filename: Optional[str] = None, size: StoredFileSize = StoredFileSize.FULL_SIZE, **kwargs, ) -> None: """Download the stored file attachment to a file. :param filename: (optional) File path. If not provided, will be saved to current working dir with `self.filename`. :type filename: basestring or None :param size: Size of file :type size: see enum.StoredFileSize :raises APIError: When unable to download the data :raises OSError: When unable to save the data to disk """ filename = filename or os.path.join(os.getcwd(), self.filename) with open(filename, "w+b") as f: for chunk in self._download(size=size, stream=True, **kwargs): f.write(chunk) def _download(self, size: StoredFileSize = StoredFileSize.SOURCE, **kwargs): """ Download the file as file object with an optional image size. Detects whether the content type falls under predefined image mime types and manages URL accordingly. Raises APIError if the download fails. When the file is not an image the 'source' file will be donwloaded. If the image size is not specified the full size image will be downloaded. :param size: Specifies the size of the file to be downloaded based :param kwargs: Additional keyword arguments :return: Response object of the download request as file descriptor :raises APIError: If the download request does not succeed """ if self.content_type in predefined_mimes["image/*"]: url = self.file.get(size, "full_size") else: url = self.file.get("source") # handle kwargs request_params = dict() do_stream = kwargs.pop("stream", False) if kwargs: request_params.update(**kwargs) response = requests.get(url, params=request_params, stream=do_stream) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError("Could not download property value.", response=response) return response def json_load(self): """Download the data from the storedfile and deserialise the contained json. :return: deserialised json data as :class:`dict` :raises APIError: When unable to retrieve the json from KE-chain :raises JSONDecodeError: When there was a problem in deserialising the json """ return self._download(size=StoredFileSize.SOURCE, stream=False).json()
class StoredFile( BaseInScope, CrudActionsMixin, TagsMixin, NameDescriptionTranslationMixin ): '''Stored File object.''' def __init__(self, json, **kwargs): '''Initialize a Stored File Object.''' pass def __repr__(self): pass @property def filename(self): '''Filename of the file inside a StoredFile, without the full path.''' pass def edit( self, name: str = Empty(), description: ''' Change the StoredFile object. Change the name, description, scope, category and classification of a StoredFile. :type name: name of the StoredFile is required. :type description: (optional) description of the StoredFile :type category: (optional) if left empty, it will not be affected :type classification: (optional) if left empty, it will not be affected :type scope: (optional) if left empty, it will not be affected ''' pass @classmethod def list(cls, client: "Client", **kwargs) -> List["StoredFile"]: '''Retrieve a list of StoredFiles objects through the client.''' pass @classmethod def get(cls, client: "Client", **kwargs) -> "StoredFile": '''Retrieve a single StoredFile object using the client.''' pass @classmethod def create( cls, client: "Client", name: str, filepath: str, scope: Union["Scope", ObjectID], category: StoredFileCategory = StoredFileCategory.GLOBAL, classification: StoredFileClassification = StoredFileClassification.GLOBAL, description: str = None, **kwargs, ) -> "StoredFile": ''' Create a new StoredFile object using the client. :param client: Client object. :param name: Name of the StoredFile :param scope: Scope of the StoredFile :param filepath: mandatory, a StoredFile must have an attachment :param category: (optional) category of the StoredFile, defaults to StoredFileCategory.GLOBAL :param classification: (optional) classification of the StoredFile, defaults to StoredFileClassification.GLOBAL :param description: (optional) description of the StoredFile :param kwargs: (optional) additional kwargs. :return: a StoredFile object :raises APIError: When the StoredFile could not be created. ''' pass def delete(self): '''Delete StoredFile.''' pass def upload(self, data: Any, **kwargs: Any) -> None: ''' Upload a file to the StoredFile object. When providing a :class:`matplotlib.figure.Figure` object as data, the figure is uploaded as PNG. For this, `matplotlib`_ should be installed. :param data: File path :type data: basestring :raises APIError: When unable to upload the file to KE-chain :raises OSError: When the path to the file is incorrect or file could not be found . _matplotlib: https://matplotlib.org/ ''' pass def _upload_json(self, content, name="data.json"): pass def _upload_plot(self, figure, name="plot.png"): pass def _upload_json(self, content, name="data.json"): ''' Upload a file to the StoredFile object. :param data: file object :type data: BufferedReader :raises APIError: When unable to upload the file to KE-chain :raises OSError: When the path to the file is incorrect or file could not be found ''' pass def save_as( self, filename: Optional[str] = None, size: StoredFileSize = StoredFileSize.FULL_SIZE, **kwargs, ) -> None: '''Download the stored file attachment to a file. :param filename: (optional) File path. If not provided, will be saved to current working dir with `self.filename`. :type filename: basestring or None :param size: Size of file :type size: see enum.StoredFileSize :raises APIError: When unable to download the data :raises OSError: When unable to save the data to disk ''' pass def _download(self, size: StoredFileSize = StoredFileSize.SOURCE, **kwargs): ''' Download the file as file object with an optional image size. Detects whether the content type falls under predefined image mime types and manages URL accordingly. Raises APIError if the download fails. When the file is not an image the 'source' file will be donwloaded. If the image size is not specified the full size image will be downloaded. :param size: Specifies the size of the file to be downloaded based :param kwargs: Additional keyword arguments :return: Response object of the download request as file descriptor :raises APIError: If the download request does not succeed ''' pass def json_load(self): '''Download the data from the storedfile and deserialise the contained json. :return: deserialised json data as :class:`dict` :raises APIError: When unable to retrieve the json from KE-chain :raises JSONDecodeError: When there was a problem in deserialising the json ''' pass
20
13
17
2
10
5
2
0.5
4
12
5
0
12
8
15
31
283
46
162
82
110
81
96
46
77
4
2
2
31
140,729
KE-works/pykechain
KE-works_pykechain/pykechain/models/user.py
pykechain.models.user.User
class User(Base): """A virtual object representing a KE-chain user. :ivar username: username of the user :type username: str :ivar name: username of the user (compatibility) :type name: str :ivar id: userid of the user :type id: int :ivar timezone: timezone of the User (defaults to <UTC>) :type timezone: timezone object :ivar language: language of the User (defaults to 'en') :type language: str :ivar email: email of the User (defaults to '') :type email: str """ def __init__(self, json, **kwargs): """Construct a user from provided json data.""" super().__init__(json, **kwargs) self.username = self._json_data.get("username", "") self.id = self._json_data.get("pk", "") def __repr__(self): # pragma: no cover return f"<pyke {self.__class__.__name__} '{self.username}' id {self.id}>" @property def default_name(self) -> str: """ Get default name, prioritizing the user name over the KE-chain name. :return: Name :rtype str """ return self.username if self.username else self.name @property def timezone(self) -> pytz.BaseTzInfo: """ Timezone of the user. Defaults to timezone UTC. With return a pytz timezone eg. 'Europe/Amsterdam' :return: timezone object (compatible with datetime) :rtype: TzInfo """ return pytz.timezone(zone=self._json_data.get("timezone", "UTC")) @property def language(self) -> str: """ Language code of the user. Defaults to English ('en") when no language code is configured. :return: language code string :rtype: basestring """ return self._json_data.get("language_code", LanguageCodes.ENGLISH) @property def email(self) -> str: """ Email of the user. :return: email address, default is empty string. :rtype: basestring """ return self._json_data.get("email", "") def reset_password(self) -> None: """Send a request password link to the email of the user. curl 'https://pim3-test.ke-chain.com/accounts/password/reset/' \ --data-raw '{"email":"hostmaster+newuser@ke-works.com"}' \ """ payload = {"email": self.email} response = self._client._request( "POST", url=self._client._build_url("user_reset_password"), json=payload ) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError( f"Could not request a reset password link for '{self}'", response=response, ) def now_in_my_timezone(self) -> datetime.datetime: """ Get current time in the timezone of the User. Defaults to timezone GMT+1 (Europe/Amsterdam). :return: Current datetime :rtype datetime.datetime """ timezone_definition = self._json_data["timezone"] if timezone_definition: timezone = pytz.timezone(timezone_definition) else: # if there is no timezone set then the Europe/Amsterdam timezone timezone = pytz.timezone("Europe/Amsterdam") # Default is utc timezone utc_time = datetime.datetime.now(tz=pytz.utc) # Convert to local timezone local_time = utc_time.astimezone(timezone) return local_time
class User(Base): '''A virtual object representing a KE-chain user. :ivar username: username of the user :type username: str :ivar name: username of the user (compatibility) :type name: str :ivar id: userid of the user :type id: int :ivar timezone: timezone of the User (defaults to <UTC>) :type timezone: timezone object :ivar language: language of the User (defaults to 'en') :type language: str :ivar email: email of the User (defaults to '') :type email: str ''' def __init__(self, json, **kwargs): '''Construct a user from provided json data.''' pass def __repr__(self): pass @property def default_name(self) -> str: ''' Get default name, prioritizing the user name over the KE-chain name. :return: Name :rtype str ''' pass @property def timezone(self) -> pytz.BaseTzInfo: ''' Timezone of the user. Defaults to timezone UTC. With return a pytz timezone eg. 'Europe/Amsterdam' :return: timezone object (compatible with datetime) :rtype: TzInfo ''' pass @property def language(self) -> str: ''' Language code of the user. Defaults to English ('en") when no language code is configured. :return: language code string :rtype: basestring ''' pass @property def email(self) -> str: ''' Email of the user. :return: email address, default is empty string. :rtype: basestring ''' pass def reset_password(self) -> None: '''Send a request password link to the email of the user. curl 'https://pim3-test.ke-chain.com/accounts/password/reset/' --data-raw '{"email":"hostmaster+newuser@ke-works.com"}' ''' pass def now_in_my_timezone(self) -> datetime.datetime: ''' Get current time in the timezone of the User. Defaults to timezone GMT+1 (Europe/Amsterdam). :return: Current datetime :rtype datetime.datetime ''' pass
13
8
10
2
4
5
1
1.39
1
6
2
0
8
2
8
13
111
22
38
21
25
53
28
17
19
2
1
1
11
140,730
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/effects.py
pykechain.models.validators.effects.ErrorTextEffect
class ErrorTextEffect(ValidatorEffect): """A Errortext effect, that will set a text. .. versionadded:: 2.2 """ effect = ValidatorEffectTypes.ERRORTEXT_EFFECT def __init__( self, json=None, text="The validation resulted in an error.", **kwargs ): """Construct an errortext effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param text: (optional) text to provide, default empty :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict """ super().__init__(json=json, **kwargs)
class ErrorTextEffect(ValidatorEffect): '''A Errortext effect, that will set a text. .. versionadded:: 2.2 ''' def __init__( self, json=None, text="The validation resulted in an error.", **kwargs ): '''Construct an errortext effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param text: (optional) text to provide, default empty :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict ''' pass
2
2
13
1
4
8
1
1.83
1
1
0
0
1
0
1
9
21
4
6
5
2
11
4
3
2
1
2
0
1
140,731
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/effects.py
pykechain.models.validators.effects.HelpTextEffect
class HelpTextEffect(ValidatorEffect): """A Errortext effect, that will set a text. .. versionadded:: 2.2 """ effect = ValidatorEffectTypes.HELPTEXT_EFFECT def __init__(self, json=None, text="", **kwargs): """Construct an helptext effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param text: (optional) text to provide, default empty :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict """ super().__init__(json=json, text=text, **kwargs)
class HelpTextEffect(ValidatorEffect): '''A Errortext effect, that will set a text. .. versionadded:: 2.2 ''' def __init__(self, json=None, text="", **kwargs): '''Construct an helptext effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param text: (optional) text to provide, default empty :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict ''' pass
2
2
11
1
2
8
1
2.75
1
1
0
0
1
0
1
9
19
4
4
3
2
11
4
3
2
1
2
0
1
140,732
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/effects.py
pykechain.models.validators.effects.InvalidVisualEffect
class InvalidVisualEffect(VisualEffect): """Effect that may apply a css class when the result of the validator is invalid. .. versionadded:: 2.2 """ def __init__(self, json=None, applyCss="invalid", **kwargs): """Construct an invalid visual effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param applyCss: (optional) class to apply, defaults to 'invalid' :type applyCss: basestring """ super().__init__(json=json, applyCss=applyCss, **kwargs)
class InvalidVisualEffect(VisualEffect): '''Effect that may apply a css class when the result of the validator is invalid. .. versionadded:: 2.2 ''' def __init__(self, json=None, applyCss="invalid", **kwargs): '''Construct an invalid visual effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param applyCss: (optional) class to apply, defaults to 'invalid' :type applyCss: basestring ''' pass
2
2
9
1
2
6
1
3
1
1
0
0
1
0
1
11
15
3
3
2
1
9
3
2
1
1
3
0
1
140,733
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/effects.py
pykechain.models.validators.effects.TextEffect
class TextEffect(ValidatorEffect): """A Text effect, that will set a text. .. versionadded:: 2.2 """ effect = ValidatorEffectTypes.TEXT_EFFECT def __init__( self, json=None, text="The validation resulted in an error.", **kwargs ): """Construct an helptext effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param text: (optional) text to provide, default empty :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict """ super().__init__(json=json, text=text, **kwargs) self.text = text def as_json(self) -> dict: """Represent effect as JSON dict.""" self._config["text"] = self.text return self._json
class TextEffect(ValidatorEffect): '''A Text effect, that will set a text. .. versionadded:: 2.2 ''' def __init__( self, json=None, text="The validation resulted in an error.", **kwargs ): '''Construct an helptext effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param text: (optional) text to provide, default empty :type text: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict ''' pass def as_json(self) -> dict: '''Represent effect as JSON dict.''' pass
3
3
9
1
4
5
1
1.2
1
2
0
0
2
1
2
10
27
5
10
7
5
12
8
5
5
1
2
0
2
140,734
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/effects.py
pykechain.models.validators.effects.ValidVisualEffect
class ValidVisualEffect(VisualEffect): """Effect that may apply a css class when the result of the validator is valid. .. versionadded:: 2.2 """ def __init__(self, json=None, applyCss="valid", **kwargs): """Construct an valid visual effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param applyCss: (optional) class to apply, defaults to 'valid' :type applyCss: basestring """ super().__init__(json=json, applyCss=applyCss, **kwargs)
class ValidVisualEffect(VisualEffect): '''Effect that may apply a css class when the result of the validator is valid. .. versionadded:: 2.2 ''' def __init__(self, json=None, applyCss="valid", **kwargs): '''Construct an valid visual effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param applyCss: (optional) class to apply, defaults to 'valid' :type applyCss: basestring ''' pass
2
2
9
1
2
6
1
3
1
1
0
0
1
0
1
11
15
3
3
2
1
9
3
2
1
1
3
0
1
140,735
KE-works/pykechain
KE-works_pykechain/pykechain/models/validators/effects.py
pykechain.models.validators.effects.VisualEffect
class VisualEffect(ValidatorEffect): """A visualeffect, to be processed by the frontend. .. versionadded:: 2.2 :ivar applyCss: css class to apply in case of this effect """ effect = ValidatorEffectTypes.VISUALEFFECT def __init__(self, json=None, applyCss=None, **kwargs): """Construct an visual effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param applyCss: (optional) class to apply, defaults to 'valid' :type applyCss: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict """ super().__init__(json=json, **kwargs) self.applyCss = applyCss or self._config.get("applyCss") def as_json(self) -> dict: """Represent effect as JSON dict.""" self._config["applyCss"] = self.applyCss self._json["config"] = self._config return self._json
class VisualEffect(ValidatorEffect): '''A visualeffect, to be processed by the frontend. .. versionadded:: 2.2 :ivar applyCss: css class to apply in case of this effect ''' def __init__(self, json=None, applyCss=None, **kwargs): '''Construct an visual effect. :param json: (optional) dict (json) object to construct the object from :type json: dict :param applyCss: (optional) class to apply, defaults to 'valid' :type applyCss: basestring :param kwargs: (optional) additional kwargs to pass down :type kwargs: dict ''' pass def as_json(self) -> dict: '''Represent effect as JSON dict.''' pass
3
3
9
1
4
5
1
1.44
1
2
0
2
2
1
2
10
28
6
9
5
6
13
9
5
6
1
2
0
2
140,736
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/test_stored_file.py
tests.test_stored_file.TestStoredFilesUpload
class TestStoredFilesUpload(TestStoredFilesBaseTestCase): def setUp(self): super().setUp() self.test_json_file_name = "test_upload_json.json" self.test_figure_file_name = "test_upload_plot.png" def tearDown(self): super().tearDown() def test_upload_file_on_top_of_an_already_existing_one(self): self.stored_pdf_file.upload(data=self.upload_image_path) self.assertEqual(self.stored_pdf_file.filename, self.image_file_name) self.assertEqual(self.stored_pdf_file.content_type, "image/jpeg") def test_upload_json_data_to_stored_file(self): test_dict = {"a": 1, "b": 3} json_data = ( self.test_json_file_name, json.dumps(test_dict), "application/json", ) self.stored_pdf_file.upload( data=json_data, name=self.test_json_file_name) self.assertEqual(self.stored_pdf_file.filename, self.test_json_file_name) self.assertEqual(self.stored_pdf_file.content_type, "application/octet-stream") @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_upload_plot_to_stored_file(self): import matplotlib.pyplot as plt from matplotlib import lines fig = plt.figure() fig.add_artist(lines.Line2D([0, 1, 0.5], [0, 1, 0.3])) fig.add_artist(lines.Line2D([0, 1, 0.5], [1, 0, 0.2])) self.stored_pdf_file.upload(data=fig, name=self.test_figure_file_name) self.assertEqual(self.stored_pdf_file.filename, self.test_figure_file_name) self.assertEqual(self.stored_pdf_file.content_type, "image/png")
class TestStoredFilesUpload(TestStoredFilesBaseTestCase): def setUp(self): pass def tearDown(self): pass def test_upload_file_on_top_of_an_already_existing_one(self): pass def test_upload_json_data_to_stored_file(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_upload_plot_to_stored_file(self): pass
7
0
7
1
6
0
1
0
1
1
0
0
5
2
5
82
43
9
34
17
22
0
26
13
18
1
4
0
5
140,737
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/test_services.py
tests.test_services.TestServices
class TestServices(TestBetamax): def _create_service(self, name=None): """Creates a service with name, and adds a test_upload_script.py (debugging)""" # setUp new_service = self.project.create_service( name=name or "Test upload script to service", description="Only used for testing - you can safely remove this", ) upload_path = os.path.join( self.test_assets_dir, "tests", "files", "uploaded", "test_upload_script.py" ) # testing new_service.upload(pkg_path=upload_path) new_service.refresh() self.assertEqual( new_service._json_data["script_file_name"], "test_upload_script.py" ) return new_service def setUp(self): super().setUp() self.test_assets_dir = os.path.dirname( os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") ) def test_retrieve_services(self): self.assertTrue(self.project.services()) def test_retrieve_services_with_kwargs(self): # setUp retrieved_services_with_kwargs = self.project.services( script_type=ServiceType.PYTHON_SCRIPT ) # testing self.assertTrue(retrieved_services_with_kwargs) for service in retrieved_services_with_kwargs: self.assertEqual( ServiceType.PYTHON_SCRIPT, service._json_data["script_type"] ) def test_retrieve_service_but_found_multiple(self): with self.assertRaises(MultipleFoundError): self.project.service(script_type=ServiceType.PYTHON_SCRIPT) def test_retrieve_single_service(self): services = self.project.services() self.assertTrue(services) service_1 = services[0] self.assertEqual(self.project.service(pk=service_1.id), service_1) def test_retrieve_service_by_name(self): service_name = "Service Gears - Successful" service = self.project.service(name=service_name) self.assertTrue(service) self.assertEqual(service.name, service_name) def test_properties_of_service(self): service_name = "Service Gears - Successful with Package" service = self.project.service(name=service_name) for key, value in service.__dict__.items(): if str(key).startswith("_"): continue # Verified on is an optional variable if key == "verified_on": continue with self.subTest(msg=f"{key}: {value}"): self.assertIsNotNone(value) @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_debug_service_execute(self): service_name = "Service Gears - Successful" service = self.project.service(name=service_name) service_execution = service.execute() self.assertTrue( service_execution.status in ServiceExecutionStatus.values()) if service_execution.status in ( ServiceExecutionStatus.LOADING, ServiceExecutionStatus.RUNNING, ): # sleep 2000 ms time.sleep(2) service_execution.refresh() self.assertTrue( service_execution.status in ServiceExecutionStatus.values()) @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_service_context(self): some_activity = self.project.activities()[0] service = self.project.service(name="Service Gears - Successful") service_execution = service.execute(activity_id=some_activity.id) self.assertEqual(some_activity.id, service_execution.activity_id) def test_update_service(self): # setUp service_name = "Service Gears - Successful" service = self.project.service(name=service_name) version_before = str(service.version) name_before = service_name name_after = "Pykechain needs no debugging" description_before = str(service._json_data["description"]) description_after = "Pykechain is way too good for that" version_after = "-latest" # testing service.edit( name=name_after, description=description_after, version=version_after ) service.refresh() self.assertEqual(service.name, name_after) self.assertEqual(service._json_data["description"], description_after) self.assertEqual(service.version, version_after) # tearDown service.edit( name=name_before, description=description_before, version=version_before ) @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_edit_service_clear_values(self): # setup initial_name = "Service testing editing" initial_description = "Description test" initial_version = "1.0" initial_run_as = "kenode" initial_trusted = False initial_type = ServiceType.PYTHON_SCRIPT initial_env = ServiceEnvironmentVersion.PYTHON_3_12 self.service = self.project.create_service(name=initial_name) self.service.edit( name=initial_name, description=initial_description, version=initial_version, type=initial_type, environment_version=initial_env, run_as=initial_run_as, trusted=initial_trusted, ) # Edit without mentioning values, everything should stay the same new_name = "Changed service name" self.service.edit(name=new_name) # testing self.assertEqual(self.service.name, new_name) self.assertEqual(self.service.description, initial_description) self.assertEqual(self.service.version, initial_version) self.assertEqual(self.service.run_as, initial_run_as) self.assertEqual(self.service.type, initial_type) self.assertEqual(self.service.environment, initial_env) self.assertEqual(self.service.trusted, initial_trusted) # Edit with clearing the values, name and status cannot be cleared self.service.edit( name=None, description=None, version=None, type=None, environment_version=None, run_as=None, trusted=None, ) self.assertEqual(self.service.name, new_name) self.assertEqual(self.service.description, "") self.assertEqual(self.service.version, "") self.assertEqual(self.service.type, initial_type) self.assertEqual(self.service.environment, initial_env) self.assertEqual(self.service.run_as, initial_run_as) self.assertEqual(self.service.trusted, initial_trusted) # teardown self.service.delete() # test added in 3.1 def test_retrieve_services_with_refs(self): # setup service_ref = "service-gears-successful" service_name = "Service Gears - Successful" service = self.project.service(ref=service_ref) # testing self.assertIsInstance(service, Service) self.assertTrue(service.name, service_name)
class TestServices(TestBetamax): def _create_service(self, name=None): '''Creates a service with name, and adds a test_upload_script.py (debugging)''' pass def setUp(self): pass def test_retrieve_services(self): pass def test_retrieve_services_with_kwargs(self): pass def test_retrieve_service_but_found_multiple(self): pass def test_retrieve_single_service(self): pass def test_retrieve_service_by_name(self): pass def test_properties_of_service(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_debug_service_execute(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_service_context(self): pass def test_update_service(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_edit_service_clear_values(self): pass def test_retrieve_services_with_refs(self): pass
17
1
13
1
11
1
1
0.12
1
6
4
0
13
2
13
88
201
31
152
64
126
18
104
52
90
4
3
2
18
140,738
KE-works/pykechain
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KE-works_pykechain/tests/test_services.py
tests.test_services.TestServiceExecutions
class TestServiceExecutions(TestServiceSetup): def test_retrieve_service_executions(self): self.assertTrue(self.project.service_executions()) def test_retrieve_service_executions_with_kwargs(self): # setUp limit = 15 retrieved_executions_with_kwargs = self.project.service_executions( limit=limit) # testing self.assertTrue(len(retrieved_executions_with_kwargs) <= limit) def test_retrieve_single_service_execution(self): service_executions = self.project.service_executions() self.assertTrue(service_executions) service_execution_1 = service_executions[0] self.assertEqual( self.project.service_execution(pk=service_execution_1.id), service_execution_1, ) def test_retrieve_single_service_execution_but_found_none(self): with self.assertRaises(NotFoundError): self.project.service_execution( username="No service execution as this user does not exist" ) def test_retrieve_single_service_execution_but_found_multiple(self): # setUp service_execution = self.service.execute() while service_execution.status in [ ServiceExecutionStatus.LOADING, ServiceExecutionStatus.RUNNING, ]: time.sleep(0.500) # 200ms service_execution.refresh() self.service.execute() # testing with self.assertRaises(MultipleFoundError): self.project.service_execution(service=self.service.id) def test_service_execution_conflict(self): # setUp self.service.execute() # testing with self.assertRaisesRegex(APIError, "Conflict: Could not execute"): self.service.execute() def test_properties_of_service_execution(self): service_name = "Service Gears - Successful" service = self.project.service(name=service_name) service_executions = self.project.service_executions( service=service.id, limit=1 ) self.assertTrue(service_executions) service_execution = service_executions[0] self.assertIsInstance(service_execution.service, Service) self.assertIsInstance(service_execution.started_at, datetime) self.assertIsInstance(service_execution.finished_at, datetime) for key, value in service_execution.__dict__.items(): if str(key).startswith("_"): continue # Originating activity is an optional variable if key == "activity_id" or key == "ref": continue with self.subTest(msg=f"{key}: {value}"): self.assertIsNotNone(value) @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_debug_service_execution_terminate(self): service_execution = self.service.execute() self.assertEqual(service_execution.status, ServiceExecutionStatus.LOADING) time.sleep(2) service_execution.refresh() self.assertEqual(service_execution.status, ServiceExecutionStatus.RUNNING) service_execution.terminate() self.assertNotEqual( service_execution.status, ServiceExecutionStatus.FAILED, "The service execution is status 'FAILED', please upload working debugging scripts" " before running the tests", ) def test_log_of_service_execution(self): # setUp service_execution = self.service.execute() time.sleep(5) with temp_chdir() as target_dir: service_execution.get_log(target_dir=target_dir) log_file = os.path.join(target_dir, "log.txt") self.assertTrue(log_file)
class TestServiceExecutions(TestServiceSetup): def test_retrieve_service_executions(self): pass def test_retrieve_service_executions_with_kwargs(self): pass def test_retrieve_single_service_execution(self): pass def test_retrieve_single_service_execution_but_found_none(self): pass def test_retrieve_single_service_execution_but_found_multiple(self): pass def test_service_execution_conflict(self): pass def test_properties_of_service_execution(self): pass @pytest.mark.skipif( "os.getenv('TRAVIS', False) or os.getenv('GITHUB_ACTIONS', False)", reason="Skipping tests when using Travis or Github Actions, as not Auth can be provided", ) def test_debug_service_execution_terminate(self): pass def test_log_of_service_execution(self): pass
11
0
10
1
8
1
1
0.12
1
6
4
0
9
0
9
87
106
21
77
28
63
9
58
23
48
4
4
2
13
140,739
KE-works/pykechain
KE-works_pykechain/pykechain/models/team.py
pykechain.models.team.Team
class Team(Base): """A virtual object representing a KE-chain Team. :ivar name: team name :ivar id: uuid of the team """ def __init__(self, json, **kwargs): """Construct a team from provided json data.""" super().__init__(json, **kwargs) self.ref = json.get("ref") self.description = json.get("description") self.options = json.get("options") self.is_hidden = json.get("is_hidden") def _update(self, resource, update_dict=None, params=None, **kwargs): """Update the team in-place.""" url = self._client._build_url(resource, **kwargs) response = self._client._request("PUT", url, json=update_dict, params=params) if response.status_code != requests.codes.ok: # pragma: no cover raise APIError(f"Could not update Team {self}", response=response) self.refresh(json=response.json().get("results")[0]) def edit( self, name: Optional[Union[str, Empty]] = empty, description: Optional[Union[str, Empty]] = empty, options: Optional[Union[Dict, Empty]] = empty, is_hidden: Optional[Union[bool, Empty]] = empty, **kwargs, ) -> None: """ Edit the attributes of the Team. :param name: (o) name of the Team :type name: str :param description: (o) description of the Team :type description: str :param options: (o) options dictionary to set attributes such as `landingPage`. :type options: dict :param is_hidden: flag to hide the Team :type is_hidden: bool :return: None :raises IllegalArgumentError whenever inputs are not of the correct type """ update_dict = { "id": self.id, "name": check_text(name, "name") or self.name, "description": check_text(description, "description"), "options": check_type(options, dict, "options"), "is_hidden": check_type(is_hidden, bool, "is_hidden"), } if kwargs: # pragma: no cover update_dict.update(kwargs) update_dict = clean_empty_values(update_dict=update_dict) self._update(resource="team", team_id=self.id, update_dict=update_dict) def delete(self) -> None: """ Delete the team. Members of the team remain intact. :return: None """ url = self._client._build_url(resource="team", team_id=self.id) response = self._client._request("DELETE", url=url) if response.status_code != requests.codes.no_content: # pragma: no cover raise APIError(f"Could not delete Team {self}", response=response) def members(self, role: Optional[Union[TeamRoles, str]] = None) -> List[Dict]: """Members of the team. You may provide the role in the team, to retrieve only the team member with that role. Normally there is a single owner, that has administration rights of the team. Normal team members do not have any rights to administer the team itself such as altering the team name, team image and team members. Administrators do have the right to administer the the team members. :param role: (optional) member belonging to a role :class:`pykechain.enums.TeamRoles` to return. :type role: basestring or None :raises IllegalArgumentError: when providing incorrect roles :return: list of dictionaries with members (pk, username, role, email) Example ------- >>> my_team = client.team(name='My own team') >>> my_team.members() [{"pk":1, "username"="first user", "role"="OWNER", "email":"email@address.com"}, ...] """ check_enum(role, TeamRoles, "role") member_list = list(self._json_data.get("members")) if role: return [ teammember for teammember in member_list if teammember.get("role") == role ] else: return member_list def add_members( self, users: Optional[List[Union[User, str]]] = None, role: Optional[Union[TeamRoles, str]] = TeamRoles.MEMBER, ) -> None: """Members to add to a team. :param users: list of members, either `User` objects or usernames :type users: List of `User` or List of pk :param role: (optional) role of the users to add (default `TeamRoles.MEMBER`) :type role: basestring :raises IllegalArgumentError: when providing incorrect user information Example ------- >>> my_team = client.team(name='My own team') >>> other_user = client.users(name='That other person') >>> myself = client.users(name='myself') >>> my_team.add_members([myself], role=TeamRoles.MANAGER) >>> my_team.add_members([other_user], role=TeamRoles.MEMBER) """ update_dict = { "role": check_enum(role, TeamRoles, "role"), "users": [check_user(user, User, "users") for user in users], } self._update("team_add_members", team_id=self.id, update_dict=update_dict) def remove_members(self, users: Optional[List[Union[User, str]]] = None) -> None: """ Remove members from the team. :param users: list of members, either `User` objects or usernames :type users: List of `User` or List of pk :raises IllegalArgumentError: when providing incorrect user information Example ------- >>> my_team = client.team(name='My own team') >>> other_user = client.users(name='That other person') >>> my_team.remove_members([other_user]) """ update_dict = {"users": [check_user(user, User, "users") for user in users]} self._update("team_remove_members", update_dict=update_dict, team_id=self.id) def scopes(self, status: Optional[ScopeStatus] = None, **kwargs) -> List["Scope"]: """Scopes associated to the team.""" return self._client.scopes(team=self.id, status=status, **kwargs)
class Team(Base): '''A virtual object representing a KE-chain Team. :ivar name: team name :ivar id: uuid of the team ''' def __init__(self, json, **kwargs): '''Construct a team from provided json data.''' pass def _update(self, resource, update_dict=None, params=None, **kwargs): '''Update the team in-place.''' pass def edit( self, name: Optional[Union[str, Empty]] = empty, description: Optional[Union[str, Empty]] = empty, options: Optional[Union[Dict, Empty]] = empty, is_hidden: Optional[Union[bool, Empty]] = empty, **kwargs, ) -> None: ''' Edit the attributes of the Team. :param name: (o) name of the Team :type name: str :param description: (o) description of the Team :type description: str :param options: (o) options dictionary to set attributes such as `landingPage`. :type options: dict :param is_hidden: flag to hide the Team :type is_hidden: bool :return: None :raises IllegalArgumentError whenever inputs are not of the correct type ''' pass def delete(self) -> None: ''' Delete the team. Members of the team remain intact. :return: None ''' pass def members(self, role: Optional[Union[TeamRoles, str]] = None) -> List[Dict]: '''Members of the team. You may provide the role in the team, to retrieve only the team member with that role. Normally there is a single owner, that has administration rights of the team. Normal team members do not have any rights to administer the team itself such as altering the team name, team image and team members. Administrators do have the right to administer the the team members. :param role: (optional) member belonging to a role :class:`pykechain.enums.TeamRoles` to return. :type role: basestring or None :raises IllegalArgumentError: when providing incorrect roles :return: list of dictionaries with members (pk, username, role, email) Example ------- >>> my_team = client.team(name='My own team') >>> my_team.members() [{"pk":1, "username"="first user", "role"="OWNER", "email":"email@address.com"}, ...] ''' pass def add_members( self, users: Optional[List[Union[User, str]]] = None, role: Optional[Union[TeamRoles, str]] = TeamRoles.MEMBER, ) -> None: '''Members to add to a team. :param users: list of members, either `User` objects or usernames :type users: List of `User` or List of pk :param role: (optional) role of the users to add (default `TeamRoles.MEMBER`) :type role: basestring :raises IllegalArgumentError: when providing incorrect user information Example ------- >>> my_team = client.team(name='My own team') >>> other_user = client.users(name='That other person') >>> myself = client.users(name='myself') >>> my_team.add_members([myself], role=TeamRoles.MANAGER) >>> my_team.add_members([other_user], role=TeamRoles.MEMBER) ''' pass def remove_members(self, users: Optional[List[Union[User, str]]] = None) -> None: ''' Remove members from the team. :param users: list of members, either `User` objects or usernames :type users: List of `User` or List of pk :raises IllegalArgumentError: when providing incorrect user information Example ------- >>> my_team = client.team(name='My own team') >>> other_user = client.users(name='That other person') >>> my_team.remove_members([other_user]) ''' pass def scopes(self, status: Optional[ScopeStatus] = None, **kwargs) -> List["Scope"]: '''Scopes associated to the team.''' pass
9
9
18
3
8
8
2
1.08
1
10
5
0
8
5
8
13
161
33
63
33
43
68
38
21
29
2
1
1
12
140,740
KE-works/pykechain
KE-works_pykechain/pykechain/models/representations/representations.py
pykechain.models.representations.representations.SignatureRepresentation
class SignatureRepresentation(SimpleConfigValueKeyRepresentation): """Representation for the signature input in a grid or propertygrid.""" rtype = PropertyRepresentation.SIGNATURE _config_value_key = PropertyRepresentation.SIGNATURE def validate_representation(self, value: Any) -> None: """ Validate whether the representation value can be set. :param value: representation value to set. :type value: Any :raises IllegalArgumentError :return: None """ check_enum( value, SignatureRepresentationValues, "signature representation values" )
class SignatureRepresentation(SimpleConfigValueKeyRepresentation): '''Representation for the signature input in a grid or propertygrid.''' def validate_representation(self, value: Any) -> None: ''' Validate whether the representation value can be set. :param value: representation value to set. :type value: Any :raises IllegalArgumentError :return: None ''' pass
2
2
12
1
4
7
1
1.14
1
2
1
0
1
0
1
10
18
3
7
4
5
8
5
4
3
1
2
0
1
140,741
KE-works/pykechain
KE-works_pykechain/tests/models/test_validators.py
tests.models.test_validators.TestValidatorParsing
class TestValidatorParsing(TestCase): def test_valid_numeric_range_validator_json(self): validator_json = dict( vtype="numericRangeValidator", config=dict( minvalue=2, maxvalue=10, stepsize=2, enforce_stepsize=False, on_valid=[dict(effect="visualEffect", config=dict(applyCss="valid"))], on_invalid=[ dict(effect="visualEffect", config=dict(applyCss="invalid")), dict( effect="errorTextEffect", config=dict( text="Range should be between 2 and 10 with step 2." ), ), ], ), ) validator = PropertyValidator.parse(validator_json) self.assertIsInstance(validator, NumericRangeValidator) self.assertTrue(validator.validate_json) pass
class TestValidatorParsing(TestCase): def test_valid_numeric_range_validator_json(self): pass
2
0
26
2
24
0
1
0
1
3
2
0
1
0
1
73
27
2
25
4
23
0
7
4
5
1
2
0
1
140,742
KE-works/pykechain
KE-works_pykechain/tests/test_activities.py
tests.test_activities.TestActivities
class TestActivities(TestBetamax): NAME = "TEST ACTIVITY" def setUp(self): super().setUp() self.workflow_root = self.project.activity(name=ActivityRootNames.WORKFLOW_ROOT) self.task = self.project.create_activity( name=self.NAME, activity_type=ActivityType.TASK ) def tearDown(self): if self.task: try: self.task.delete() except APIError: pass super().tearDown() def test_retrieve_activities(self): self.assertTrue(self.project.activities()) def test_retrieve_single_activity(self): self.assertTrue(self.project.activity(self.NAME)) def test_activity_attributes(self): attributes = [ "_client", "_json_data", "id", "name", "created_at", "updated_at", "ref", "description", "status", "activity_type", "_scope_id", "start_date", "due_date", "_form_collection", ] for attribute in attributes: with self.subTest(msg=attribute): self.assertTrue( hasattr(self.task, attribute), "Could not find '{}' in the object: '{}'".format( attribute, self.task.__dict__.keys() ), ) def test_retrieve_unknown_activity(self): with self.assertRaises(NotFoundError): self.project.activity("Hello?!") def test_retrieve_too_many_activity(self): with self.assertRaises(MultipleFoundError): self.project.activity() # new in 1.7 def test_edit_activity_name(self): self.task.edit(name="Specify wheel diameter - updated") self.task_u = self.project.activity("Specify wheel diameter - updated") self.assertEqual(self.task.id, self.task_u.id) self.assertEqual(self.task.name, self.task_u.name) self.assertEqual(self.task.name, "Specify wheel diameter - updated") # Added to improve coverage. Assert whether IllegalArgumentError is raised when 'name' is not a string object. with self.assertRaises(IllegalArgumentError): self.task.edit(name=True) def test_edit_activity_description(self): self.task.edit(description="This task has a cool description") self.assertEqual(self.task._client.last_response.status_code, requests.codes.ok) # Added to improve coverage. Assert whether IllegalArgumentError is raised when 'description' is # not a string object. with self.assertRaises(IllegalArgumentError): self.task.edit(description=42) def test_edit_activity_naive_dates(self): start_time = datetime(2000, 1, 1, 0, 0, 0) due_time = datetime(2019, 12, 31, 0, 0, 0) with warnings.catch_warnings(record=False): warnings.simplefilter("ignore") self.task.edit(start_date=start_time, due_date=due_time) self.assertEqual(self.task._client.last_response.status_code, requests.codes.ok) with self.assertRaises(IllegalArgumentError): self.task.edit(start_date="All you need is love") with self.assertRaises(IllegalArgumentError): self.task.edit(due_date="Love is all you need") def test_edit_due_date_timezone_aware(self): self.task.edit(start_date=self.time, due_date=self.time) self.assertEqual(self.task._client.last_response.status_code, requests.codes.ok) # 1.10.0 def test_edit_activity_status(self): self.task.edit(status=ActivityStatus.COMPLETED) for status in [True, "NO STATUS", 3]: with self.subTest(msg=status): with self.assertRaises(IllegalArgumentError): self.task.edit(status=status) # 1.7.2 def test_datetime_with_naive_duedate_only_fails(self): """reference to #121 - thanks to @joost.schut""" naive_duedate = datetime(2017, 6, 5, 5, 0, 0) with warnings.catch_warnings(record=False): warnings.simplefilter("ignore") self.task.edit(due_date=naive_duedate) def test_datetime_with_tzinfo_provides_correct_offset(self): """reference to #121 - thanks to @joost.schut The tzinfo.timezone('Europe/Amsterdam') should provide a 2 hour offset, recording 20 minutes """ # setup tz = pytz.timezone("Europe/Amsterdam") tzaware_due = tz.localize(datetime(2017, 7, 1)) tzaware_start = tz.localize(datetime(2017, 6, 30, 0, 0, 0)) self.task.edit(start_date=tzaware_start) self.assertTrue( self.task._json_data["start_date"], tzaware_start.isoformat(sep="T") ) self.task.edit(due_date=tzaware_due) self.assertTrue( self.task._json_data["due_date"], tzaware_due.isoformat(sep="T") ) def test_edit_cascade_down(self): # setup subprocess = self.project.activity("Subprocess") # type: Activity subtask = self.project.activity("SubTask") # type: Activity testuser = self.client.user(username="testuser") subprocess.edit_cascade_down( assignees=["testuser"], status=ActivityStatus.COMPLETED, overwrite=False, ) subprocess.refresh() subtask.refresh() # testing self.assertIn(testuser, subprocess.assignees) self.assertIn(testuser, subtask.assignees) self.assertEqual(subprocess.status, ActivityStatus.COMPLETED) self.assertEqual(subtask.status, ActivityStatus.COMPLETED) # tearDown subprocess.edit(assignees=[], status=ActivityStatus.OPEN) subtask.edit(assignees=[], status=ActivityStatus.OPEN) # test added due to #847 - providing no inputs overwrites values def test_edit_activity_clearing_values(self): # setup initial_name = "Pykechain testing task" initial_description = "Task created to test editing." initial_start_date = datetime(2018, 12, 5, tzinfo=None) initial_due_date = datetime(2018, 12, 8, tzinfo=None) initial_tags = ["tag_one", "tag_two"] initial_assignee = self.client.user(username="testuser") self.task.edit( name=initial_name, description=initial_description, tags=initial_tags, start_date=initial_start_date, due_date=initial_due_date, assignees=[initial_assignee.username], ) # Edit without mentioning values, everything should stay the same new_name = "New name for task" self.task.edit(name=new_name) # testing self.assertEqual(self.task.name, new_name) self.assertEqual(self.task.description, initial_description) self.assertEqual( self.task.start_date.strftime("%Y/%m/%d, %H:%M:%S"), initial_start_date.strftime("%Y/%m/%d, %H:%M:%S"), ) self.assertEqual( self.task.due_date.strftime("%Y/%m/%d, %H:%M:%S"), initial_due_date.strftime("%Y/%m/%d, %H:%M:%S"), ) self.assertEqual(self.task.tags, initial_tags) # Edit with clearing the values, name and status cannot be cleared self.task.edit( name=None, description=None, tags=None, start_date=None, due_date=None, status=None, assignees=None, ) self.task.refresh() self.assertEqual(self.task.name, new_name) self.assertEqual(self.task.description, "") self.assertEqual(self.task.start_date, None) self.assertEqual(self.task.due_date, None) self.assertEqual(self.task.assignees, list()) self.assertEqual(self.task.tags, list()) def test_retrieve_children_of_task_fails_for_task(self): with self.assertRaises(NotFoundError, msg="Tasks have no children!"): self.task.children() def test_child(self): child_task = self.workflow_root.child(name=self.NAME) self.assertIsInstance(child_task, Activity) self.assertEqual(child_task._json_data["parent_id"], self.workflow_root.id) def test_child_invalid(self): with self.assertRaises(IllegalArgumentError): self.workflow_root.child() second_process = self.workflow_root.create(name=self.NAME) with self.assertRaises(MultipleFoundError): self.workflow_root.child(name=self.NAME) second_process.delete() with self.assertRaises(NotFoundError): self.workflow_root.child(name="Just a scratch") def test_retrieve_all_children(self): all_tasks = self.workflow_root.all_children() self.assertIsInstance(all_tasks, list) self.assertEqual( 13, len(all_tasks), msg="Number of tasks has changed, expected 12." ) def test_retrieve_activity_by_id(self): task = self.project.activity(name="Subprocess") # type: Activity task_by_id = self.client.activity(pk=task.id) self.assertEqual(task.id, task_by_id.id) def test_retrieve_siblings_of_a_task_in_a_subprocess(self): task = self.project.activity(name="Subprocess") # type: Activity siblings = task.siblings() self.assertIn(task.id, [sibling.id for sibling in siblings]) self.assertTrue(len(siblings) >= 1) def test_retrieve_siblings_of_root(self): with self.assertRaises(NotFoundError): self.workflow_root.siblings() # in 1.12 def test_retrieve_siblings_of_a_task_in_a_subprocess_with_arguments(self): task = self.project.activity(name="SubTask") # type: Activity siblings = task.siblings(name__icontains="sub") self.assertIn(task.id, [sibling.id for sibling in siblings]) self.assertEqual(1, len(siblings)) def test_activity_without_scope_id_will_fix_itself(self): specify_wheel_diam_cripled = self.project.activity( name="Specify wheel diameter", fields="id,name,status" ) self.assertFalse(specify_wheel_diam_cripled._json_data.get("scope_id")) # now the self-healing will begin self.assertEqual(specify_wheel_diam_cripled.scope_id, self.project.id) # in 1.13 def test_create_activity_with_incorrect_activity_class_fails(self): with self.assertRaisesRegex( IllegalArgumentError, "must be an option from enum" ): self.project.create_activity(name="New", activity_type="DEFUNCTActivity") # 2.0 new activity # noinspection PyTypeChecker def test_edit_activity_assignee(self): specify_wd = self.project.activity("Specify wheel diameter") # type: Activity original_assignee_ids = specify_wd._json_data.get("assignee_ids") or [] # pykechain_user = self.client.user(username='pykechain') test_user = self.client.user(username="testuser") specify_wd.edit(assignees_ids=[test_user.id]) specify_wd.refresh() self.assertIsInstance(specify_wd._json_data.get("assignees_ids")[0], int) self.assertEqual( specify_wd._client.last_response.status_code, requests.codes.ok ) # Added to improve coverage. Assert whether NotFoundError is raised when 'assignee' is not part of the # scope members with self.assertRaises(NotFoundError): specify_wd.edit(assignees_ids=[-100]) # Added to improve coverage. Assert whether NotFoundError is raised when 'assignee' is not part of the # scope members with self.assertRaises(IllegalArgumentError): specify_wd.edit(assignees_ids="this should have been a list") specify_wd.edit(assignees_ids=original_assignee_ids) def test_activity_retrieve_parent_of_task(self): task = self.project.activity(name="SubTask") subprocess = task.parent() # type Activity self.assertEqual(subprocess.activity_type, ActivityType.PROCESS) def test_activity_retrieve_parent_of_root(self): task = self.project.activity(name=ActivityRootNames.WORKFLOW_ROOT) with self.assertRaises(NotFoundError): task.parent() def test_activity_retrieve_parent_of_a_toplevel_task_returns_workflow_root_id( self, ): task = self.project.activity("Specify wheel diameter") parent = task.parent() self.assertEqual(self.project._json_data.get("workflow_root_id"), parent.id) def test_activity_test_workflow_root_object(self): workflow_root = self.project.activity( id=self.project._json_data.get("workflow_root_id") ) self.assertTrue(workflow_root.is_root()) self.assertTrue(workflow_root.is_workflow_root()) def test_activity_retrieve_children_of_parent(self): subprocess = self.project.activity(name="Subprocess") # type: Activity children = subprocess.children() self.assertTrue(len(children) >= 1) for child in children: self.assertEqual(child._json_data.get("parent_id"), subprocess.id) def test_activity_retrieve_children_of_subprocess_with_arguments(self): subprocess = self.project.activity(name="Subprocess") # type: Activity children = subprocess.children(name__icontains="task") self.assertTrue(len(children) >= 1) for child in children: self.assertEqual(child._json_data.get("parent_id"), subprocess.id) def test_count_children(self): process = self.project.activity(name="Tasks with Widgets") nr = process.count_children() self.assertIsInstance(nr, int) self.assertEqual(8, nr) nr = process.count_children(name__contains="Service") self.assertEqual(4, nr) with self.assertRaises(IllegalArgumentError): self.task.count_children() def test_rootlevel_activity_is_rootlevel(self): specify_wd = self.project.activity("Specify wheel diameter") self.assertTrue(specify_wd.is_rootlevel()) root_itself = self.project.activity(ActivityRootNames.WORKFLOW_ROOT) self.assertFalse(root_itself.is_rootlevel()) def test_subtask_activity_is_not_rootlevel(self): subprocess_subtask = self.project.activity("SubTask") self.assertFalse(subprocess_subtask.is_rootlevel()) def test_activity_is_task(self): specify_wd = self.project.activity("Specify wheel diameter") self.assertTrue(specify_wd.is_task()) self.assertFalse(specify_wd.is_subprocess()) def test_activity_is_subprocess(self): subprocess = self.project.activity("Subprocess") self.assertTrue(subprocess.is_subprocess()) self.assertFalse(subprocess.is_task()) def test_activity_assignees_list(self): test_user = self.client.user(username="testuser") self.task.edit(assignees_ids=[test_user.id]) self.task.refresh() list_of_assignees_in_data = self.task._json_data.get("assignees_ids") assignees_list = self.task.assignees self.assertSetEqual( set(list_of_assignees_in_data), {u.id for u in assignees_list} ) def test_activity_assignees_list_no_assignees_gives_empty_list(self): activity_name = "Specify wheel diameter" activity = self.project.activity(name=activity_name) # type: Activity self.assertListEqual( list(), activity.assignees, "Task has no assignees and should return Empty list", ) def test_activity_move(self): # setUp activity_to_be_moved = self.task new_parent_name = "Subprocess" new_parent = self.project.activity(name=new_parent_name) activity_to_be_moved.move(parent=new_parent) # testing self.assertEqual(new_parent, activity_to_be_moved.parent()) def test_activity_move_under_task_parent(self): # setUp new_parent_name = "Specify wheel diameter" new_parent = self.project.activity(name=new_parent_name) # testing with self.assertRaises(IllegalArgumentError): self.task.move(parent=new_parent) def test_activity_move_under_part_object(self): # setUp new_parent_name = "Bike" new_parent = self.project.part(name=new_parent_name) # testing with self.assertRaises(IllegalArgumentError): self.task.move(parent=new_parent) # tests added in 3.0 def test_activity_retrieve_with_refs(self): # setup test_task_ref = slugify_ref(self.task.name) test_task_activity = self.project.activity(ref=test_task_ref) # testing self.assertIsInstance(test_task_activity, Activity) self.assertEqual(self.task, test_task_activity) def test_activity_associated_parts(self): # setUp activity_name = "Task - Form + Tables + Service" activity = self.project.activity(name=activity_name) associated_models, associated_instances = activity.associated_parts() # testing for model in associated_models: self.assertTrue(model.category == Category.MODEL) if model.name == "Bike": self.assertTrue(model.property(name="Gears").output) self.assertFalse(model.property(name="Total height").output) self.assertFalse(model.property(name="Picture").output) self.assertFalse(model.property(name="Description").output) self.assertTrue(model.property(name="Website").output) self.assertTrue(model.property(name="Sale?").output) for instance in associated_instances: self.assertTrue(instance.category == Category.INSTANCE) self.assertTrue(len(associated_models) == 3) self.assertTrue(len(associated_instances) == 4) def test_activity_associated_objects_ids(self): # setUp activity_name = "Task - Form + Tables + Service" activity = self.project.activity(name=activity_name) associated_object_ids = activity.associated_object_ids() # testing self.assertTrue(len(associated_object_ids) == 17) def test_activity_parts_of_specific_type(self): # setUp activity_name = "Task - Form + Tables + Service" bike_model = self.project.model(name="Bike") activity = self.project.activity(name=activity_name) associated_models = activity.parts(category=Category.MODEL) # testing for model in associated_models: self.assertTrue(model.category == Category.MODEL) if model == bike_model: self.assertTrue(model.property(name="Gears").output) self.assertFalse(model.property(name="Total height").output) self.assertFalse(model.property(name="Picture").output) self.assertFalse(model.property(name="Description").output) self.assertTrue(model.property(name="Website").output) self.assertTrue(model.property(name="Sale?").output) self.assertTrue(len(associated_models) == 3) def test_activity_retrieve_form_collection(self): forms = self.project.forms(classification=Classification.CATALOG) for status_form in forms[0].status_forms: self.assertEqual(status_form.activity._form_collection, forms[0].id)
class TestActivities(TestBetamax): def setUp(self): pass def tearDown(self): pass def test_retrieve_activities(self): pass def test_retrieve_single_activity(self): pass def test_activity_attributes(self): pass def test_retrieve_unknown_activity(self): pass def test_retrieve_too_many_activity(self): pass def test_edit_activity_name(self): pass def test_edit_activity_description(self): pass def test_edit_activity_naive_dates(self): pass def test_edit_due_date_timezone_aware(self): pass def test_edit_activity_status(self): pass def test_datetime_with_naive_duedate_only_fails(self): '''reference to #121 - thanks to @joost.schut''' pass def test_datetime_with_tzinfo_provides_correct_offset(self): '''reference to #121 - thanks to @joost.schut The tzinfo.timezone('Europe/Amsterdam') should provide a 2 hour offset, recording 20 minutes ''' pass def test_edit_cascade_down(self): pass def test_edit_activity_clearing_values(self): pass def test_retrieve_children_of_task_fails_for_task(self): pass def test_child(self): pass def test_child_invalid(self): pass def test_retrieve_all_children(self): pass def test_retrieve_activity_by_id(self): pass def test_retrieve_siblings_of_a_task_in_a_subprocess(self): pass def test_retrieve_siblings_of_root(self): pass def test_retrieve_siblings_of_a_task_in_a_subprocess_with_arguments(self): pass def test_activity_without_scope_id_will_fix_itself(self): pass def test_create_activity_with_incorrect_activity_class_fails(self): pass def test_edit_activity_assignee(self): pass def test_activity_retrieve_parent_of_task(self): pass def test_activity_retrieve_parent_of_root(self): pass def test_activity_retrieve_parent_of_a_toplevel_task_returns_workflow_root_id( self, ): pass def test_activity_test_workflow_root_object(self): pass def test_activity_retrieve_children_of_parent(self): pass def test_activity_retrieve_children_of_subprocess_with_arguments(self): pass def test_count_children(self): pass def test_rootlevel_activity_is_rootlevel(self): pass def test_subtask_activity_is_not_rootlevel(self): pass def test_activity_is_task(self): pass def test_activity_is_subprocess(self): pass def test_activity_assignees_list(self): pass def test_activity_assignees_list_no_assignees_gives_empty_list(self): pass def test_activity_move(self): pass def test_activity_move_under_task_parent(self): pass def test_activity_move_under_part_object(self): pass def test_activity_retrieve_with_refs(self): pass def test_activity_associated_parts(self): pass def test_activity_associated_objects_ids(self): pass def test_activity_parts_of_specific_type(self): pass def test_activity_retrieve_form_collection(self): pass
49
2
10
1
8
1
1
0.15
1
15
9
0
48
4
48
123
517
111
362
136
311
54
293
133
244
4
3
3
60
140,743
KE-works/pykechain
KE-works_pykechain/pykechain/models/widgets/widget_models.py
pykechain.models.widgets.widget_models.ProjectinfoWidget
class ProjectinfoWidget(Widget): """Project Info Widget."""
class ProjectinfoWidget(Widget): '''Project Info Widget.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
25
2
0
1
1
0
1
1
1
0
0
3
0
0
140,744
KE-works/pykechain
KE-works_pykechain/pykechain/models/widgets/widget_models.py
pykechain.models.widgets.widget_models.PropertygridWidget
class PropertygridWidget(Widget): """Propertygrid Widget."""
class PropertygridWidget(Widget): '''Propertygrid Widget.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
25
2
0
1
1
0
1
1
1
0
0
3
0
0
140,745
KE-works/pykechain
KE-works_pykechain/pykechain/models/widgets/widget_models.py
pykechain.models.widgets.widget_models.ScopeWidget
class ScopeWidget(Widget): """Scope grid Widget."""
class ScopeWidget(Widget): '''Scope grid Widget.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
25
2
0
1
1
0
1
1
1
0
0
3
0
0
140,746
KE-works/pykechain
KE-works_pykechain/pykechain/models/widgets/widget_models.py
pykechain.models.widgets.widget_models.ScopemembersWidget
class ScopemembersWidget(Widget): """ScopeMembers Widget."""
class ScopemembersWidget(Widget): '''ScopeMembers Widget.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
25
2
0
1
1
0
1
1
1
0
0
3
0
0
140,747
KE-works/pykechain
KE-works_pykechain/pykechain/models/widgets/widget_models.py
pykechain.models.widgets.widget_models.ServiceWidget
class ServiceWidget(Widget): """Service Widget."""
class ServiceWidget(Widget): '''Service Widget.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
25
2
0
1
1
0
1
1
1
0
0
3
0
0