Abhijeet Goswami
Abhijeet Goswami

Reputation: 3

Setting "self.client.headers" in a locust test by reading values from a config.txt file

I'm using configparser to read below values in a sample text file named config.txt:

cookie='StaticWebAppsAuthCookie=GKeVpelA4wK+udvu7de737v7v8cv8v'
Accept='*/*'
Accept-Encoding=' gzip, deflate, br'
Connection= 'keep-alive'`

I'm reading the config.txt through below python code:

config = configparser.ConfigParser()
config.read('config.txt')
self.client.headers = {'cookie': config.get('DEFAULT','cookie'),
                       'Accept':config.get('DEFAULT','Accept'),
                       'Accept-Encoding':config.get('DEFAULT','Accept-Encoding'),
                       'Connection':config.get('DEFAULT','Connection')}'

I'm getting below error when executed:

configparser.MissingSectionHeaderError: File contains no section headers.

Kindly help in this, or suggest an alternate to achieve setting client-headers by reading values over a given .txt file

Upvotes: 0

Views: 42

Answers (1)

AnikeiPS
AnikeiPS

Reputation: 18

That's because Python's configparser library is used to parse .ini files. INI files have headers that look like this: [HEADER], but your file doesn't have any. Also INI files do not support any types except strings, so there's no need to use quotation marks in INI file. So to fix your problem you could add DEFAULT header and change your config.txt to

[DEFAULT]
cookie=StaticWebAppsAuthCookie=GKeVpelA4wK+udvu7de737v7v8cv8v
Accept=*/*
Accept-Encoding=gzip, deflate, br
Connection=keep-alive

And yes, configparser does not care about extensions.
2. Your usage of configparser is a little bit wrong. Python's .get dict function has this format: .get("key", "default value (if key does not exist"). Configparser stores data as dict in dict and to get data you would need to use config["header"]["key"]. So you need to use config['DEFAULT']['cookie'] for example. And to fix this problem just change your python file to this:

config = configparser.ConfigParser()
config.read('config.txt')
self.client.headers = {'cookie': config['DEFAULT']['cookie'],
                       'Accept': config['DEFAULT']['Accept'],
                       'Accept-Encoding': config['DEFAULT']['Accept-Encoding'],
                       'Connection': config['DEFAULT']['Connection']}

And you can also just do

config = configparser.ConfigParser()
config.read('config.txt')
self.client.headers = config['DEFAULT']

Upvotes: 0

Related Questions