Example #1
0
class test_employees(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

    @httpretty.activate
    def test_get_employee_specific_fields(self):
        # Request specific fields
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
                               body='{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123"}',
                               content_type="application/json")

        employee = self.bamboo.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['id'], '123')

    @httpretty.activate
    def test_get_employee_all_fields(self):
        # Request all fields
        # NOTE: We are mocking this so we aren't getting all fields- we are just adding city.
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
                               body='{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123", "city": "Testville"}',
                               content_type="application/json")

        employee = self.bamboo.get_employee(123)
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['city'], 'Testville')
        self.assertEquals(employee['id'], '123')
Example #2
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_urlfetch_stub()
        
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test', api_key='testingnotrealapikey', underscore_keys=True)
Example #3
0
class test_reports(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    # Another instance, using underscore keys
    bamboo_u = None

    # Common report response body:
    body = None

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_urlfetch_stub()
        
        if self.body is None:
            self.body = dumps({"title":"Template","fields":[{"id":"fullName2","type":"text","name":"Last Name, First Name"},{"id":"employeeNumber","type":"employee_number","name":"Employee #"},{"id":"hireDate","type":"date","name":"Hire date"}],"employees":[{"id":"123","fullName2":"Person, Test","employeeNumber":"00001","hireDate":"2010-12-15"},{"id":"124","fullName2":"Guy, Someother","employeeNumber":"00002","hireDate":"2008-10-13"},{"id":"125","fullName2":"Here, Someone","employeeNumber":"00003","hireDate":"2011-03-04"}]})

        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test', api_key='testingnotrealapikey', underscore_keys=True)

    @httpretty.activate
    def test_request_company_report(self):
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/reports/1?format=json&fd=yes",
                               status=200, body=self.body, content_type="application/json")

        result = self.bamboo.request_company_report(1, report_format='json', filter_duplicates=True)
        self.assertIsNotNone(result['fields'])
        self.assertEquals('123', result['employees'][0]['id'])

    @httpretty.activate
    def test_company_report_format_failure(self):
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/reports/1?format=json&fd=yes",
                               status=200, body=self.body, content_type="application/json")

        self.assertRaises(UserWarning, self.bamboo.request_company_report, 1, report_format='gif', filter_duplicates=True)

    @httpretty.activate
    def test_request_custom_report(self):
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/reports/custom/?format=xls",
                               status=200, body=self.body, content_type="application/vnd.ms-excel")

        result = self.bamboo.request_custom_report(['id', 'firstName', 'lastName', 'workEmail'], report_format='xls')
        self.assertEquals(result.headers['status'], '200')
        self.assertEquals(result.headers['content-type'], 'application/vnd.ms-excel')

    @httpretty.activate
    def test_company_custom_format_failure(self):
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/reports/1?format=json&fd=yes",
                               status=200, body=self.body, content_type="application/json")

        self.assertRaises(UserWarning, self.bamboo.request_custom_report, 1, report_format='gif')
Example #4
0
    def setUp(self):
        if self.body is None:
            self.body = dumps({"title":"Template","fields":[{"id":"fullName2","type":"text","name":"Last Name, First Name"},{"id":"employeeNumber","type":"employee_number","name":"Employee #"},{"id":"hireDate","type":"date","name":"Hire date"}],"employees":[{"id":"123","fullName2":"Person, Test","employeeNumber":"00001","hireDate":"2010-12-15"},{"id":"124","fullName2":"Guy, Someother","employeeNumber":"00002","hireDate":"2008-10-13"},{"id":"125","fullName2":"Here, Someone","employeeNumber":"00003","hireDate":"2011-03-04"}]})

        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test', api_key='testingnotrealapikey', underscore_keys=True)
