Beispiel #1
0
class TestTM1pyDictMethods(unittest.TestCase):
    tm1 = TM1Service(address=address,
                     port=port,
                     user=user,
                     password=pwd,
                     ssl=ssl)

    def test_stuff(self):
        mdx_rows = '[}Clients].Members'
        mdx_columns = '[}Groups].Members'
        cube_name = '[}ClientGroups]'
        mdx = 'SELECT {} ON ROWS, {} ON COLUMNS FROM {}'.format(
            mdx_rows, mdx_columns, cube_name)
        data = self.tm1.data.execute_mdx(mdx)

        # Get
        self.assertIsNotNone(data[('[}Clients].[ad min]',
                                   '[}Groups].[ADM IN]')])

        # Delete
        self.assertTrue(('[}clients].[admin]', '[}groups].[admin]') in data)
        del data[('[}Clients].[ad min]', '[}Groups].[ADM IN]')]
        self.assertFalse(('[}clients].[admin]', '[}groups].[admin]') in data)

        # Copy
        data_cloned = data.copy()
        self.assertTrue(data_cloned == data)
        self.assertFalse(data_cloned is data)
Beispiel #2
0
    def setUpClass(cls):
        """
        Establishes a connection to TM1 and creates a dimensions and a cube to use across all tests
        """

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath('config.ini'))
        cls.tm1 = TM1Service(**cls.config['tm1srv01'])

        # Build Dimensions
        cls.dimension_names = ("TM1py_tests_annotations_dimension1",
                               "TM1py_tests_annotations_dimension2",
                               "TM1py_tests_annotations_dimension3")

        for dimension_name in cls.dimension_names:
            elements = [
                Element('Element {}'.format(str(j)), 'Numeric')
                for j in range(1, 1001)
            ]
            hierarchy = Hierarchy(dimension_name=dimension_name,
                                  name=dimension_name,
                                  elements=elements)
            dimension = Dimension(dimension_name, [hierarchy])
            cls.tm1.dimensions.update_or_create(dimension)

        # Build Cube
        cls.cube_name = "TM1py_tests_annotations"

        cube = Cube(cls.cube_name, cls.dimension_names)
        cls.tm1.cubes.update_or_create(cube)
Beispiel #3
0
    def setUpClass(cls):
        """
        Establishes a connection to TM1 and creates TM! objects to use across all tests
        """

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath('config.ini'))
        cls.tm1 = TM1Service(**cls.config['tm1srv01'])

        cls.all_dimension_names = cls.tm1.dimensions.get_all_names()
        cls.random_dimension = cls.tm1.dimensions.get(random.choice(cls.all_dimension_names))
        cls.random_dimension_all_elements = cls.random_dimension.default_hierarchy.elements
        cls.random_dimension_elements = [element for element in cls.random_dimension_all_elements][0:2]

        # Subset process
        cls.subset_name = cls.prefix + '_subset_' + cls.some_name
        cls.subset = Subset(dimension_name=cls.random_dimension.name,
                            subset_name=cls.subset_name,
                            elements=cls.random_dimension_elements)
        cls.tm1.dimensions.subsets.update_or_create(cls.subset, False)
        cls.p_subset = Process(name=cls.prefix + '_subset_' + cls.some_name,
                               datasource_type='TM1DimensionSubset',
                               datasource_data_source_name_for_server=cls.subset.dimension_name,
                               datasource_subset=cls.subset.name,
                               metadata_procedure="sTest = 'abc';")

        with open(Path(__file__).parent.joinpath('resources', 'Bedrock.Server.Wait.json'), 'r') as file:
            cls.p_bedrock_server_wait = Process.from_json(file.read())
Beispiel #4
0
    def setup_class(cls):
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # Define Names
        cls.dimension_name = PREFIX + "Dimension"
        cls.subset_name_static = PREFIX + "static"
        cls.subset_name_dynamic = PREFIX + "dynamic"
Beispiel #5
0
    def setUpClass(cls):
        """
        Establishes a connection to TM1 and creates TM! objects to use across all tests
        """

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath('config.ini'))
        cls.tm1 = TM1Service(**cls.config['tm1srv01'])

        # Build Dimensions
        for i in range(3):
            elements = [
                Element('Element {}'.format(str(j)), 'Numeric')
                for j in range(1, 1001)
            ]
            hierarchy = Hierarchy(dimension_name=cls.dimension_names[i],
                                  name=cls.dimension_names[i],
                                  elements=elements)
            dimension = Dimension(name=cls.dimension_names[i],
                                  hierarchies=[hierarchy])
            if not cls.tm1.dimensions.exists(dimension_name=dimension.name):
                cls.tm1.dimensions.create(dimension=dimension)
        # Build Cube
        cube = Cube(cls.cube_name, cls.dimension_names)
        if not cls.tm1.cubes.exists(cls.cube_name):
            cls.tm1.cubes.create(cube)
        # Write data into cube
        cellset = {}
        for i in range(20000):
            element1 = 'Element ' + str(random.randint(1, 1000))
            element2 = 'Element ' + str(random.randint(1, 1000))
            element3 = 'Element ' + str(random.randint(1, 1000))
            cellset[(element1, element2, element3)] = random.randint(1, 1000)
        cls.tm1.cells.write_values(cls.cube_name, cellset)
