示例#1
0
def example_read_catch_errors():
    """ Reading a file and catch errors. """
    try:
        my_file = FileAsObj()
        my_file.read('/tmp/example_file.txt')
    except Exception as msg:
        print(msg)
 def test_save_with_changes(self):
     """ Instance an empty test file, overwrite its contents and save to disk. """
     test_file = FileAsObj()
     test_file.filename = TESTFILE
     test_file.contents = TESTCONTENTS.split('\n')
     self.assertEqual(TESTCONTENTS, str(test_file))
     self.assertTrue(test_file.save())
 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_logging_enabled(self):
     """ Test local log enabled by default. """
     test_file = FileAsObj()
     self.assertIsNotNone(str(test_file.log))
     test_file.log('FINDME')
     self.assertTrue('FINDME' in str(test_file.log))
     self.assertTrue('FINDME' in test_file.log.trace)
 def test_check_failure(self):
     """ Test check() method with wrong parameter type. """
     test_file = FileAsObj()
     with self.assertRaises(TypeError):
         test_file.check(1)
     with self.assertRaises(TypeError):
         test_file.check(False)
 def test_subtract(self):
     """ Test __sub__ method. """
     test_file = FileAsObj()
     test_file.contents = TESTCONTENTS.split('\n')
     self.assertFalse(test_file.changed)
     self.assertTrue(test_file - '#comment')
     self.assertTrue(test_file.changed)
 def test_append_failure_param(self):
     """ Test wrong param type in append() """
     test_file = FileAsObj()
     with self.assertRaises(TypeError):
         test_file.append(1)
     with self.assertRaises(TypeError):
         test_file.append(True)
 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)
示例#9
0
 def test_replace_list(self):
     test_file = FileAsObj(TestFile, verbose=True)
     old = ['#', '# ', '#1']
     new = '###'
     self.assertTrue(test_file.replace(old, new))
     for this in old:
         self.assertFalse(test_file.check(this))
 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_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_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_append_string_no_unique(self):
     """ Test content integrity using `unique` """
     test_file = FileAsObj()
     subject = 'uniq'
     self.assertTrue(test_file.append(subject))
     self.assertTrue(test_file.append(subject))
     self.assertTrue(test_file.contents == [subject, subject])
 def test_subtract_fail(self):
     """ Test __sub__ method fails. """
     test_file = FileAsObj()
     test_file.contents = TESTCONTENTS.split('\n')
     self.assertFalse(test_file.changed)
     self.assertFalse(test_file - 'this string does not exist in file!')
     self.assertFalse(test_file.changed)
 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_rm_failure(self):
     """ Test wrong param type in rm() """
     test_file = FileAsObj()
     with self.assertRaises(TypeError):
         test_file.rm(1)
     with self.assertRaises(TypeError):
         test_file.rm(True)
 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])
 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_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_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'])
示例#22
0
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_addition_string_unique(self):
     """ Test content integrity using `unique` """
     test_file = FileAsObj()
     test_file.unique = True
     subject = 'uniq'
     self.assertTrue(test_file + subject)
     self.assertFalse(test_file + subject)
     self.assertTrue(test_file.contents == [subject])
示例#25
0
def example_file_create():
    """
    Creating an object for a file that does NOT exist but we wish to create.
    If the file exists this will truncate it.
    """
    my_file = FileAsObj()
    my_file.filename = '/tmp/a_file.txt'
    my_file.save()
 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_append_list_no_unique(self):
     """ Test adding a 3 element list with .add() """
     test_file = FileAsObj()
     subject = ['simultaneous', 'money shot', 'remedy']
     self.assertTrue(test_file.append(subject))
     self.assertTrue(test_file.changed)
     self.assertTrue(test_file.append(subject))
     self.assertTrue(test_file.contents == subject + subject)
     self.assertTrue(str(test_file) == '\n'.join(subject + subject))
示例#28
0
def example_sort_during_read():
    """
    To sort contents during read().
    The .sorted attribute is checked every time contents are modified.
    Whenever a change occurs if sorted is True the contents are sorted with self.sort().
    """
    my_file = FileAsObj()
    my_file.sorted = True
    my_file.read('/tmp/example_file.txt')
示例#29
0
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 test_addition_list_unique(self):
     """ Test adding a 3 element list with unique. """
     test_file = FileAsObj()
     test_file.unique = True
     subject = ['simultaneous', 'money shot', 'remedy']
     self.assertFalse(test_file.changed)
     self.assertTrue(test_file + subject)
     self.assertTrue(test_file.changed)
     self.assertFalse(test_file + subject)
     self.assertTrue(test_file.contents == subject)
     self.assertTrue(str(test_file) == '\n'.join(subject))
示例#31
0
"""

"""
import re
from fileasobj import FileAsObj

try:
    impossible = FileAsObj('File does not exist')
except FileNotFoundError as msg:
    print(msg)

test_file = FileAsObj('Test.txt', verbose=True)

#
# test iterable
for this in test_file:
    print(this)

print(test_file.birthday)

# test_file = FileAsObj('Test.txt')
# print(test_file)
# print(test_file.trace)

if 'Checking for __contains__ functionality 123' in test_file:
    print('__contains__ test string present')

if 'a7s6d9f7a6sd9f76asf9a8d7s89d6f967adfsadf' not in test_file:
    print('bogus string not in test file, good!')

test_file + 'using __add__ three times, force unique'
示例#32
0
"""
fileasobj/examples.py

"""
import sys
import os

from fileasobj import FileAsObj

# Reading a file
my_file = FileAsObj()
try:
    my_file.read('./input.txt')
except Exception as msg:
    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.