Example #5
0
class test_misc(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

    def test_employee_xml(self):
        employee = {
            'firstName': 'Test',
            'lastName': 'Person'
        }
        xml = self.bamboo._format_employee_xml(employee)
        self.assertIn('<field id="firstName">Test</field>', xml)
        self.assertIn('<field id="lastName">Person</field>', xml)

    def test_init_value_errors(self):
        self.assertRaises(ValueError, PyBambooHR, {'subdomain': 'test'})
        self.assertRaises(ValueError, PyBambooHR, {'api_key': 'testingnotrealapikey'})
        self.assertIsNotNone(PyBambooHR(subdomain='test', api_key='testingnotrealapikey'))
Example #6
0
class test_employees(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    # Another instance, using underscore keys
    bamboo_u = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test',
                                     api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test',
                                       api_key='testingnotrealapikey',
                                       underscore_keys=True)

    @httpretty.activate
    def test_get_employee_directory(self):
        body = {
            "fields": [{
                "id": "displayName",
                "type": "text",
                "name": "Display name"
            }, {
                "id": "firstName",
                "type": "text",
                "name": "First name"
            }, {
                "id": "lastName",
                "type": "text",
                "name": "Last name"
            }, {
                "id": "jobTitle",
                "type": "list",
                "name": "Job title"
            }, {
                "id": "workPhone",
                "type": "text",
                "name": "Work Phone"
            }, {
                "id": "workPhoneExtension",
                "type": "text",
                "name": "Work Extension"
            }, {
                "id": "mobilePhone",
                "type": "text",
                "name": "Mobile Phone"
            }, {
                "id": "workEmail",
                "type": "email",
                "name": "Work Email"
            }, {
                "id": "department",
                "type": "list",
                "name": "Department"
            }, {
                "id": "location",
                "type": "list",
                "name": "Location"
            }, {
                "id": "division",
                "type": "list",
                "name": "Division"
            }, {
                "id": "photoUploaded",
                "type": "bool",
                "name": "Employee photo exists"
            }, {
                "id": "photoUrl",
                "type": "url",
                "name": "Employee photo url"
            }],
            "employees": [{
                "id":
                "123",
                "displayName":
                "Test Person",
                "firstName":
                "Test",
                "lastName":
                "Person",
                "jobTitle":
                "Testing Coordinator",
                "workPhone":
                "555-555-5555",
                "workPhoneExtension":
                "",
                "mobilePhone":
                "555-555-5555",
                "workEmail":
                "*****@*****.**",
                "department":
                "Useless Department",
                "location":
                "Testville, US",
                "division":
                None,
                "photoUploaded":
                False,
                "photoUrl":
                "https://iws.bamboohr.com/images/photo_placeholder.gif"
            }]
        }
        body = dumps(body)
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/directory",
            body=body,
            content_type="application/json")

        employees = self.bamboo.get_employee_directory()
        self.assertIsNotNone(employees[0])
        self.assertEquals('123', employees[0]['id'])
        self.assertEquals('*****@*****.**', employees[0]['workEmail'])

        employees = self.bamboo_u.get_employee_directory()
        self.assertIsNotNone(employees[0])
        self.assertEquals('123', employees[0]['id'])
        self.assertEquals('*****@*****.**', employees[0]['work_email'])

    @httpretty.activate
    def test_get_employee_specific_fields(self):
        # Request specific fields
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
            body=
            '{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123"}',
            content_type="application/json")

        employee = self.bamboo.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['id'], '123')

        employee = self.bamboo_u.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['work_email'], '*****@*****.**')
        self.assertEquals(employee['work_phone'], '555-555-5555')

    @httpretty.activate
    def test_get_employee_custom_fields(self):
        # Request custom fields
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
            body='{"customField": "custom value", "id": "123"}',
            content_type="application/json")

        employee = self.bamboo.get_employee(123, [
            'customCustomField',
        ])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['customField'], 'custom value')
        self.assertEquals(employee['id'], '123')

        employee = self.bamboo_u.get_employee(123, [
            'customCustomField',
        ])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['custom_field'], 'custom value')
        self.assertEquals(employee['id'], '123')

    @httpretty.activate
    def test_get_employee_all_fields(self):
        # Request all fields
        # NOTE: We are mocking this so we aren't getting all fields- we are just adding city.
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
            body=
            '{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123", "city": "Testville"}',
            content_type="application/json")

        employee = self.bamboo.get_employee(123)
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['city'], 'Testville')
        self.assertEquals(employee['id'], '123')

    @httpretty.activate
    def test_add_employee(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/",
            body='',
            status='201',
            adding_headers={
                'location':
                'https://api.bamboohr.com/api/gateway.php/test/v1/employees/333'
            })
        employee = {'firstName': 'Test', 'lastName': 'Person'}
        result = self.bamboo.add_employee(employee)
        self.assertEqual(result['id'], '333')

        # Test adding with underscore keys
        employee = {'first_name': 'Test', 'last_name': 'Person'}
        result = self.bamboo.add_employee(employee)
        self.assertEqual(result['id'], '333')

    @httpretty.activate
    def test_add_employee_failure(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/",
            body='',
            status='400',
            adding_headers={
                'location':
                'https://api.bamboohr.com/api/gateway.php/test/v1/employees/333'
            })
        employee = {}
        self.assertRaises(UserWarning, self.bamboo.add_employee, employee)

    @httpretty.activate
    def test_update_employee(self):
        # Good result
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333",
            body='',
            status='200')
        employee = {'firstName': 'Test', 'lastName': 'Person'}
        result = self.bamboo.update_employee(333, employee)
        self.assertTrue(result)

        # Test updating with underscore keys
        employee = {'first_name': 'Test', 'last_name': 'Person'}
        result = self.bamboo.update_employee(333, employee)
        self.assertTrue(result)

    @httpretty.activate
    def test_update_employee_failure(self):
        # Forbidden result
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333",
            body='',
            status='403')
        employee = {}
        self.assertRaises(HTTPError, self.bamboo.update_employee, 333,
                          employee)

    @httpretty.activate
    def test_get_tabular_data(self):
        xml = """<?xml version="1.0"?>
                 <table>
                     <row id="321" employeeId="123">
                         <field id="customTypeA">Value A</field>
                         <field id="customTypeB">Value B</field>
                         <field id="customTypeC">Value C</field>
                     </row>
                 </table>"""
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123/tables/customTable",
            body=xml,
            content_type="application/xml")
        table = self.bamboo.get_tabular_data('customTable', 123)
        d = {
            '123': [{
                'customTypeA': 'Value A',
                'customTypeB': 'Value B',
                'customTypeC': 'Value C',
                'row_id': '321'
            }]
        }

        self.assertIsNotNone(table)
        self.assertEqual(d, table)

    @httpretty.activate
    def test_get_tabular_data_all_employees(self):
        xml = """<?xml version="1.0"?>
                 <table>
                     <row id="321" employeeId="123">
                         <field id="customTypeA">Value A</field>
                         <field id="customTypeB">Value B</field>
                         <field id="customTypeC">Value C</field>
                     </row>
                     <row id="322" employeeId="333">
                         <field id="customTypeA">333 Value A</field>
                         <field id="customTypeB">333 Value B</field>
                         <field id="customTypeC">333 Value C</field>
                     </row>
                 </table>"""
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/all/tables/customTable",
            body=xml,
            content_type="application/xml")
        table = self.bamboo.get_tabular_data('customTable')
        d = {
            '123': [{
                'customTypeA': 'Value A',
                'customTypeB': 'Value B',
                'customTypeC': 'Value C',
                'row_id': '321'
            }],
            '333': [{
                'customTypeA': '333 Value A',
                'customTypeB': '333 Value B',
                'customTypeC': '333 Value C',
                'row_id': '322'
            }]
        }

        self.assertIsNotNone(table)
        self.assertEqual(d, table)

    @httpretty.activate
    def test_add_row(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333/tables/customTable/",
            body='',
            status='200')

        row = {'custom_type_a': 'New Value A'}
        result = self.bamboo.add_row('customTable', '333', row)

        self.assertTrue(result)

    @httpretty.activate
    def test_add_row_failure(self):
        # Forbidden result
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123/tables/customTable/",
            body='',
            status='406')
        row = {'invalid_id': 'New Value A'}

        self.assertRaises(HTTPError, self.bamboo.add_row, 'customTable', '123',
                          row)

    @httpretty.activate
    def test_update_row(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333/tables/customTable/321/",
            body='',
            status='200')
        row = {'custom_type_a': 'New Value A'}
        result = self.bamboo.update_row('customTable', '333', '321', row)

        self.assertTrue(result)