Beispiel #6
0
    def setUpClass(cls):
        """
        Establishes a connection to TM1 and creates TM! objects to use across all tests
        """

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath('config.ini'))
        cls.tm1 = TM1Service(**cls.config['tm1srv01'])

        cls.user_name = PREFIX + "Us'er1"
        cls.user_name_exotic_password = "******"
        cls.enabled = True
        cls.user = User(name=cls.user_name,
                        groups=[],
                        password='******',
                        enabled=cls.enabled)
        cls.group_name1 = PREFIX + "Gro'up1"
        cls.group_name2 = PREFIX + "Group2"
        cls.user.add_group(cls.group_name1)

        if cls.user_name in CaseAndSpaceInsensitiveSet(
                *cls.tm1.security.get_all_user_names()):
            cls.tm1.security.delete_user(cls.user_name)

        for group in (cls.group_name1, cls.group_name2):
            if group in CaseAndSpaceInsensitiveSet(
                    *cls.tm1.security.get_all_groups()):
                cls.tm1.security.delete_group(group)
async def main():
    loop = asyncio.get_event_loop()
    with TM1Service(address='localhost', port=12354, user='******', password='******', ssl=True) as tm1:
        with ThreadPoolExecutor(max_workers=10) as executor:
            futures = [loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(0, 9999), range(0, 9999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(9999, 19999), range(9999, 19999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(19999, 39999), range(19999, 29999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(29999, 49999), range(29999, 39999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(39999, 59999), range(39999, 49999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(49999, 69999), range(49999, 59999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(59999, 79999), range(59999, 69999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(69999, 89999), range(69999, 79999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(79999, 99999), range(79999, 89999)),
                       loop.run_in_executor(executor, write_values, tm1,
                                            MDX_TEMPLATE.format(89999, 99999), range(89999, 99999))]
            for future in futures:
                await future
Beispiel #8
0
    def setUpClass(cls):
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # Build Dimensions
        for dimension_name in cls.dimension_names:
            elements = [
                Element('Element {}'.format(str(j)), 'Numeric')
                for j in range(1, 1001)
            ]
            hierarchy = Hierarchy(dimension_name=dimension_name,
                                  name=dimension_name,
                                  elements=elements)
            dimension = Dimension(dimension_name, [hierarchy])
            if not cls.tm1.dimensions.exists(dimension.name):
                cls.tm1.dimensions.create(dimension)

        # Build Cube
        cube = Cube(cls.cube_name, cls.dimension_names)
        if not cls.tm1.cubes.exists(cls.cube_name):
            cls.tm1.cubes.create(cube)
        c = Cube(cls.cube_name,
                 dimensions=cls.dimension_names,
                 rules=Rules(''))
        if cls.tm1.cubes.exists(c.name):
            cls.tm1.cubes.delete(c.name)
        cls.tm1.cubes.create(c)
def main(params):
    # 3. Get credentials
    creds = {
        'user':params['pauser'],
        'password':params['papassword'], 
        'port':params['paport'],
        'ssl':'False',
        'address':params['paaddress']
    }

    # 4. Get cellset
    cellset = {
        (
            params['Month'], 
            params['Version'], 
            params['Currency'], 
            params['CostCentre'], 
            params['Account'], 
            params['Project'], 
            params['GeneralLedgerSource'], 
            params['GeneralLedgerMeasure'],
        ):params['Value']
    }

    # 5. Write to cube
    with TM1Service(**creds) as tm1:
        tm1.cubes.cells.write_values('General Ledger', cellset, dimensions=['Time Month', 'Version', 'Currency', 'Cost Centre', 'Account', 'Project', 'General Ledger Source', 'General Ledger Measure'])

    # 6. Return result
    print('Data loaded.')
    return {
        'headers':{'Content-Type':'application/json'}, 
        'body':{'message':'Commentary loaded.'}
    }
Beispiel #10
0
    def setup_class(cls):
        cls.tm1 = TM1Service(**test_config)

        # Do random stuff
        cls.private = bool(random.getrandbits(1))

        # Define Names
        cls.prefix = 'TM1py_unittest_dimension_'
        cls.dimension_name = cls.prefix + str(uuid.uuid4())
        cls.subset_name_static = cls.prefix + str(uuid.uuid4())
        cls.subset_name_dynamic = cls.prefix + str(uuid.uuid4())

        # Instantiate Subsets
        cls.static_subset = Subset(dimension_name=cls.dimension_name,
                                   subset_name=cls.subset_name_static,
                                   elements=['USD', 'EUR', 'NZD'])
        cls.dynamic_subset = Subset(
            dimension_name=cls.dimension_name,
            subset_name=cls.subset_name_dynamic,
            expression='{ HIERARCHIZE( {TM1SUBSETALL( [' + cls.dimension_name +
            '] )} ) }')

        elements = [
            Element('USD', 'Numeric'),
            Element('EUR', 'Numeric'),
            Element('JPY', 'Numeric'),
            Element('CNY', 'Numeric'),
            Element('GBP', 'Numeric'),
            Element('NZD', 'Numeric')
        ]
        element_attributes = [ElementAttribute('Currency Name', 'String')]
        h = Hierarchy(cls.dimension_name, cls.dimension_name, elements,
                      element_attributes)
        d = Dimension(cls.dimension_name, hierarchies=[h])
        cls.tm1.dimensions.create(d)
Beispiel #11
0
    def setUp(cls):

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath('config.ini'))
        cls.tm1 = TM1Service(**cls.config['tm1srv01'])

        cls.prefix = "TM1py_Tests_Cube_"

        cls.cube_name = cls.prefix + "some_name"
        cls.dimension_names = [
            cls.prefix + "dimension1",
            cls.prefix + "dimension2",
            cls.prefix + "dimension3"]

        for dimension_name in cls.dimension_names:
            elements = [Element('Element {}'.format(str(j)), 'Numeric') for j in range(1, 1001)]
            hierarchy = Hierarchy(dimension_name=dimension_name,
                                  name=dimension_name,
                                  elements=elements)
            dimension = Dimension(dimension_name, [hierarchy])
            if not cls.tm1.dimensions.exists(dimension.name):
                cls.tm1.dimensions.create(dimension)

        # Build Cube
        cube = Cube(cls.cube_name, cls.dimension_names)
        if not cls.tm1.cubes.exists(cls.cube_name):
            cls.tm1.cubes.create(cube)
        c = Cube(cls.cube_name, dimensions=cls.dimension_names, rules=Rules(''))
        if cls.tm1.cubes.exists(c.name):
            cls.tm1.cubes.delete(c.name)
        cls.tm1.cubes.create(c)
Beispiel #12
0
class TestAnnotationMethods(unittest.TestCase):
    tm1 = TM1Service(**test_config)

    # Get Random Cube + Intersection
    all_cube_names = tm1.cubes.get_all_names()
    cube_name = random.choice(all_cube_names)
    
    random_intersection = tm1.cubes.get_random_intersection(cube_name, False)
    random_text = "".join([random.choice(string.printable) for i in range(100)])

    def test1_create_annotation(self):
        annotation = Annotation(comment_value=self.random_text,
                                object_name=self.cube_name,
                                dimensional_context=self.random_intersection)
        response = self.tm1.cubes.annotations.create(annotation)
        annotation_id = response.json()['ID']

        # test, if it exists
        all_annotations = self.tm1.cubes.annotations.get_all(self.cube_name)
        if len(all_annotations) > 0:
            annotation = self.tm1.cubes.annotations.get(annotation_id)
            self.assertEqual(self.random_text, annotation.comment_value)

    def test2_get_all_annotations_from_cube(self):
        annotations = self.tm1.cubes.annotations.get_all(self.cube_name)
        for a in annotations:
            b = self.tm1.cubes.annotations.get(a.id)
            self.assertEqual(a.body, b.body)

    def test3_update_annotation(self):
        annotations = self.tm1.cubes.annotations.get_all(self.cube_name)
        for a in annotations:
            # Get the anntoation that was created in test1
            if a.dimensional_context == self.random_intersection and a.comment_value == self.random_text:
                # Update Value and Coordinates
                new_random_text = "".join([random.choice(string.printable) for _ in range(100)])
                a.comment_value = new_random_text
                response = self.tm1.cubes.annotations.update(a)
                annotation_id = json.loads(response.text)['ID']
                a_updated = self.tm1.cubes.annotations.get(annotation_id)
                self.assertEqual(a_updated.comment_value, new_random_text)

    def test4_delete_annotation(self):
        # get Annotations
        annotations = self.tm1.cubes.annotations.get_all(self.cube_name)
        # sort Them
        annotations = sorted(annotations, key=lambda a: str(a.last_updated if a.last_updated else a.created))
        # First count
        number_annotations_at_start = len(annotations)

        last_annotation = annotations[-1]
        self.tm1.cubes.annotations.delete(last_annotation._id)

        # get Annotations again
        annotations = self.tm1.cubes.annotations.get_all(self.cube_name)
        # Second count
        number_annotations_at_end = len(annotations)

        self.assertEqual(number_annotations_at_start, number_annotations_at_end + 1)
        self.tm1.logout()
Beispiel #13
0
    def setup_class(cls):
        # hard coded stuff
        cls.dimension_name = dimension_prefix.format(uuid.uuid4())
        cls.hierarchy_name = cls.dimension_name

        # Connection to TM1
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # Elements
        cls.years = ("No Year", "1989", "1990", "1991", "1992")
        cls.extra_year = "4321"
        # Element Attributes
        cls.attributes = ('Previous Year', 'Next Year')

        # create dimension with a default hierarchy
        d = Dimension(cls.dimension_name)
        h = Hierarchy(cls.dimension_name, cls.hierarchy_name)
        h.add_element('Total Years', 'Consolidated')
        h.add_element('All Consolidations', 'Consolidated')
        h.add_edge("All Consolidations", "Total Years", 1)
        for year in cls.years:
            h.add_element(year, 'Numeric')
            h.add_edge('Total Years', year, 1)
        for attribute in cls.attributes:
            h.add_element_attribute(attribute, "String")
        d.add_hierarchy(h)
        cls.tm1.dimensions.create(d)

        # write one element attribute value
        cls.tm1.cubes.cells.write_value('1988', '}ElementAttributes_' + cls.dimension_name, ('1989', 'Previous Year'))
Beispiel #14
0
    def setUpClass(cls):
        # Namings
        cls.prefix = "TM1py_unittest_server_"
        cls.dimension_name1 = cls.prefix + str(uuid.uuid4())
        cls.dimension_name2 = cls.prefix + str(uuid.uuid4())
        cls.cube_name = cls.prefix + str(uuid.uuid4())
        cls.process_name1 = cls.prefix + str(uuid.uuid4())
        cls.process_name2 = cls.prefix + str(uuid.uuid4())

        # Connect to TM1
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # create a simple cube with dimensions to test transactionlog methods
        if not cls.tm1.dimensions.exists(cls.dimension_name1):
            d = Dimension(cls.dimension_name1)
            h = Hierarchy(cls.dimension_name1, cls.dimension_name1)
            h.add_element('Total Years', 'Consolidated')
            h.add_element('No Year', 'Numeric')
            for year in range(1989, 2040, 1):
                h.add_element(str(year), 'Numeric')
                h.add_edge('Total Years', str(year), 1)
            d.add_hierarchy(h)
            cls.tm1.dimensions.create(d)

        if not cls.tm1.dimensions.exists(cls.dimension_name2):
            d = Dimension(cls.dimension_name2)
            h = Hierarchy(cls.dimension_name2, cls.dimension_name2)
            h.add_element('Value', 'Numeric')
            d.add_hierarchy(h)
            cls.tm1.dimensions.create(d)

        if not cls.tm1.cubes.exists(cls.cube_name):
            cube = Cube(cls.cube_name,
                        [cls.dimension_name1, cls.dimension_name2])
            cls.tm1.cubes.create(cube)
    def setUp(cls):

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath('config.ini'))
        cls.tm1 = TM1Service(**cls.config['tm1srv01'])

        for dimension_name in cls.dimension_names:
            elements = [
                Element('Element {}'.format(str(j)), 'Numeric')
                for j in range(1, 1001)
            ]
            hierarchy = Hierarchy(dimension_name=dimension_name,
                                  name=dimension_name,
                                  elements=elements)
            dimension = Dimension(dimension_name, [hierarchy])
            if not cls.tm1.dimensions.exists(dimension.name):
                cls.tm1.dimensions.create(dimension)

        # Build Cube
        cube = Cube(cls.cube_name, cls.dimension_names)
        if not cls.tm1.cubes.exists(cls.cube_name):
            cls.tm1.cubes.create(cube)
        c = Cube(cls.cube_name,
                 dimensions=cls.dimension_names,
                 rules=Rules(''))
        if cls.tm1.cubes.exists(c.name):
            cls.tm1.cubes.delete(c.name)
        cls.tm1.cubes.create(c)

        if not cls.tm1.sandboxes.exists(cls.sandbox_name1):
            cls.tm1.sandboxes.create(
                Sandbox(name=cls.sandbox_name1,
                        include_in_sandbox_dimension=True))
Beispiel #16
0
    def setup_class(cls):
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # chore properties
        cls.chore_name1 = 'TM1py_unittest_chore_' + str(uuid.uuid4())
        cls.chore_name2 = 'TM1py_unittest_chore_' + str(uuid.uuid4())
        cls.start_time = datetime.now()
        cls.frequency_days = int(random.uniform(0, 355))
        cls.frequency_hours = int(random.uniform(0, 23))
        cls.frequency_minutes = int(random.uniform(0, 59))
        cls.frequency_seconds = int(random.uniform(0, 59))
        cls.frequency = ChoreFrequency(days=cls.frequency_days, hours=cls.frequency_hours,
                                       minutes=cls.frequency_minutes, seconds=cls.frequency_seconds)
        cls.tasks = [ChoreTask(0, process_name1, parameters=[{'Name': 'pRegion', 'Value': 'UK'}]),
                     ChoreTask(1, process_name1, parameters=[{'Name': 'pRegion', 'Value': 'FR'}]),
                     ChoreTask(2, process_name1, parameters=[{'Name': 'pRegion', 'Value': 'CH'}])]
        p1 = Process(name=process_name1)
        p1.add_parameter('pRegion', 'pRegion (String)', value='US')
        if cls.tm1.processes.exists(p1.name):
            cls.tm1.processes.delete(p1.name)
        cls.tm1.processes.create(p1)
        p2 = Process(name=process_name2)
        p2.add_parameter('pRegion', 'pRegion (String)', value='UK')
        if cls.tm1.processes.exists(p2.name):
            cls.tm1.processes.delete(p2.name)
        cls.tm1.processes.create(p2)
Beispiel #17
0
    def setUpClass(cls):
        cls.tm1 = TM1Service(**config['tm1srv01'])

        cls.random_string = str(uuid.uuid4())

        cls.all_dimension_names = cls.tm1.dimensions.get_all_names()
        cls.random_dimension = cls.tm1.dimensions.get(random.choice(cls.all_dimension_names))
        cls.random_dimension_all_elements = cls.random_dimension.default_hierarchy.elements
        cls.random_dimension_elements = [element for element in cls.random_dimension_all_elements][0:2]

        # None process
        cls.p_none = Process(name=process_prefix + '_none_' + cls.random_string, datasource_type='None')

        # ACII process
        cls.p_ascii = Process(name=process_prefix + '_ascii_' + cls.random_string,
                              datasource_type='ASCII',
                              datasource_ascii_delimiter_type='Character',
                              datasource_ascii_delimiter_char=',',
                              datasource_ascii_header_records=2,
                              datasource_ascii_quote_character='^',
                              datasource_ascii_thousand_separator='~',
                              prolog_procedure="sTestProlog = 'test prolog procedure'",
                              metadata_procedure="sTestMeta = 'test metadata procedure'",
                              data_procedure="sTestData =  'test data procedure'",
                              epilog_procedure="sTestEpilog = 'test epilog procedure'",
                              datasource_data_source_name_for_server=r'C:\Data\file.csv',
                              datasource_data_source_name_for_client=r'C:\Data\file.csv')
        # Variables
        cls.p_ascii.add_variable('v_1', 'Numeric')
        cls.p_ascii.add_variable('v_2', 'Numeric')
        cls.p_ascii.add_variable('v_3', 'Numeric')
        cls.p_ascii.add_variable('v_4', 'Numeric')
        # Parameters
        cls.p_ascii.add_parameter('p_Year', 'year?', '2016')
        cls.p_ascii.add_parameter('p_Number', 'number?', 2)

        # View process
        cls.p_view = Process(name=process_prefix + '_view_' + cls.random_string,
                             datasource_type='TM1CubeView',
                             datasource_view='view1',
                             datasource_data_source_name_for_client='Plan_BudgetPlan',
                             datasource_data_source_name_for_server='Plan_BudgetPlan')

        # ODBC process
        cls.p_odbc = Process(name=process_prefix + '_odbc_' + cls.random_string,
                             datasource_type='ODBC',
                             datasource_password='******',
                             datasource_user_name='user')

        # Subset process
        cls.subset_name = process_prefix + '_subset_' + cls.random_string
        cls.subset = Subset(dimension_name=cls.random_dimension.name,
                            subset_name=cls.subset_name,
                            elements=cls.random_dimension_elements)
        cls.tm1.dimensions.subsets.create(cls.subset, False)
        cls.p_subset = Process(name=process_prefix + '_subset_' + cls.random_string,
                               datasource_type='TM1DimensionSubset',
                               datasource_data_source_name_for_server=cls.subset.dimension_name,
                               datasource_subset=cls.subset.name,
                               metadata_procedure="sTest = 'abc';")
Beispiel #18
0
class TestUserMethods(unittest.TestCase):
    tm1 = TM1Service(address=address, port=port, user=user, password=pwd, ssl=ssl)

    user_name = str(uuid.uuid4())
    group_name = str(uuid.uuid4())
    user = User(name=user_name, groups=[], password='******')

    # Create Group for unittests
    @classmethod
    def setup_class(cls):
        code = "AddGroup('{}');".format(cls.group_name)
        cls.tm1.processes.execute_ti_code([code])

    def test1_create_user(self):
        all_users_before = self.tm1.security.get_all()
        self.tm1.security.create(self.user)
        all_users_after = self.tm1.security.get_all()
        # test it!
        self.assertEqual(len(all_users_before) + 1, len(all_users_after))

    def test2_get_user(self):
        u = self.tm1.security.get(self.user_name)
        # Adjust it a little bit
        u.password = '******'
        u.friendly_name = None

        # test it !
        self.assertEqual(u.body, self.user.body)

    def test3_update_user(self):
        # get user
        u = self.tm1.security.get(self.user_name)
        # update user. Add Group
        u.add_group(self.group_name)
        self.tm1.security.update(u)
        # test it !
        groups = self.tm1.security.get_groups(u.name)
        self.assertIn(self.group_name, groups)
        # update user. Remove Group
        u.remove_group(self.group_name)
        self.tm1.security.update(u)
        # test it !
        groups = self.tm1.security.get_groups(u.name)
        self.assertNotIn(self.group_name, groups)

    def test4_delete_user(self):
        users_before = self.tm1.security.get_all()
        self.tm1.security.delete(self.user_name)
        users_after = self.tm1.security.get_all()

        # test it !
        self.assertEqual(len(users_before) - 1, len(users_after))

    @classmethod
    def teardown_class(cls):
        # Delete Group
        code = "DeleteGroup('{}');".format(cls.group_name)
        cls.tm1.processes.execute_ti_code([code])
        cls.tm1.logout()
Beispiel #19
0
    def setup_class(cls):
        # Connection to TM1
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # generate random coordinates
        cls.target_coordinates = list(
            zip(('Element ' + str(random.randint(1, 1000))
                 for _ in range(100)),
                ('Element ' + str(random.randint(1, 1000))
                 for _ in range(100)),
                ('Element ' + str(random.randint(1, 1000))
                 for _ in range(100))))

        # Build Dimensions
        for i in range(3):
            elements = [
                Element('Element {}'.format(str(j)), 'Numeric')
                for j in range(1, 1001)
            ]
            hierarchy = Hierarchy(dimension_names[i], dimension_names[i],
                                  elements)
            dimension = Dimension(dimension_names[i], [hierarchy])
            if not cls.tm1.dimensions.exists(dimension.name):
                cls.tm1.dimensions.create(dimension)

        # Build Cube
        cube = Cube(cube_name, dimension_names)
        if not cls.tm1.cubes.exists(cube_name):
            cls.tm1.cubes.create(cube)

        # Build cube view
        view = NativeView(cube_name=cube_name,
                          view_name=view_name,
                          suppress_empty_columns=True,
                          suppress_empty_rows=True)
        subset = AnonymousSubset(dimension_name=dimension_names[0],
                                 expression='{[' + dimension_names[0] +
                                 '].Members}')
        view.add_row(dimension_name=dimension_names[0], subset=subset)
        subset = AnonymousSubset(dimension_name=dimension_names[1],
                                 expression='{[' + dimension_names[1] +
                                 '].Members}')
        view.add_row(dimension_name=dimension_names[1], subset=subset)
        subset = AnonymousSubset(dimension_name=dimension_names[2],
                                 expression='{[' + dimension_names[2] +
                                 '].Members}')
        view.add_column(dimension_name=dimension_names[2], subset=subset)
        cls.tm1.cubes.views.create(view, private=False)

        # Sum of all the values that we write in the cube. serves as a checksum
        cls.total_value = 0

        # cellset of data that shall be written
        cls.cellset = {}
        for element1, element2, element3 in cls.target_coordinates:
            value = random.randint(1, 1000)
            cls.cellset[(element1, element2, element3)] = value
            # update the checksum
            cls.total_value += value
Beispiel #20
0
class TestOtherMethods(unittest.TestCase):
    tm1 = TM1Service(address=address,
                     port=port,
                     user=user,
                     password=pwd,
                     ssl=ssl)

    def test1_execute_mdx(self):
        cube_names = self.tm1.cubes.get_all_names()
        cube_name = cube_names[random.randrange(0, len(cube_names))]
        _, public_views = self.tm1.cubes.views.get_all(cube_name=cube_name)
        # if no views on cube. Recursion
        if len(public_views) == 0:
            self.test1_execute_mdx()
        else:
            # random public view on random cube
            view = public_views[random.randrange(0, len(public_views))]
            # if random view is MDXView. Recursion
            if isinstance(view, MDXView):
                self.test1_execute_mdx()
            else:
                # if native view has no dimensions on the columns. Recursion
                if len(view._columns) == 0:
                    self.test1_execute_mdx()
                else:
                    # sum up all numeric cells in Native View
                    data_native_view = self.tm1.cubes.cells.get_view_content(
                        cube_name, view.name, private=False)
                    sum_native_view = sum([
                        float(cell['Value'])
                        for cell in data_native_view.values()
                        if str(cell['Value']).isdigit()
                    ])

                    # get mdx from native view
                    mdx = view.as_MDX
                    # sum up all numeric cells in the response of the mdx query
                    data_mdx = self.tm1.cubes.cells.execute_mdx(mdx)
                    sum_mdx = sum([
                        float(cell['Value']) for cell in data_mdx.values()
                        if str(cell['Value']).isdigit()
                    ])

                    # test it !
                    self.assertEqual(sum_mdx, sum_native_view)

    def test2_read_cube_name_from_mdx(self):
        all_cube_names = self.tm1.cubes.get_all_names()
        all_cube_names_normalized = [
            cube_name.upper().replace(" ", "") for cube_name in all_cube_names
        ]
        for cube_name in all_cube_names:
            private_views, public_views = self.tm1.cubes.views.get_all(
                cube_name)
            for view in private_views + public_views:
                mdx = view.MDX
                cube_name = Utils.read_cube_name_from_mdx(mdx)
                self.assertIn(cube_name, all_cube_names_normalized)
Beispiel #21
0
    def setUpClass(cls):
        """
        Establishes a connection to TM1 and creates TM1 objects to use across all tests
        """

        # Connection to TM1
        cls.config = configparser.ConfigParser()
        cls.config.read(Path(__file__).parent.joinpath("config.ini"))
        cls.tm1 = TM1Service(**cls.config["tm1srv01"])
Beispiel #22
0
 def test_session_context_custom(self):
     app_name = "Some Application"
     with TM1Service(**config['tm1srv01'], session_context=app_name) as tm1:
         threads = tm1.monitoring.get_threads()
         for thread in threads:
             if "GET /api/v1/Threads" in thread["Function"] and thread["Name"] == config['tm1srv01']['user']:
                 self.assertTrue(thread["Context"] == app_name)
                 return
     raise Exception("Did not find my own Thread")
Beispiel #23
0
    def setUpClass(cls):
        # Connect to TM1
        cls.tm1 = TM1Service(**config['tm1srv01'])

        # Build 4 Dimensions
        cls.dim1_name = str(uuid.uuid4())
        cls.dim1_element_names = [str(uuid.uuid4()) for _ in range(10)]
        d = Dimension(cls.dim1_name)
        h = Hierarchy(cls.dim1_name, cls.dim1_name)
        for element_name in cls.dim1_element_names:
            h.add_element(element_name, 'Numeric')
        d.add_hierarchy(h)
        cls.tm1.dimensions.create(d)

        cls.dim2_name = str(uuid.uuid4())
        cls.dim2_element_names = [str(uuid.uuid4()) for _ in range(10)]
        d = Dimension(cls.dim2_name)
        h = Hierarchy(cls.dim2_name, cls.dim2_name)
        for element_name in cls.dim2_element_names:
            h.add_element(element_name, 'Numeric')
        d.add_hierarchy(h)
        cls.tm1.dimensions.create(d)

        cls.dim3_name = str(uuid.uuid4())
        cls.dim3_element_names = [str(uuid.uuid4()) for _ in range(10)]
        d = Dimension(cls.dim3_name)
        h = Hierarchy(cls.dim3_name, cls.dim3_name)
        for element_name in cls.dim3_element_names:
            h.add_element(element_name, 'Numeric')
        d.add_hierarchy(h)
        cls.tm1.dimensions.create(d)

        cls.dim4_name = str(uuid.uuid4())
        cls.dim4_element_names = [str(uuid.uuid4()) for _ in range(10)]
        d = Dimension(cls.dim4_name)
        h = Hierarchy(cls.dim4_name, cls.dim4_name)
        for element_name in cls.dim4_element_names:
            h.add_element(element_name, 'Numeric')
        d.add_hierarchy(h)
        cls.tm1.dimensions.create(d)

        # Build Subset
        cls.dim4_subset_Name = "TM1pyTests"
        cls.dim4_subset = cls.tm1.dimensions.subsets.create(
            Subset(subset_name=cls.dim4_subset_Name,
                   dimension_name=cls.dim4_name,
                   hierarchy_name=cls.dim4_name,
                   expression="HEAD([{}].Members, 1)".format(cls.dim4_name)))

        # Build Cube with 4 Dimensions
        cls.cube_name = str(uuid.uuid4())
        cube = Cube(name=cls.cube_name,
                    dimensions=[
                        cls.dim1_name, cls.dim2_name, cls.dim3_name,
                        cls.dim4_name
                    ])
        cls.tm1.cubes.create(cube)
Beispiel #24
0
    def setup_class(cls):
        cls.tm1 = TM1Service(**test_config)
        cls.user_name = str(uuid.uuid4())
        cls.user = User(name=cls.user_name, groups=[], password='******')

        # Create Group for unittests
        cls.group_name = str(uuid.uuid4())
        code = "AddGroup('{}');".format(cls.group_name)
        cls.tm1.processes.execute_ti_code([code])
async def main():
    loop = asyncio.get_event_loop()
    with TM1Service(**config['tm1srv01']) as tm1:
        future1 = loop.run_in_executor(None, execute_mdx, tm1)
        future2 = loop.run_in_executor(None, get_server_name, tm1)
        future3 = loop.run_in_executor(None, read_pnl, tm1)
        future4 = loop.run_in_executor(None, get_all_dimension_names, tm1)
        future5 = loop.run_in_executor(None, get_all_process_names, tm1)
        response1, response, response3, response4, response5 = \
            await future1, await future2, await future3, await future4, await future5
Beispiel #26
0
    def test_update_user_password(self):
        self.tm1.security.update_user_password(user_name=self.user.name,
                                               password="******")

        with TM1Service(user=self.user.name,
                        password="******",
                        base_url=self.tm1._tm1_rest._base_url,
                        ssl=self.tm1._tm1_rest._ssl) as _:
            # if no exception. Login was successful
            pass
Beispiel #27
0
async def main():
    loop = asyncio.get_event_loop()
    with TM1Service(address='localhost', port=12354, user='******', password='******', ssl=True) as tm1:

        future1 = loop.run_in_executor(None, get_product_version, tm1)
        future2 = loop.run_in_executor(None, get_server_name, tm1)
        future3 = loop.run_in_executor(None, read_pnl, tm1)
        future4 = loop.run_in_executor(None, get_all_dimension_names, tm1)
        future5 = loop.run_in_executor(None, get_all_process_names, tm1)
        response1, response, response3, response4, response5 = \
            await future1, await future2, await future3, await future4, await future5
async def main():
    loop = asyncio.get_event_loop()
    with TM1Service(**config['tm1srv01']) as tm1:

        future1 = loop.run_in_executor(None, execute_mdx, tm1, mdx1)
        future2 = loop.run_in_executor(None, execute_mdx, tm1, mdx2)
        future3 = loop.run_in_executor(None, execute_mdx, tm1, mdx3)
        future4 = loop.run_in_executor(None, execute_mdx, tm1, mdx4)
        future5 = loop.run_in_executor(None, execute_mdx, tm1, mdx5)
        response1, response, response3, response4, response5 = \
            await future1, await future2, await future3, await future4, await future5
Beispiel #29
0
def main():
    try:
        tm1_instance = sys.argv[1]
    except:
        logger.fatal("No Instance Specified")

    try:
        file_path = sys.argv[2]
    except:
        logger.fatal("No File Specified")

    if not os.path.isfile(file_path):
        logger.fatal("File not found, exiting")

    default_max_threads = 5
    try:
        max_threads = int(sys.argv[3])
    except:
        max_threads = default_maxthreads
        logger.warning(
            "Max Parallel Threads Not Specified, Default: {}".format(
                default_max_threads))

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    config = configparser.ConfigParser()
    config.read('config.ini')
    logger.info("Reading Config File")
    tis = create_ti_instructions(file_path)
    row_count = sum(1 for row in tis)
    logger.info("Reading file {}, {} lines read".format(file_path, row_count))
    logger.info("Maximum Parallel Threads: {}".format(max_threads))

    try:

        with TM1Service(**config[tm1_instance]) as tm1:
            logger.info("Connecting to: {}".format(
                tm1.server.get_server_name()))
            logger.info("Starting Processes found in: {}".format(file_path))
            start_time = time.clock()
            result = loop.run_until_complete(
                execute_parallel_ti(tm1, tis, max_threads))
            tm1.logout()
            logger.info("Logging Out")
            end_time = time.clock()
            elapsed_time = end_time - start_time
            logger.info("Total Time To Complete {} Processes: {}".Format(
                row_count, elapsed_time))
            loop.close()

    except Exception as e:
        logging.fatal("Unable to Connect to TM1")
        logging.fatal("Connection Error: {}".format(e))
async def main():
    loop = asyncio.get_event_loop()
    with TM1Service(**config['tm1srv01']) as tm1:
        outcomes = list()
        futures = list()
        for _ in range(50):
            futures.append(loop.run_in_executor(None, execute_mdx, tm1, mdx1))
            futures.append(loop.run_in_executor(None, execute_mdx, tm1, mdx2))
            futures.append(loop.run_in_executor(None, execute_mdx, tm1, mdx3))
        for future in futures:
            outcomes.append(await future)
        assert all(outcomes)