Search code examples
pythonpython-3.xpython-behave

Capture behave outputs into a dynamically created log file


I am trying to capture the Behave outputs in a file(let's say a log file). I am dynamically creating a new log file at '@then' step for every run of Behave based on datetime. Below is the sample code given in the steps/xx.py file.

def filecreation(filename):
    chwd=os.chdir('C:\\Users\\xxx\\Desktop\\features\\test_features')
    with open(filename, 'w+') as d:
        pass

cur_ts = datetime.datetime.now()
log_time_stamp = str(cur_ts).split('.')[0].replace(' ',':').replace('-',':').replace(':','')
file_name = 'ATMorFrameRelay' + log_time_stamp + '.log'
filecreation(file_name)
pass

Now i am trying to send the Behave output at every run to the log file created above. I am aware that the command "Behave -o [file name]" will create a file for every run , but thought will rather send the STDOUT to the above created file for every new run. Also is it fine/safer to use the STDOUT to write into files in a production like environment and not cause any issues.

I am a newbie to both Python and Behave, so looking forward for any solution/suggestions on how it can be achieved. Any relevant materials or information will be really appreciated too.

Thanks in advance


Solution

  • Maybe something like this, where cmd is actually behave command to run the tests.

    cmd = [
        'behave',
        '--no-capture',
        '--no-capture-stderr',
        '--format', 'progress2',
        '--logging-level', 'INFO',
        '--no-source', '--no-skipped', '--no-summary',
        '--tags', 'MACRO'
        ]
    with io.open(filename, 'a') as writer, io.open(filename, 'rb', 1) as reader:
       process = subprocess.Popen(cmd, env=env, stdout=writer,stderr=writer)
       while process.poll() is None:
            sys.stdout.write(reader.read())
            sys.stdout.flush()
            time.sleep(0.1)
       sys.stdout.write(reader.read())
       sys.stdout.flush(