Example #7
0
class CalendarSync:
    STATUS_MAP = {
        'approved': 'confirmed',
        'denied': 'tentative',
        'declined': 'tentative',
        'requested': 'tentative',
        'canceled': 'cancelled',  # This is what their API is
        'cancelled': 'cancelled'  # Just in case they fix it
    }

    def __init__(self):
        outer_config = Config()
        config = outer_config.get_config()

        try:
            token = config[Config.BAMBOO_SECTION]['token']
        except KeyError:
            # No token - try getting it from username/password
            password = getpass()
            token = CalendarSync.get_api_key(
                config[Config.BAMBOO_SECTION]['company'],
                config[Config.BAMBOO_SECTION]['user'], password)
            outer_config.save_token(token)

        self.bamboohr_client = PyBambooHR(
            config[Config.BAMBOO_SECTION]['company'], token)
        self.gcal_client = GoogleCalendar(
            config[Config.GCAL_SECTION]['calendar_id'])
        self.employee_id = config[Config.BAMBOO_SECTION]['employee_id']

    @staticmethod
    def get_api_key(company, user, password):

        logging.info('Obtaining API Key')
        payload = {
            'user': user,
            'password': password,
            'applicationKey': '3fdb46cdade6088a442be908141eaaada89ff6c9'
        }
        url = 'https://api.bamboohr.com/api/gateway.php/%s/v1/login' % company
        r = requests.post(url,
                          data=payload,
                          headers={'Accept': "application/json"})
        # I have no idea how long this key is valid for. Let's see when it fails
        if r.ok:
            return json.loads(r.text).get('key')
        else:
            raise Exception(
                'Failed to get Access Token. Invalid username/password?')

    def get_time_off_requests(self):
        # Get events up to one year in the past
        start = (date.today() - timedelta(days=365)).isoformat()
        return self.bamboohr_client.get_time_off_requests(
            start_date=start, employee_id=self.employee_id)

    def update_calendar(self, time_off_requests):
        print('Updating/Creating %s items' % len(time_off_requests))
        for booking in time_off_requests:
            event_id = 'emp' + booking['employeeId'] + 'id' + booking['id']
            start = booking['start']
            # Add an extra day, otherwise google will treat it as ending at the start of the last day
            end = (datetime.strptime(booking['end'], '%Y-%m-%d') +
                   timedelta(days=1)).date().isoformat()

            status = booking['status']['status']
            notes = 'Type: ' + booking['type']['name'] + '\n'
            try:
                notes += 'Notes:\n' + '\n'.join([
                    '  ' + str(k) + ': ' + str(v)
                    for k, v in booking['notes'].items()
                ])
            except AttributeError as e:
                pass
            summary = 'Time Booked off: ' + status.title()
            # Set the status to be what google calendars expents
            status = self.STATUS_MAP.get(status, 'tentative')
            logging.debug(
                'Updating Booking: id: %s, start: %s, end: %s, status: %s, summary: %s, notes: %s',
                event_id, start, end, status, summary, notes)
            self.gcal_client.update_event(event_id, start, end, status,
                                          summary, notes)
Example #8
0
def strip_accent(s):
    return ''.join(
        c for c in unicodedata.normalize('NFD', s)
        if unicodedata.category(c) != 'Mn'
    )

if not geteuid() == 0:
    exit('this script must be run as root')

# constants
ON, OFF = [1, 0]

# connect to bambooHR and get the employees' list
bamboo = PyBambooHR(
    subdomain=environ.get('BAMBOOHR_SUBDOMAIN', 'your_subdomain'),
    api_key=environ.get('BAMBOOHR_API_KEY', 'your_api_key')
)
employees = bamboo.get_employee_directory()

try:
    # initialize the LCD screen
    lcd.init()
    lcd.cls()
    lcd.backlight(ON)

    # display the name of each employee
    for employee in employees:
        # clear the screen
        lcd.cls()

        # get the employee first and last name and strip any special character
Example #9
0
 def setUp(self):
     if self.bamboo is None:
         self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')
