def test_egrep_word_list(self): """ Test egrep with valid choice regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) result = test_file.egrep('(host|bird)') self.assertTrue(result) self.assertIsInstance(result, list)
def test_good_regex(self): """ Test egrep with valid wildcard regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) result = test_file.egrep('.*rd') self.assertTrue(result) self.assertIsInstance(result, list)
def test_egrep_no_matches(self): """ Test egrep with valid regex but pattern not in file. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) result = test_file.egrep('^this is not present in file.*') self.assertTrue(result is False) self.assertIsInstance(result, bool)
def test_egrep_word(self): """ Test egrep with a word. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) result = test_file.egrep('bird') self.assertTrue(result) self.assertIsInstance(result, list)
def test_egrep_string_start(self): """ Test egrep with valid regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) result = test_file.egrep('^10.*') self.assertTrue(len(result) == 5) self.assertIsInstance(result, list)
def test_replace_whole_line(self): """ Test substitute a line. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) old = '172.19.18.17 freebird.example.com' new = '172.19.18.17 freebird.example.com # Added 1976.10.29 -jh' self.assertTrue(test_file.replace(old, new))
def test_add_failure_param(self): """ Test wrong param type. """ test_file = FileAsObj() with self.assertRaises(TypeError): test_file.add(1) with self.assertRaises(TypeError): test_file.add(True)
def example_add_list_of_lines_to_file(): """ Add a list() of strings, each on its own line. Same as the previous example you can use .append() or '+'. """ my_file = FileAsObj('/tmp/example_file.txt') lines_to_add = ['simultaneous', 'money shot', 'remedy'] my_file.add(lines_to_add)
def test_bad_regex(self): """ Test egrep with invalid regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) try: test_file.egrep('*rd') except Exception as error: self.assertEqual('nothing to repeat', str(error))
def test_egrep_char_list(self): """ Test egrep with valid character selector regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) subject = 'h[o0]stname' result = test_file.egrep(subject) self.assertTrue(result) self.assertIsInstance(result, list)
def test_grep_matches(self): """ Test grep substring present in file, multiple match. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) subject = 'www01' result = test_file.egrep(subject) self.assertTrue(result) self.assertTrue(result == ['10.2.5.2 www01 www01.example.tld', '#172.8.8.8 www01 www01.example.tld'])
def test_grep_match(self): """ Test grep substring present in file, 1 match. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) subject = 'localhost' result = test_file.egrep(subject) self.assertTrue(result) self.assertTrue(result == ['127.0.0.1 localhost.localdomain localhost'])
def test_replace_regex(self): """ Test substitute lines using a valid regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) old = test_file.egrep('^[ ]+#.*') new = '###' self.assertTrue(test_file.replace(old, new)) self.assertFalse(test_file.egrep('^[ ]+#.*'))
def test_add_string_unique(self): """ Test content integrity with unique. """ test_file = FileAsObj() test_file.unique = True subject = 'uniq' self.assertTrue(test_file.add(subject)) self.assertFalse(test_file.add(subject)) self.assertTrue(test_file.contents == [subject])
def test_count_comment_empty(self): """ Test __len__ method. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) subject = '#' result = test_file.grep(subject) self.assertTrue(result) self.assertEqual(len(result), 18)
def test_add_list_no_unique(self): """ Test adding a 3 element list. """ test_file = FileAsObj() subject = ['simultaneous', 'money shot', 'remedy'] self.assertTrue(test_file.add(subject)) self.assertTrue(test_file.changed) self.assertTrue(test_file.add(subject)) self.assertTrue(test_file.contents == subject + subject) self.assertTrue(str(test_file) == '\n'.join(subject + subject))
def test_sorted_attr(self): """ Test self.sorted attribute. """ test_file = FileAsObj() test_file.sorted = True test_file.add('3') test_file.add('2') test_file.add('1') self.assertTrue(test_file.changed) self.assertTrue(test_file.contents == ['1', '2', '3'])
def vlan_create(form): """ Add a VLAN to Kickstart 1. Validate IP information 2. Set gateway to lowest host 3. Set kickstart server IP to highest host minus 2. 4. Add 'include vlan_XX.conf' line to dhcpd.conf file 5. Create vlan_XX.conf file On error raise an exception, let the view handle it. :param: form - A cleaned form object from view.form_valid() :return: form """ netinfo = ipcalc.Network('{0}/{1}'.format(form.instance.network, form.instance.cidr), version=4) # # Set model data to actual network, it's often entered incorrectly. form.instance.network = netinfo.network() # # Gateway and ServerIP are auto-selected during VLAN.Create, but specified during VLAN.Update. if 'gateway' not in form.cleaned_data: form.instance.gateway = netinfo.host_first() else: # # If user entered no gateway during VLAN.Update then set to lowest host. if not form.cleaned_data['gateway']: form.instance.gateway = netinfo.host_first() elif form.cleaned_data['gateway'] not in netinfo: raise ValueError('Gateway is outside this VLAN!') # if 'server_ip' not in form.cleaned_data or not form.cleaned_data['server_ip']: # # No server IP given, default to form.instance.server_ip = ipcalc.IP(int(netinfo.host_last()) - 2, version=4) else: if form.cleaned_data['server_ip'] not in netinfo: raise ValueError('Kickstart Server IP is outside this VLAN!') # name = form.cleaned_data['name'] dhcpd_conf = FileAsObj(os.path.join(KSROOT, 'dhcpd.conf')) # /opt/kickstart/etc/dhcpd.conf dhcpd_conf.add('include "{0}/vlan_{1}.conf";'.format(KSROOT, name)) # vlan_conf = FileAsObj() vlan_conf.filename = os.path.join(KSROOT, 'vlan_{0}.conf'.format(name)) # /opt/kickstart/etc/vlan_{name}.conf vlan_conf.contents = base_vlan.format( NETWORK=form.instance.network, CIDR=form.instance.cidr, GATEWAY=form.instance.gateway, SERVER_IP=form.instance.server_ip, ).split('\n') # # All is OK, save changes and return form. dhcpd_conf.write() vlan_conf.write() return form
def example_add_line_to_file(): """ Different methods to append a given line to the file, all work the same. """ my_file = FileAsObj('/tmp/example_file.txt') my_file.add('foo') my_file.append('bar') # Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed. print(my_file + 'lol') # Add line even if it already exists in the file. my_file.unique = False my_file.add('foo')
def test_iter(self): """ Test __iter__ method. """ test_file = FileAsObj() test_file.filename = TESTFILE test_file.add(TESTCONTENTS) self.assertTrue(test_file.save()) test_file = FileAsObj(TESTFILE) for this in test_file: self.assertIsNotNone(this) # Can be True or False, but not None; empty str is False. self.assertIsInstance(this, str)
def test_sort_method(self): """ Test self.sort() method. """ test_file = FileAsObj() test_file.sorted = False test_file.add('3') test_file.add('2') test_file.add('1') self.assertTrue(test_file.changed) self.assertIsNone(test_file.sort()) self.assertTrue(test_file.contents == ['1', '2', '3'])
def activate(self): """ Update KSROOT/eth1.sh with this VLAN and set self.active to True. """ file = FileAsObj(os.path.join(KSROOT, 'eth1.sh')) file.contents = [] file.add('/sbin/ifconfig eth1 inet {IP} netmask {MASK} up'.format( IP=self.server_ip, MASK=self.cidr, )) file.add('/sbin/service dhcpd restart') file.write() self.active = True self.save() return
def test_add_string_no_unique(self): """ Test content integrity without unique. """ test_file = FileAsObj() subject = 'uniq' self.assertTrue(test_file.add(subject)) self.assertTrue(test_file.add(subject)) self.assertTrue(test_file.contents == [subject, subject])
print('---') old = '172.19.18.17 freebird.example.com' new = '172.19.18.17 freebird.example.com # Added 1976.10.29 -jh' print('Replace {0} with {1}'.format(old, new)) print(test_file.replace(old, new)) print('---') x = '^[ ]+#.*' print('Remove {0} from {1}, RESULT={2}'.format( x, test_file.egrep(x), test_file.rm(test_file.egrep(x)))) print('---') x = '#FOO' print('Add line {0}'.format(x)) print(test_file.add(x)) x = '#FOO' print('Add line {0}'.format(x)) print(test_file.add(x)) x = '#FOO' print('non-unique Add line {0}'.format(x)) print(test_file.add(x, unique=False)) x = ['#', '# ', '#1'] y = '###' print('replace {0} with {1}'.format(x, y)) print(test_file.replace(x, y)) print('Remove all lines that contain "#"')
def test_not_contains(self): """ Test __contains__ method. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) subject = '95bf5dd7096c3552063e4187b4194b1f' self.assertTrue(subject not in test_file)
def test_contains(self): """ Test __contains__ method. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) subject = 'Checking for __contains__ functionality.' self.assertTrue(subject in test_file)
def test_string(self): """ Test __str__ method. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) self.assertTrue(str(test_file) == TESTCONTENTS)
print('File was NOT loaded, here are the errors') print(msg) # Reading a file during instantiation and catching errors. try: my_file = FileAsObj(os.path.join(os.sep, 'home', 'bob', 'clients.txt'), verbose=True) except Exception as msg: print(msg) sys.exit(10) # # If your file does not yet exist... new_file = FileAsObj() new_file.filename = './new_file.txt' new_file.add('new data') new_file.save() # This will create the file on disk and put your data into it. # # # Find mail servers in a hosts file that have IPs starting with 172 my_file.egrep('^172.*mail[0-9]') # # Check for a line in file. # if 'This entire line' in my_file: # return True # # or simply: # return my_file.check('This entire line') #
def test_unique_failure(self): """ Test unique wrong attribute type. """ test_file = FileAsObj() test_file.unique = 'this is invalid attr type' with self.assertRaises(AttributeError): test_file.add('.')
print('File was NOT loaded, here are the errors') print(msg) # Reading a file during instantiation and catching errors. try: my_file = FileAsObj(os.path.join(os.sep, 'home', 'bob', 'clients.txt'), verbose=True) except Exception as msg: print(msg) sys.exit(10) # # If your file does not yet exist... new_file = FileAsObj() new_file.filename = './new_file.txt' new_file.add('new data') new_file.save() # This will create the file on disk and put your data into it. # # # Find mail servers in a hosts file that have IPs starting with 172 my_file.egrep('^172.*mail[0-9]') # # Check for a line in file. # if 'This entire line' in my_file: # return True # # or simply:
print('Replace {0} with {1}'.format(old, new)) print(test_file.replace(old, new)) print('---') x = '^[ ]+#.*' print('Remove {0} from {1}, RESULT={2}'.format( x, test_file.egrep(x), test_file.rm(test_file.egrep(x))) ) print('---') x = '#FOO' print('Add line {0}'.format(x)) print(test_file.add(x)) x = '#FOO' print('Add line {0}'.format(x)) print(test_file.add(x)) x = '#FOO' print('non-unique Add line {0}'.format(x)) print(test_file.add(x, unique=False)) x = ['#', '# ', '#1'] y = '###' print('replace {0} with {1}'.format(x, y)) print(test_file.replace(x, y))
def test_egrep_char_range(self): """ Test egrep with valid range regex. """ test_file = FileAsObj() test_file.add(TESTCONTENTS) self.assertTrue(test_file.egrep('[a-z]ird'))