Example #10
0
class test_misc(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

    def test_employee_xml(self):
        employee = {
            'firstName': 'Test',
            'lastName': 'Person'
        }
        xml = self.bamboo._format_employee_xml(employee)
        self.assertIn('<field id="firstName">Test</field>', xml)
        self.assertIn('<field id="lastName">Person</field>', xml)

    def test_init_value_errors(self):
        self.assertRaises(ValueError, PyBambooHR, {'subdomain': 'test'})
        self.assertRaises(ValueError, PyBambooHR, {'api_key': 'testingnotrealapikey'})
        self.assertIsNotNone(PyBambooHR(subdomain='test', api_key='testingnotrealapikey'))

    def test_xml(self):
        xml = """<?xml version="1.0"?>
                     <table>
                       <row id="321" employeeId="123">
                           <field id="customFieldA">123 Value A</field>
                           <field id="customFieldB">123 Value B</field>
                       </row>
                       <row id="999" employeeId="321">
                           <field id="customFieldA">321 Value A</field>
                           <field id="customFieldB">321 Value B</field>
                       </row>
                     </table>"""
        obj = utils._parse_xml(xml)

        row_id_one = obj['table']['row'][0]['@id']
        row_id_two = obj['table']['row'][1]['@id']

        self.assertEqual('321', row_id_one)
        self.assertEqual('999', row_id_two)

        employee_id_one = obj['table']['row'][0]['@employeeId']
        employee_id_two = obj['table']['row'][1]['@employeeId']

        self.assertEqual('123', employee_id_one)
        self.assertEqual('321', employee_id_two)

        rows = utils._extract(obj, 'table', 'row')

        self.assertEqual('123 Value A', rows[0]['field'][0]['#text'])
        self.assertEqual('123 Value B', rows[0]['field'][1]['#text'])

        self.assertEqual('321 Value A', rows[1]['field'][0]['#text'])
        self.assertEqual('321 Value B', rows[1]['field'][1]['#text'])

    def test_make_field_xml(self):
        xml = utils.make_field_xml('123', 'T&C')
        self.assertEqual('<field id="123">T&amp;C</field>', xml)

        xml = utils.make_field_xml('123', 'T&C', pre='\t', post='\n')
        self.assertEqual('\t<field id="123">T&amp;C</field>\n', xml)

        xml = utils.make_field_xml('123', None, pre='\t', post='\n')
        self.assertEqual('\t<field id="123" />\n', xml)
        pass

    def test__format_row_xml(self):
        row = {'f1': 'v1', 'f2': 'v2'}
        xml = self.bamboo._format_row_xml(row)
        self.assertIn('<field id="f1">v1</field>', xml)
        self.assertIn('<field id="f2">v2</field>', xml)

    def test_transform_tabular_data(self):
        xml = """<?xml version="1.0"?>
                 <table>
                   <row id="321" employeeId="123">
                     <field id="customFieldA">123 Value A</field>
                     <field id="customFieldB">123 Value B</field>
                   </row>
                   <row id="999" employeeId="321">
                     <field id="customFieldA">321 &amp; Value A</field>
                   </row>
                 </table>"""
        table = {'123': [{
                         'customFieldA': '123 Value A',
                         'customFieldB': '123 Value B',
                         'row_id': '321'}],
                 '321': [{
                         'customFieldA': '321 & Value A',
                         'row_id': '999'}]}
        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_tabular_data_single_row(self):
        xml = """<?xml version="1.0"?>
                 <table>
                   <row id="321" employeeId="123">
                     <field id="customFieldA">123 Value A</field>
                   </row>
                 </table>"""
        table = {'123': [{'customFieldA': '123 Value A', 'row_id': '321'}]}
        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_tabular_data_empty_table(self):
        xml = """<?xml version="1.0"?>
                     <table/>"""
        table = {}
        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_tabular_data_empty_field(self):
        xml = """<?xml version="1.0"?>
                 <table>
                   <row id="321" employeeId="123">
                     <field id="customFieldA">123 Value A</field>
                     <field id="customFieldC"></field>
                   </row>
                   <row id="999" employeeId="321">
                     <field id="customFieldB">321 Value B</field>
                   </row>
                 </table>"""
        table = {'123': [{'customFieldA': '123 Value A',
                          'customFieldC': None,
                          'row_id': '321'}],
                 '321': [{'customFieldB': '321 Value B',
                          'row_id': '999'}]}

        self.assertEqual(table, utils.transform_tabular_data(xml))
Example #11
0
 def setUp(self):
     if self.bamboo is None:
         self.bamboo = PyBambooHR(subdomain='test',
                                  api_key='testingnotrealapikey')
Example #12
0
class test_reports(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    # Another instance, using underscore keys
    bamboo_u = None

    # Common report response body:
    body = None

    def setUp(self):
        if self.body is None:
            self.body = dumps({
                "title":
                "Template",
                "fields": [{
                    "id": "fullName2",
                    "type": "text",
                    "name": "Last Name, First Name"
                }, {
                    "id": "employeeNumber",
                    "type": "employee_number",
                    "name": "Employee #"
                }, {
                    "id": "hireDate",
                    "type": "date",
                    "name": "Hire date"
                }],
                "employees": [{
                    "id": "123",
                    "fullName2": "Person, Test",
                    "employeeNumber": "00001",
                    "hireDate": "2010-12-15"
                }, {
                    "id": "124",
                    "fullName2": "Guy, Someother",
                    "employeeNumber": "00002",
                    "hireDate": "2008-10-13"
                }, {
                    "id": "125",
                    "fullName2": "Here, Someone",
                    "employeeNumber": "00003",
                    "hireDate": "2011-03-04"
                }]
            })

        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test',
                                     api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test',
                                       api_key='testingnotrealapikey',
                                       underscore_keys=True)

    @httpretty.activate
    def test_request_company_report(self):
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/reports/1?format=json&fd=yes",
            status=200,
            body=self.body,
            content_type="application/json")

        result = self.bamboo.request_company_report(1,
                                                    report_format='json',
                                                    filter_duplicates=True)
        self.assertIsNotNone(result['fields'])
        self.assertEquals('123', result['employees'][0]['id'])

    @httpretty.activate
    def test_company_report_format_failure(self):
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/reports/1?format=json&fd=yes",
            status=200,
            body=self.body,
            content_type="application/json")

        self.assertRaises(UserWarning,
                          self.bamboo.request_company_report,
                          1,
                          report_format='gif',
                          filter_duplicates=True)

    @httpretty.activate
    def test_request_custom_report(self):
        httpretty.register_uri(
            httpretty.POST,
            "https://api.bamboohr.com/api/gateway.php/test/v1/reports/custom/?format=xls",
            status=200,
            body=self.body,
            content_type="application/vnd.ms-excel")

        result = self.bamboo.request_custom_report(
            ['id', 'firstName', 'lastName', 'workEmail'], report_format='xls')
        self.assertEquals(result.headers['status'], '200')
        self.assertEquals(result.headers['content-type'],
                          'application/vnd.ms-excel')

    @httpretty.activate
    def test_company_custom_format_failure(self):
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/reports/1?format=json&fd=yes",
            status=200,
            body=self.body,
            content_type="application/json")

        self.assertRaises(UserWarning,
                          self.bamboo.request_custom_report,
                          1,
                          report_format='gif')
Example #13
0
class test_employees(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    # Another instance, using underscore keys
    bamboo_u = None

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_urlfetch_stub()
        
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test', api_key='testingnotrealapikey', underscore_keys=True)

    @httpretty.activate
    def test_get_employee_directory(self):
        body = {"fields": [
            {
                "id": "displayName",
                "type": "text",
                "name": "Display name"
            },
            {
                "id": "firstName",
                "type": "text",
                "name": "First name"
            },
            {
                "id": "lastName",
                "type": "text",
                "name": "Last name"
            },
            {
                "id": "jobTitle",
                "type": "list",
                "name": "Job title"
            },
            {
                "id": "workPhone",
                "type": "text",
                "name": "Work Phone"
            },
            {
                "id": "workPhoneExtension",
                "type": "text",
                "name": "Work Extension"
            },
            {
                "id": "mobilePhone",
                "type": "text",
                "name": "Mobile Phone"
            },
            {
                "id": "workEmail",
                "type": "email",
                "name": "Work Email"
            },
            {
                "id": "department",
                "type": "list",
                "name": "Department"
            },
            {
                "id": "location",
                "type": "list",
                "name": "Location"
            },
            {
                "id": "division",
                "type": "list",
                "name": "Division"
            },
            {
                "id": "photoUploaded",
                "type": "bool",
                "name": "Employee photo exists"
            },
            {
                "id": "photoUrl",
                "type": "url",
                "name": "Employee photo url"
            }],
            "employees": [
                {
                    "id": "123",
                    "displayName": "Test Person",
                    "firstName": "Test",
                    "lastName": "Person",
                    "jobTitle": "Testing Coordinator",
                    "workPhone": "555-555-5555",
                    "workPhoneExtension": "",
                    "mobilePhone": "555-555-5555",
                    "workEmail": "*****@*****.**",
                    "department": "Useless Department",
                    "location": "Testville, US",
                    "division":  None,
                    "photoUploaded":  False,
                    "photoUrl": "https://iws.bamboohr.com/images/photo_placeholder.gif"
                }]
        }
        body = dumps(body)
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/directory",
                               body=body, content_type="application/json")

        employees = self.bamboo.get_employee_directory()
        self.assertIsNotNone(employees[0])
        self.assertEquals('123', employees[0]['id'])
        self.assertEquals('*****@*****.**', employees[0]['workEmail'])

        employees = self.bamboo_u.get_employee_directory()
        self.assertIsNotNone(employees[0])
        self.assertEquals('123', employees[0]['id'])
        self.assertEquals('*****@*****.**', employees[0]['work_email'])

    @httpretty.activate
    def test_get_employee_specific_fields(self):
        # Request specific fields
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
                               body='{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123"}',
                               content_type="application/json")

        employee = self.bamboo.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['id'], '123')

        employee = self.bamboo_u.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['work_email'], '*****@*****.**')
        self.assertEquals(employee['work_phone'], '555-555-5555')

    @httpretty.activate
    def test_get_employee_all_fields(self):
        # Request all fields
        # NOTE: We are mocking this so we aren't getting all fields- we are just adding city.
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
                               body='{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123", "city": "Testville"}',
                               content_type="application/json")

        employee = self.bamboo.get_employee(123)
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['city'], 'Testville')
        self.assertEquals(employee['id'], '123')

    @httpretty.activate
    def test_add_employee(self):
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/",
                               body='', status='201', adding_headers={'location': 'https://api.bamboohr.com/api/gateway.php/test/v1/employees/333'})
        employee = {
            'firstName': 'Test',
            'lastName': 'Person'
        }
        result = self.bamboo.add_employee(employee)
        self.assertEqual(result['id'], '333')

        # Test adding with underscore keys
        employee = {
            'first_name': 'Test',
            'last_name': 'Person'
        }
        result = self.bamboo.add_employee(employee)
        self.assertEqual(result['id'], '333')

    @httpretty.activate
    def test_add_employee_failure(self):
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/",
                               body='', status='400', adding_headers={'location': 'https://api.bamboohr.com/api/gateway.php/test/v1/employees/333'})
        employee = {}
        self.assertRaises(UserWarning, self.bamboo.add_employee, employee)

    @httpretty.activate
    def test_update_employee(self):
        # Good result
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333", body='', status='200')
        employee = {
            'firstName': 'Test',
            'lastName': 'Person'
        }
        result = self.bamboo.update_employee(333, employee)
        self.assertTrue(result)

        # Test updating with underscore keys
        employee = {
            'first_name': 'Test',
            'last_name': 'Person'
        }
        result = self.bamboo.update_employee(333, employee)
        self.assertTrue(result)

    @httpretty.activate
    def test_update_employee_failure(self):
        # Forbidden result
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333", body='', status='403')
        employee = {}
        self.assertRaises(HTTPError, self.bamboo.update_employee, 333, employee)

    @httpretty.activate
    def test_get_tabular_data(self):
        xml = """<?xml version="1.0"?>
                 <table>
                     <row id="321" employeeId="123">
                         <field id="customTypeA">Value A</field>
                         <field id="customTypeB">Value B</field>
                         <field id="customTypeC">Value C</field>
                     </row>
                 </table>"""
        httpretty.register_uri(httpretty.GET,
                               "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123/tables/customTable",
                               body=xml,
                               content_type="application/xml")
        table = self.bamboo.get_tabular_data('customTable', 123)
        d = {'123': [{'customTypeA': 'Value A',
                      'customTypeB': 'Value B',
                      'customTypeC': 'Value C',
                      'row_id': '321'}]}

        self.assertIsNotNone(table)
        self.assertEqual(d, table)

    @httpretty.activate
    def test_get_tabular_data_all_employees(self):
        xml = """<?xml version="1.0"?>
                 <table>
                     <row id="321" employeeId="123">
                         <field id="customTypeA">Value A</field>
                         <field id="customTypeB">Value B</field>
                         <field id="customTypeC">Value C</field>
                     </row>
                     <row id="322" employeeId="333">
                         <field id="customTypeA">333 Value A</field>
                         <field id="customTypeB">333 Value B</field>
                         <field id="customTypeC">333 Value C</field>
                     </row>
                 </table>"""
        httpretty.register_uri(httpretty.GET,
                               "https://api.bamboohr.com/api/gateway.php/test/v1/employees/all/tables/customTable",
                               body=xml,
                               content_type="application/xml")
        table = self.bamboo.get_tabular_data('customTable')
        d = {'123': [{'customTypeA': 'Value A',
                      'customTypeB': 'Value B',
                      'customTypeC': 'Value C',
                      'row_id': '321'}],
             '333': [{'customTypeA': '333 Value A',
                      'customTypeB': '333 Value B',
                      'customTypeC': '333 Value C',
                      'row_id': '322'}]}

        self.assertIsNotNone(table)
        self.assertEqual(d, table)

    @httpretty.activate
    def test_add_row(self):
        httpretty.register_uri(httpretty.POST,
                               "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333/tables/customTable/",
                               body='',
                               status='200')

        row = {'custom_type_a': 'New Value A'}
        result = self.bamboo.add_row('customTable', '333', row)

        self.assertTrue(result)

    @httpretty.activate
    def test_add_row_failure(self):
        # Forbidden result
        httpretty.register_uri(httpretty.POST,
                               "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123/tables/customTable/",
                               body='',
                               status='406')
        row = {'invalid_id': 'New Value A'}

        self.assertRaises(HTTPError, self.bamboo.add_row, 'customTable', '123', row)

    @httpretty.activate
    def test_update_row(self):
        httpretty.register_uri(httpretty.POST,
                               "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333/tables/customTable/321/",
                               body='',
                               status='200')
        row = {'custom_type_a': 'New Value A'}
        result = self.bamboo.update_row('customTable', '333', '321', row)

        self.assertTrue(result)
Example #14
0

def strip_accent(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s)
                   if unicodedata.category(c) != 'Mn')


if not geteuid() == 0:
    exit('this script must be run as root')

# constants
ON, OFF = [1, 0]

# connect to bambooHR and get the employees' list
bamboo = PyBambooHR(subdomain=environ.get('BAMBOOHR_SUBDOMAIN',
                                          'your_subdomain'),
                    api_key=environ.get('BAMBOOHR_API_KEY', 'your_api_key'))
employees = bamboo.get_employee_directory()

try:
    # initialize the LCD screen
    lcd.init()
    lcd.cls()
    lcd.backlight(ON)

    # display the photo of each employee with his first name
    # next to it
    for employee in employees:
        # get the jpg photo and convert it to a usable bitmap
        img = urllib.urlretrieve(employee.get('photoUrl'))[0]
        bmp = Image.open(img)
Example #15
0
class test_time_off(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test',
                                     api_key='testingnotrealapikey')

    @httpretty.activate
    def test_get_time_off_requests(self):
        body = [{
            "id": "1342",
            "employeeId": "4",
            "status": {
                "lastChanged": "2019-09-12",
                "lastChangedByUserId": "2369",
                "status": "approved"
            },
            "name": "Charlotte Abbott",
            "start": "2019-05-30",
            "end": "2019-06-01",
            "created": "2019-09-11",
            "type": {
                "id": "78",
                "name": "Vacation",
                "icon": "palm-trees"
            },
            "amount": {
                "unit": "hours",
                "amount": "24"
            },
            "actions": {
                "view": True,
                "edit": True,
                "cancel": False,
                "approve": False,
                "deny": False,
                "bypass": False
            },
            "dates": {
                "2019-05-30": "24"
            },
            "notes": {
                "manager": "Home sick with the flu."
            }
        }]
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/time_off/requests",
            body=dumps(body),
            content_type="application/json")

        response = self.bamboo.get_time_off_requests()
        self.assertIsNotNone(response)
        self.assertTrue(len(response) > 0)
        self.assertEquals(response[0]['id'], '1342')
        return

    @httpretty.activate
    def test_get_time_off_policies(self):
        body = [{
            'id': '70',
            'timeOffTypeId': '77',
            'name': 'Testing Manual Policy',
            'effectiveDate': None,
            'type': 'manual'
        }]
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/meta/time_off/policies",
            body=dumps(body),
            content_type="application/json")
        response = self.bamboo.get_time_off_policies()
        self.assertIsNotNone(response)
        self.assertTrue(len(response) > 0)
        self.assertEquals(response[0]['id'], '70')
        return

    @httpretty.activate
    def test_get_time_off_types(self):
        body = {
            'timeOffTypes': [{
                'id': '78',
                'name': 'Vacation',
                'units': 'hours',
                'color': None,
                'icon': 'palm-trees'
            }]
        }
        httpretty.register_uri(
            httpretty.GET,
            "https://api.bamboohr.com/api/gateway.php/test/v1/meta/time_off/types",
            body=dumps(body),
            content_type="application/json")
        response = self.bamboo.get_time_off_types()
        self.assertIsNotNone(response)
        self.assertTrue(len(response) > 0)
        self.assertEquals(response[0]['id'], '78')
        return

    @httpretty.activate
    def test_create_time_off_request(self):
        body = {
            'id':
            '1675',
            'employeeId':
            '111',
            'start':
            '2040-02-01',
            'end':
            '2040-02-02',
            'created':
            '2019-12-24',
            'status': {
                'status': 'requested',
                'lastChanged': '2019-12-24 02:29:45',
                'lastChangedByUserId': '2479'
            },
            'name':
            'xdd xdd',
            'type': {
                'id': '78',
                'name': 'Vacation'
            },
            'amount': {
                'unit': 'hours',
                'amount': '2'
            },
            'notes': {
                'employee': 'Going overseas with family',
                'manager': 'Enjoy!'
            },
            'dates': {
                '2040-02-01': '1',
                '2040-02-02': '1'
            },
            'comments': [{
                'employeeId': '111',
                'comment': 'Enjoy!',
                'commentDate': '2019-12-24',
                'commenterName': 'Test use'
            }],
            'approvers': [{
                'userId':
                '2479',
                'displayName':
                'Test user',
                'employeeId':
                '111',
                'photoUrl':
                'https://resources.bamboohr.com/employees/photos/initials.php?initials=testuser'
            }],
            'actions': {
                'view': True,
                'edit': True,
                'cancel': True,
                'approve': True,
                'deny': True,
                'bypass': True
            },
            'policyType':
            'discretionary',
            'usedYearToDate':
            0,
            'balanceOnDateOfRequest':
            0
        }
        httpretty.register_uri(
            httpretty.PUT,
            "https://api.bamboohr.com/api/gateway.php/test/v1/employees/111/time_off/request",
            body=dumps(body),
            content_type="application/json")
        data = {
            'status':
            'requested',
            'employee_id':
            '111',
            'start':
            '2040-02-01',
            'end':
            '2040-02-02',
            'timeOffTypeId':
            '78',
            'amount':
            '2',
            'dates': [{
                'ymd': '2040-02-01',
                'amount': '1'
            }, {
                'ymd': '2040-02-02',
                'amount': '1'
            }],
            'notes': [{
                'type': 'employee',
                'text': 'Going overseas with family'
            }, {
                'type': 'manager',
                'text': 'Enjoy!'
            }]
        }
        response = self.bamboo.create_time_off_request(data)
        self.assertIsNotNone(response)
        self.assertEquals(response['id'], '1675')
        return

    @httpretty.activate
    def test_update_time_off_request_status(self):
        body = {
            'id':
            '1675',
            'employeeId':
            '111',
            'start':
            '2040-02-01',
            'end':
            '2040-02-02',
            'created':
            '2019-12-24',
            'status': {
                'status': 'declined',
                'lastChanged': '2019-12-24 02:29:45',
                'lastChangedByUserId': '2479'
            },
            'name':
            'xdd xdd',
            'type': {
                'id': '78',
                'name': 'Vacation'
            },
            'amount': {
                'unit': 'hours',
                'amount': '2'
            },
            'notes': {
                'employee': 'Going overseas with family',
                'manager': 'Enjoy!'
            },
            'dates': {
                '2040-02-01': '1',
                '2040-02-02': '1'
            },
            'comments': [{
                'employeeId': '111',
                'comment': 'Enjoy!',
                'commentDate': '2019-12-24',
                'commenterName': 'Test use'
            }],
            'approvers': [{
                'userId':
                '2479',
                'displayName':
                'Test user',
                'employeeId':
                '111',
                'photoUrl':
                'https://resources.bamboohr.com/employees/photos/initials.php?initials=testuser'
            }],
            'actions': {
                'view': True,
                'edit': True,
                'cancel': True,
                'approve': True,
                'deny': True,
                'bypass': True
            },
            'policyType':
            'discretionary',
            'usedYearToDate':
            0,
            'balanceOnDateOfRequest':
            0
        }
        httpretty.register_uri(
            httpretty.PUT,
            "https://api.bamboohr.com/api/gateway.php/test/v1/time_off/requests/1675/status",
            body=dumps(body),
            content_type="application/json")
        data = {'status': 'declined', 'note': 'Have fun!'}
        response = self.bamboo.update_time_off_request_status(body['id'], data)
        self.assertIsNotNone(response)
        self.assertTrue(response)
        return
Example #16
0
    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test', api_key='testingnotrealapikey', underscore_keys=True)
Example #17
0
class test_employees(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    # Another instance, using underscore keys
    bamboo_u = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test', api_key='testingnotrealapikey')

        if self.bamboo_u is None:
            self.bamboo_u = PyBambooHR(subdomain='test', api_key='testingnotrealapikey', underscore_keys=True)

    @httpretty.activate
    def test_get_employee_directory(self):
        body = {"fields":[
        {
            "id":"displayName",
            "type":"text",
            "name":"Display name"
        },
        {
            "id":"firstName",
            "type":"text",
            "name":"First name"
        },
        {
            "id":"lastName",
            "type":"text",
            "name":"Last name"
        },
        {
            "id":"jobTitle",
            "type":"list",
            "name":"Job title"
        },
        {
            "id":"workPhone",
            "type":"text",
            "name":"Work Phone"
        },
        {
            "id":"workPhoneExtension",
            "type":"text",
            "name":"Work Extension"
        },
        {
            "id":"mobilePhone",
            "type":"text",
            "name":"Mobile Phone"
        },
        {
            "id":"workEmail",
            "type":"email",
            "name":"Work Email"
        },
        {
            "id":"department",
            "type":"list",
            "name":"Department"
        },
        {
            "id":"location",
            "type":"list",
            "name":"Location"
        },
        {
            "id":"division",
            "type":"list",
            "name":"Division"
        },
        {
            "id":"photoUploaded",
            "type":"bool",
            "name":"Employee photo exists"
        },
        {
            "id":"photoUrl",
            "type":"url",
            "name":"Employee photo url"
        }
        ],"employees":[
        {
        "id":"123",
        "displayName":"Test Person",
        "firstName":"Test",
        "lastName":"Person",
        "jobTitle":"Testing Coordinator",
        "workPhone":"555-555-5555",
        "workPhoneExtension":"",
        "mobilePhone":"555-555-5555",
        "workEmail":"*****@*****.**",
        "department":"Useless Department",
        "location":"Testville, US",
        "division": None,
        "photoUploaded": False,
        "photoUrl":"https://iws.bamboohr.com/images/photo_placeholder.gif"
        }]
        }
        body = dumps(body)
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/directory",
                               body=body, content_type="application/json")

        employees = self.bamboo.get_employee_directory()
        self.assertIsNotNone(employees[0])
        self.assertEquals('123', employees[0]['id'])
        self.assertEquals('*****@*****.**', employees[0]['workEmail'])

        employees = self.bamboo_u.get_employee_directory()
        self.assertIsNotNone(employees[0])
        self.assertEquals('123', employees[0]['id'])
        self.assertEquals('*****@*****.**', employees[0]['work_email'])

    @httpretty.activate
    def test_get_employee_specific_fields(self):
        # Request specific fields
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
                               body='{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123"}',
                               content_type="application/json")

        employee = self.bamboo.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['id'], '123')

        employee = self.bamboo_u.get_employee(123, ['workPhone', 'workEmail'])
        self.assertIsNotNone(employee)
        self.assertEquals(employee['work_email'], '*****@*****.**')
        self.assertEquals(employee['work_phone'], '555-555-5555')

    @httpretty.activate
    def test_get_employee_all_fields(self):
        # Request all fields
        # NOTE: We are mocking this so we aren't getting all fields- we are just adding city.
        httpretty.register_uri(httpretty.GET, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/123",
                               body='{"workEmail": "*****@*****.**", "workPhone": "555-555-5555", "id": "123", "city": "Testville"}',
                               content_type="application/json")

        employee = self.bamboo.get_employee(123)
        self.assertIsNotNone(employee)
        self.assertEquals(employee['workEmail'], '*****@*****.**')
        self.assertEquals(employee['workPhone'], '555-555-5555')
        self.assertEquals(employee['city'], 'Testville')
        self.assertEquals(employee['id'], '123')

    @httpretty.activate
    def test_add_employee(self):
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/",
                               body='', status='201', adding_headers={'location': 'https://api.bamboohr.com/api/gateway.php/test/v1/employees/333'})
        employee = {
            'firstName': 'Test',
            'lastName': 'Person'
        }
        result = self.bamboo.add_employee(employee)
        self.assertEqual(result['id'], '333')

        # Test adding with underscore keys
        employee = {
            'first_name': 'Test',
            'last_name': 'Person'
        }
        result = self.bamboo.add_employee(employee)
        self.assertEqual(result['id'], '333')

    @httpretty.activate
    def test_add_employee_failure(self):
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/",
                               body='', status='400', adding_headers={'location': 'https://api.bamboohr.com/api/gateway.php/test/v1/employees/333'})
        employee = {}
        self.assertRaises(UserWarning, self.bamboo.add_employee, employee)

    @httpretty.activate
    def test_update_employee(self):
        # Good result
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333", body='', status='200')
        employee = {
            'firstName': 'Test',
            'lastName': 'Person'
        }
        result = self.bamboo.update_employee(333, employee)
        self.assertTrue(result)

        # Test updating with underscore keys
        employee = {
            'first_name': 'Test',
            'last_name': 'Person'
        }
        result = self.bamboo.update_employee(333, employee)
        self.assertTrue(result)

    @httpretty.activate
    def test_update_employee_failure(self):
        # Forbidden result
        httpretty.register_uri(httpretty.POST, "https://api.bamboohr.com/api/gateway.php/test/v1/employees/333", body='', status='403')
        employee = {}
        self.assertRaises(HTTPError, self.bamboo.update_employee, 333, employee)
Example #18
0
from PyBambooHR import PyBambooHR

bamboo = PyBambooHR.PyBambooHR(subdomain='', api_key='')

# Use the ID to request json information
# result = bamboo.request_company_report(1, format='json', filter_duplicates=True)
result = bamboo.request_company_report(1, filter_duplicates=True)

# Now do stuff with your results (Will vary by report.)
for employee in result['employees']:
    print(employee)
Example #19
0
 def test_init_value_errors(self):
     self.assertRaises(ValueError, PyBambooHR, {'subdomain': 'test'})
     self.assertRaises(ValueError, PyBambooHR,
                       {'api_key': 'testingnotrealapikey'})
     self.assertIsNotNone(
         PyBambooHR(subdomain='test', api_key='testingnotrealapikey'))
Example #20
0
class test_misc(unittest.TestCase):
    # Used to store the cached instance of PyBambooHR
    bamboo = None

    def setUp(self):
        if self.bamboo is None:
            self.bamboo = PyBambooHR(subdomain='test',
                                     api_key='testingnotrealapikey')

    def test_employee_xml(self):
        employee = {'firstName': 'Test', 'lastName': 'Person'}
        xml = self.bamboo._format_employee_xml(employee)
        self.assertIn('<field id="firstName">Test</field>', xml)
        self.assertIn('<field id="lastName">Person</field>', xml)

    def test_xml(self):
        xml = """<?xml version="1.0"?>
                     <table>
                       <row id="321" employeeId="123">
                           <field id="customFieldA">123 Value A</field>
                           <field id="customFieldB">123 Value B</field>
                       </row>
                       <row id="999" employeeId="321">
                           <field id="customFieldA">321 Value A</field>
                           <field id="customFieldB">321 Value B</field>
                       </row>
                     </table>"""
        obj = utils._parse_xml(xml)

        row_id_one = obj['table']['row'][0]['@id']
        row_id_two = obj['table']['row'][1]['@id']

        self.assertEqual('321', row_id_one)
        self.assertEqual('999', row_id_two)

        employee_id_one = obj['table']['row'][0]['@employeeId']
        employee_id_two = obj['table']['row'][1]['@employeeId']

        self.assertEqual('123', employee_id_one)
        self.assertEqual('321', employee_id_two)

        rows = utils._extract(obj, 'table', 'row')

        self.assertEqual('123 Value A', rows[0]['field'][0]['#text'])
        self.assertEqual('123 Value B', rows[0]['field'][1]['#text'])

        self.assertEqual('321 Value A', rows[1]['field'][0]['#text'])
        self.assertEqual('321 Value B', rows[1]['field'][1]['#text'])

    def test_make_field_xml(self):
        xml = utils.make_field_xml('123', 'T&C')
        self.assertEqual('<field id="123">T&amp;C</field>', xml)

        xml = utils.make_field_xml('123', 'T&C', pre='\t', post='\n')
        self.assertEqual('\t<field id="123">T&amp;C</field>\n', xml)

        xml = utils.make_field_xml('123', None, pre='\t', post='\n')
        self.assertEqual('\t<field id="123" />\n', xml)
        pass

    def test__format_row_xml(self):
        row = {'f1': 'v1', 'f2': 'v2'}
        xml = self.bamboo._format_row_xml(row)
        self.assertIn('<field id="f1">v1</field>', xml)
        self.assertIn('<field id="f2">v2</field>', xml)

    def test_transform_tabular_data(self):
        xml = """<?xml version="1.0"?>
                 <table>
                   <row id="321" employeeId="123">
                     <field id="customFieldA">123 Value A</field>
                     <field id="customFieldB">123 Value B</field>
                   </row>
                   <row id="999" employeeId="321">
                     <field id="customFieldA">321 &amp; Value A</field>
                   </row>
                 </table>"""
        table = {
            '123': [{
                'customFieldA': '123 Value A',
                'customFieldB': '123 Value B',
                'row_id': '321'
            }],
            '321': [{
                'customFieldA': '321 & Value A',
                'row_id': '999'
            }]
        }
        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_tabular_data_single_row(self):
        xml = """<?xml version="1.0"?>
                 <table>
                   <row id="321" employeeId="123">
                     <field id="customFieldA">123 Value A</field>
                   </row>
                 </table>"""
        table = {'123': [{'customFieldA': '123 Value A', 'row_id': '321'}]}
        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_tabular_data_empty_table(self):
        xml = """<?xml version="1.0"?>
                     <table/>"""
        table = {}
        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_tabular_data_empty_field(self):
        xml = """<?xml version="1.0"?>
                 <table>
                   <row id="321" employeeId="123">
                     <field id="customFieldA">123 Value A</field>
                     <field id="customFieldC"></field>
                   </row>
                   <row id="999" employeeId="321">
                     <field id="customFieldB">321 Value B</field>
                   </row>
                 </table>"""
        table = {
            '123': [{
                'customFieldA': '123 Value A',
                'customFieldC': None,
                'row_id': '321'
            }],
            '321': [{
                'customFieldB': '321 Value B',
                'row_id': '999'
            }]
        }

        self.assertEqual(table, utils.transform_tabular_data(xml))

    def test_transform_json_tabular_data(self):
        json_data = [[{
            "id": 321,
            "employeeId": 123,
            "customFieldA": "123 Value A",
            "customFieldB": "123 Value B",
        }, {
            "id": 999,
            "employeeId": 321,
            "customFieldA": "321 & Value A",
        }]]
        table = {
            '123': [{
                'customFieldA': '123 Value A',
                'customFieldB': '123 Value B',
                'row_id': '321'
            }],
            '321': [{
                'customFieldA': '321 & Value A',
                'row_id': '999'
            }]
        }
        self.assertEqual(table, utils.transform_json_tabular_data(json_data))

    def test_transform_json_tabular_data_single_row(self):
        json_data = [[{
            "id": 321,
            "employeeId": 123,
            "customFieldA": "123 Value A",
        }]]
        table = {'123': [{'customFieldA': '123 Value A', 'row_id': '321'}]}
        self.assertEqual(table, utils.transform_json_tabular_data(json_data))

    def test_transform_json_tabular_data_empty_table(self):
        json_data = [[{}]]
        table = {}
        self.assertEqual(table, utils.transform_json_tabular_data(json_data))

    def test_transform_json_tabular_data_empty_field(self):
        json_data = [[{
            "id": 321,
            "employeeId": 123,
            "customFieldA": "123 Value A",
            "customFieldC": None,
        }, {
            "id": 999,
            "employeeId": 321,
            "customFieldB": "321 Value B",
        }]]
        table = {
            '123': [{
                'customFieldA': '123 Value A',
                'customFieldC': None,
                'row_id': '321'
            }],
            '321': [{
                'customFieldB': '321 Value B',
                'row_id': '999'
            }]
        }

        self.assertEqual(table, utils.transform_json_tabular_data(json_data))
Example #21
0
"""Core classes utilized to wrap BambooHR objects."""

import os
import uuid

from datetime import date, datetime
from dateutil.parser import parse

from PyBambooHR import PyBambooHR

from icalendar import Event

CLIENT = PyBambooHR.PyBambooHR(subdomain=os.environ.get('BAMBOOHR_SUBDOMAIN', ''),
                               api_key=os.environ.get('BAMBOOHR_API_KEY', ''))


class Company(object):
    """Class to house zero to many Employee objects."""

    def get_employees(self):
        """Returns a list of Employee objects.

        Returns:
            list: A list of Employee objects.
        """
        return [Employee(e) for e in CLIENT.get_employee_directory()]


class Employee(object):
    """Class to represent an employee with support for iCal."""