test_env.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. # SPDX-License-Identifier: GPL-2.0
  2. # Copyright (c) 2015 Stephen Warren
  3. # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
  4. """
  5. Test operation of shell commands relating to environment variables.
  6. """
  7. import os
  8. import os.path
  9. import re
  10. from subprocess import call, CalledProcessError
  11. import tempfile
  12. import pytest
  13. import u_boot_utils
  14. # FIXME: This might be useful for other tests;
  15. # perhaps refactor it into ConsoleBase or some other state object?
  16. class StateTestEnv(object):
  17. """Container that represents the state of all U-Boot environment variables.
  18. This enables quick determination of existant/non-existant variable
  19. names.
  20. """
  21. def __init__(self, u_boot_console):
  22. """Initialize a new StateTestEnv object.
  23. Args:
  24. u_boot_console: A U-Boot console.
  25. Returns:
  26. Nothing.
  27. """
  28. self.u_boot_console = u_boot_console
  29. self.get_env()
  30. self.set_var = self.get_non_existent_var()
  31. def get_env(self):
  32. """Read all current environment variables from U-Boot.
  33. Args:
  34. None.
  35. Returns:
  36. Nothing.
  37. """
  38. if self.u_boot_console.config.buildconfig.get(
  39. 'config_version_variable', 'n') == 'y':
  40. with self.u_boot_console.disable_check('main_signon'):
  41. response = self.u_boot_console.run_command('printenv')
  42. else:
  43. response = self.u_boot_console.run_command('printenv')
  44. self.env = {}
  45. for l in response.splitlines():
  46. if not '=' in l:
  47. continue
  48. (var, value) = l.split('=', 1)
  49. self.env[var] = value
  50. def get_existent_var(self):
  51. """Return the name of an environment variable that exists.
  52. Args:
  53. None.
  54. Returns:
  55. The name of an environment variable.
  56. """
  57. for var in self.env:
  58. return var
  59. def get_non_existent_var(self):
  60. """Return the name of an environment variable that does not exist.
  61. Args:
  62. None.
  63. Returns:
  64. The name of an environment variable.
  65. """
  66. n = 0
  67. while True:
  68. var = 'test_env_' + str(n)
  69. if var not in self.env:
  70. return var
  71. n += 1
  72. ste = None
  73. @pytest.fixture(scope='function')
  74. def state_test_env(u_boot_console):
  75. """pytest fixture to provide a StateTestEnv object to tests."""
  76. global ste
  77. if not ste:
  78. ste = StateTestEnv(u_boot_console)
  79. return ste
  80. def unset_var(state_test_env, var):
  81. """Unset an environment variable.
  82. This both executes a U-Boot shell command and updates a StateTestEnv
  83. object.
  84. Args:
  85. state_test_env: The StateTestEnv object to update.
  86. var: The variable name to unset.
  87. Returns:
  88. Nothing.
  89. """
  90. state_test_env.u_boot_console.run_command('setenv %s' % var)
  91. if var in state_test_env.env:
  92. del state_test_env.env[var]
  93. def set_var(state_test_env, var, value):
  94. """Set an environment variable.
  95. This both executes a U-Boot shell command and updates a StateTestEnv
  96. object.
  97. Args:
  98. state_test_env: The StateTestEnv object to update.
  99. var: The variable name to set.
  100. value: The value to set the variable to.
  101. Returns:
  102. Nothing.
  103. """
  104. bc = state_test_env.u_boot_console.config.buildconfig
  105. if bc.get('config_hush_parser', None):
  106. quote = '"'
  107. else:
  108. quote = ''
  109. if ' ' in value:
  110. pytest.skip('Space in variable value on non-Hush shell')
  111. state_test_env.u_boot_console.run_command(
  112. 'setenv %s %s%s%s' % (var, quote, value, quote))
  113. state_test_env.env[var] = value
  114. def validate_empty(state_test_env, var):
  115. """Validate that a variable is not set, using U-Boot shell commands.
  116. Args:
  117. var: The variable name to test.
  118. Returns:
  119. Nothing.
  120. """
  121. response = state_test_env.u_boot_console.run_command('echo ${%s}' % var)
  122. assert response == ''
  123. def validate_set(state_test_env, var, value):
  124. """Validate that a variable is set, using U-Boot shell commands.
  125. Args:
  126. var: The variable name to test.
  127. value: The value the variable is expected to have.
  128. Returns:
  129. Nothing.
  130. """
  131. # echo does not preserve leading, internal, or trailing whitespace in the
  132. # value. printenv does, and hence allows more complete testing.
  133. response = state_test_env.u_boot_console.run_command('printenv %s' % var)
  134. assert response == ('%s=%s' % (var, value))
  135. @pytest.mark.boardspec('sandbox')
  136. def test_env_initial_env_file(u_boot_console):
  137. """Test that the u-boot-initial-env make target works"""
  138. cons = u_boot_console
  139. builddir = 'O=' + cons.config.build_dir
  140. envfile = cons.config.build_dir + '/u-boot-initial-env'
  141. # remove if already exists from an older run
  142. try:
  143. os.remove(envfile)
  144. except:
  145. pass
  146. u_boot_utils.run_and_log(cons, ['make', builddir, 'u-boot-initial-env'])
  147. assert os.path.exists(envfile)
  148. # assume that every environment has a board variable, e.g. board=sandbox
  149. with open(envfile, 'r') as file:
  150. env = file.read()
  151. regex = re.compile('board=.+\\n')
  152. assert re.search(regex, env)
  153. def test_env_echo_exists(state_test_env):
  154. """Test echoing a variable that exists."""
  155. var = state_test_env.get_existent_var()
  156. value = state_test_env.env[var]
  157. validate_set(state_test_env, var, value)
  158. @pytest.mark.buildconfigspec('cmd_echo')
  159. def test_env_echo_non_existent(state_test_env):
  160. """Test echoing a variable that doesn't exist."""
  161. var = state_test_env.set_var
  162. validate_empty(state_test_env, var)
  163. def test_env_printenv_non_existent(state_test_env):
  164. """Test printenv error message for non-existant variables."""
  165. var = state_test_env.set_var
  166. c = state_test_env.u_boot_console
  167. with c.disable_check('error_notification'):
  168. response = c.run_command('printenv %s' % var)
  169. assert response == '## Error: "%s" not defined' % var
  170. @pytest.mark.buildconfigspec('cmd_echo')
  171. def test_env_unset_non_existent(state_test_env):
  172. """Test unsetting a nonexistent variable."""
  173. var = state_test_env.get_non_existent_var()
  174. unset_var(state_test_env, var)
  175. validate_empty(state_test_env, var)
  176. def test_env_set_non_existent(state_test_env):
  177. """Test set a non-existant variable."""
  178. var = state_test_env.set_var
  179. value = 'foo'
  180. set_var(state_test_env, var, value)
  181. validate_set(state_test_env, var, value)
  182. def test_env_set_existing(state_test_env):
  183. """Test setting an existant variable."""
  184. var = state_test_env.set_var
  185. value = 'bar'
  186. set_var(state_test_env, var, value)
  187. validate_set(state_test_env, var, value)
  188. @pytest.mark.buildconfigspec('cmd_echo')
  189. def test_env_unset_existing(state_test_env):
  190. """Test unsetting a variable."""
  191. var = state_test_env.set_var
  192. unset_var(state_test_env, var)
  193. validate_empty(state_test_env, var)
  194. def test_env_expansion_spaces(state_test_env):
  195. """Test expanding a variable that contains a space in its value."""
  196. var_space = None
  197. var_test = None
  198. try:
  199. var_space = state_test_env.get_non_existent_var()
  200. set_var(state_test_env, var_space, ' ')
  201. var_test = state_test_env.get_non_existent_var()
  202. value = ' 1${%(var_space)s}${%(var_space)s} 2 ' % locals()
  203. set_var(state_test_env, var_test, value)
  204. value = ' 1 2 '
  205. validate_set(state_test_env, var_test, value)
  206. finally:
  207. if var_space:
  208. unset_var(state_test_env, var_space)
  209. if var_test:
  210. unset_var(state_test_env, var_test)
  211. @pytest.mark.buildconfigspec('cmd_importenv')
  212. def test_env_import_checksum_no_size(state_test_env):
  213. """Test that omitted ('-') size parameter with checksum validation fails the
  214. env import function.
  215. """
  216. c = state_test_env.u_boot_console
  217. ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
  218. addr = '%08x' % ram_base
  219. with c.disable_check('error_notification'):
  220. response = c.run_command('env import -c %s -' % addr)
  221. assert response == '## Error: external checksum format must pass size'
  222. @pytest.mark.buildconfigspec('cmd_importenv')
  223. def test_env_import_whitelist_checksum_no_size(state_test_env):
  224. """Test that omitted ('-') size parameter with checksum validation fails the
  225. env import function when variables are passed as parameters.
  226. """
  227. c = state_test_env.u_boot_console
  228. ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
  229. addr = '%08x' % ram_base
  230. with c.disable_check('error_notification'):
  231. response = c.run_command('env import -c %s - foo1 foo2 foo4' % addr)
  232. assert response == '## Error: external checksum format must pass size'
  233. @pytest.mark.buildconfigspec('cmd_exportenv')
  234. @pytest.mark.buildconfigspec('cmd_importenv')
  235. def test_env_import_whitelist(state_test_env):
  236. """Test importing only a handful of env variables from an environment."""
  237. c = state_test_env.u_boot_console
  238. ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
  239. addr = '%08x' % ram_base
  240. set_var(state_test_env, 'foo1', 'bar1')
  241. set_var(state_test_env, 'foo2', 'bar2')
  242. set_var(state_test_env, 'foo3', 'bar3')
  243. c.run_command('env export %s' % addr)
  244. unset_var(state_test_env, 'foo1')
  245. set_var(state_test_env, 'foo2', 'test2')
  246. set_var(state_test_env, 'foo4', 'bar4')
  247. # no foo1 in current env, foo2 overridden, foo3 should be of the value
  248. # before exporting and foo4 should be of the value before importing.
  249. c.run_command('env import %s - foo1 foo2 foo4' % addr)
  250. validate_set(state_test_env, 'foo1', 'bar1')
  251. validate_set(state_test_env, 'foo2', 'bar2')
  252. validate_set(state_test_env, 'foo3', 'bar3')
  253. validate_set(state_test_env, 'foo4', 'bar4')
  254. # Cleanup test environment
  255. unset_var(state_test_env, 'foo1')
  256. unset_var(state_test_env, 'foo2')
  257. unset_var(state_test_env, 'foo3')
  258. unset_var(state_test_env, 'foo4')
  259. @pytest.mark.buildconfigspec('cmd_exportenv')
  260. @pytest.mark.buildconfigspec('cmd_importenv')
  261. def test_env_import_whitelist_delete(state_test_env):
  262. """Test importing only a handful of env variables from an environment, with.
  263. deletion if a var A that is passed to env import is not in the
  264. environment to be imported.
  265. """
  266. c = state_test_env.u_boot_console
  267. ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
  268. addr = '%08x' % ram_base
  269. set_var(state_test_env, 'foo1', 'bar1')
  270. set_var(state_test_env, 'foo2', 'bar2')
  271. set_var(state_test_env, 'foo3', 'bar3')
  272. c.run_command('env export %s' % addr)
  273. unset_var(state_test_env, 'foo1')
  274. set_var(state_test_env, 'foo2', 'test2')
  275. set_var(state_test_env, 'foo4', 'bar4')
  276. # no foo1 in current env, foo2 overridden, foo3 should be of the value
  277. # before exporting and foo4 should be empty.
  278. c.run_command('env import -d %s - foo1 foo2 foo4' % addr)
  279. validate_set(state_test_env, 'foo1', 'bar1')
  280. validate_set(state_test_env, 'foo2', 'bar2')
  281. validate_set(state_test_env, 'foo3', 'bar3')
  282. validate_empty(state_test_env, 'foo4')
  283. # Cleanup test environment
  284. unset_var(state_test_env, 'foo1')
  285. unset_var(state_test_env, 'foo2')
  286. unset_var(state_test_env, 'foo3')
  287. unset_var(state_test_env, 'foo4')
  288. @pytest.mark.buildconfigspec('cmd_nvedit_info')
  289. def test_env_info(state_test_env):
  290. """Test 'env info' command with all possible options.
  291. """
  292. c = state_test_env.u_boot_console
  293. response = c.run_command('env info')
  294. nb_line = 0
  295. for l in response.split('\n'):
  296. if 'env_valid = ' in l:
  297. assert '= invalid' in l or '= valid' in l or '= redundant' in l
  298. nb_line += 1
  299. elif 'env_ready =' in l or 'env_use_default =' in l:
  300. assert '= true' in l or '= false' in l
  301. nb_line += 1
  302. else:
  303. assert True
  304. assert nb_line == 3
  305. response = c.run_command('env info -p -d')
  306. assert 'Default environment is used' in response or \
  307. "Environment was loaded from persistent storage" in response
  308. assert 'Environment can be persisted' in response or \
  309. "Environment cannot be persisted" in response
  310. response = c.run_command('env info -p -d -q')
  311. assert response == ""
  312. response = c.run_command('env info -p -q')
  313. assert response == ""
  314. response = c.run_command('env info -d -q')
  315. assert response == ""
  316. @pytest.mark.boardspec('sandbox')
  317. @pytest.mark.buildconfigspec('cmd_nvedit_info')
  318. @pytest.mark.buildconfigspec('cmd_echo')
  319. def test_env_info_sandbox(state_test_env):
  320. """Test 'env info' command result with several options on sandbox
  321. with a known ENV configuration: ready & default & persistent
  322. """
  323. c = state_test_env.u_boot_console
  324. response = c.run_command('env info')
  325. assert 'env_ready = true' in response
  326. assert 'env_use_default = true' in response
  327. response = c.run_command('env info -p -d')
  328. assert 'Default environment is used' in response
  329. assert 'Environment cannot be persisted' in response
  330. response = c.run_command('env info -d -q')
  331. response = c.run_command('echo $?')
  332. assert response == "0"
  333. response = c.run_command('env info -p -q')
  334. response = c.run_command('echo $?')
  335. assert response == "1"
  336. response = c.run_command('env info -d -p -q')
  337. response = c.run_command('echo $?')
  338. assert response == "1"
  339. def mk_env_ext4(state_test_env):
  340. """Create a empty ext4 file system volume."""
  341. c = state_test_env.u_boot_console
  342. filename = 'env.ext4.img'
  343. persistent = c.config.persistent_data_dir + '/' + filename
  344. fs_img = c.config.result_dir + '/' + filename
  345. if os.path.exists(persistent):
  346. c.log.action('Disk image file ' + persistent + ' already exists')
  347. else:
  348. # Some distributions do not add /sbin to the default PATH, where mkfs.ext4 lives
  349. os.environ["PATH"] += os.pathsep + '/sbin'
  350. try:
  351. u_boot_utils.run_and_log(c, 'dd if=/dev/zero of=%s bs=1M count=16' % persistent)
  352. u_boot_utils.run_and_log(c, 'mkfs.ext4 %s' % persistent)
  353. sb_content = u_boot_utils.run_and_log(c, 'tune2fs -l %s' % persistent)
  354. if 'metadata_csum' in sb_content:
  355. u_boot_utils.run_and_log(c, 'tune2fs -O ^metadata_csum %s' % persistent)
  356. except CalledProcessError:
  357. call('rm -f %s' % persistent, shell=True)
  358. raise
  359. u_boot_utils.run_and_log(c, ['cp', '-f', persistent, fs_img])
  360. return fs_img
  361. @pytest.mark.boardspec('sandbox')
  362. @pytest.mark.buildconfigspec('cmd_echo')
  363. @pytest.mark.buildconfigspec('cmd_nvedit_info')
  364. @pytest.mark.buildconfigspec('cmd_nvedit_load')
  365. @pytest.mark.buildconfigspec('cmd_nvedit_select')
  366. @pytest.mark.buildconfigspec('env_is_in_ext4')
  367. def test_env_ext4(state_test_env):
  368. """Test ENV in EXT4 on sandbox."""
  369. c = state_test_env.u_boot_console
  370. fs_img = ''
  371. try:
  372. fs_img = mk_env_ext4(state_test_env)
  373. c.run_command('host bind 0 %s' % fs_img)
  374. response = c.run_command('ext4ls host 0:0')
  375. assert 'uboot.env' not in response
  376. # force env location: EXT4 (prio 1 in sandbox)
  377. response = c.run_command('env select EXT4')
  378. assert 'Select Environment on EXT4: OK' in response
  379. response = c.run_command('env save')
  380. assert 'Saving Environment to EXT4' in response
  381. response = c.run_command('env load')
  382. assert 'Loading Environment from EXT4... OK' in response
  383. response = c.run_command('ext4ls host 0:0')
  384. assert '8192 uboot.env' in response
  385. response = c.run_command('env info')
  386. assert 'env_valid = valid' in response
  387. assert 'env_ready = true' in response
  388. assert 'env_use_default = false' in response
  389. response = c.run_command('env info -p -d')
  390. assert 'Environment was loaded from persistent storage' in response
  391. assert 'Environment can be persisted' in response
  392. response = c.run_command('env info -d -q')
  393. assert response == ""
  394. response = c.run_command('echo $?')
  395. assert response == "1"
  396. response = c.run_command('env info -p -q')
  397. assert response == ""
  398. response = c.run_command('echo $?')
  399. assert response == "0"
  400. response = c.run_command('env erase')
  401. assert 'OK' in response
  402. response = c.run_command('env load')
  403. assert 'Loading Environment from EXT4... ' in response
  404. assert 'bad CRC, using default environment' in response
  405. response = c.run_command('env info')
  406. assert 'env_valid = invalid' in response
  407. assert 'env_ready = true' in response
  408. assert 'env_use_default = true' in response
  409. response = c.run_command('env info -p -d')
  410. assert 'Default environment is used' in response
  411. assert 'Environment can be persisted' in response
  412. # restore env location: NOWHERE (prio 0 in sandbox)
  413. response = c.run_command('env select nowhere')
  414. assert 'Select Environment on nowhere: OK' in response
  415. response = c.run_command('env load')
  416. assert 'Loading Environment from nowhere... OK' in response
  417. response = c.run_command('env info')
  418. assert 'env_valid = invalid' in response
  419. assert 'env_ready = true' in response
  420. assert 'env_use_default = true' in response
  421. response = c.run_command('env info -p -d')
  422. assert 'Default environment is used' in response
  423. assert 'Environment cannot be persisted' in response
  424. finally:
  425. if fs_img:
  426. call('rm -f %s' % fs_img, shell=True)
  427. def test_env_text(u_boot_console):
  428. """Test the script that converts the environment to a text file"""
  429. def check_script(intext, expect_val):
  430. """Check a test case
  431. Args:
  432. intext: Text to pass to the script
  433. expect_val: Expected value of the CONFIG_EXTRA_ENV_TEXT string, or
  434. None if we expect it not to be defined
  435. """
  436. with tempfile.TemporaryDirectory() as path:
  437. fname = os.path.join(path, 'infile')
  438. with open(fname, 'w') as inf:
  439. print(intext, file=inf)
  440. result = u_boot_utils.run_and_log(cons, ['awk', '-f', script, fname])
  441. if expect_val is not None:
  442. expect = '#define CONFIG_EXTRA_ENV_TEXT "%s"\n' % expect_val
  443. assert result == expect
  444. else:
  445. assert result == ''
  446. cons = u_boot_console
  447. script = os.path.join(cons.config.source_dir, 'scripts', 'env2string.awk')
  448. # simple script with a single var
  449. check_script('fred=123', 'fred=123\\0')
  450. # no vars
  451. check_script('', None)
  452. # two vars
  453. check_script('''fred=123
  454. mary=456''', 'fred=123\\0mary=456\\0')
  455. # blank lines
  456. check_script('''fred=123
  457. mary=456
  458. ''', 'fred=123\\0mary=456\\0')
  459. # append
  460. check_script('''fred=123
  461. mary=456
  462. fred+= 456''', 'fred=123 456\\0mary=456\\0')
  463. # append from empty
  464. check_script('''fred=
  465. mary=456
  466. fred+= 456''', 'fred= 456\\0mary=456\\0')
  467. # variable with + in it
  468. check_script('fred+mary=123', 'fred+mary=123\\0')
  469. # ignores variables that are empty
  470. check_script('''fred=
  471. fred+=
  472. mary=456''', 'mary=456\\0')
  473. # single-character env name
  474. check_script('''m=123
  475. e=456
  476. m+= 456''', 'e=456\\0m=123 456\\0')
  477. # contains quotes
  478. check_script('''fred="my var"
  479. mary=another"''', 'fred=\\"my var\\"\\0mary=another\\"\\0')
  480. # variable name ending in +
  481. check_script('''fred\\+=my var
  482. fred++= again''', 'fred+=my var again\\0')
  483. # variable name containing +
  484. check_script('''fred+jane=both
  485. fred+jane+=again
  486. mary=456''', 'fred+jane=bothagain\\0mary=456\\0')
  487. # multi-line vars - new vars always start at column 1
  488. check_script('''fred=first
  489. second
  490. \tthird with tab
  491. after blank
  492. confusing=oops
  493. mary=another"''', 'fred=first second third with tab after blank confusing=oops\\0mary=another\\"\\0')
  494. # real-world example
  495. check_script('''ubifs_boot=
  496. env exists bootubipart ||
  497. env set bootubipart UBI;
  498. env exists bootubivol ||
  499. env set bootubivol boot;
  500. if ubi part ${bootubipart} &&
  501. ubifsmount ubi${devnum}:${bootubivol};
  502. then
  503. devtype=ubi;
  504. run scan_dev_for_boot;
  505. fi
  506. ''',
  507. 'ubifs_boot=env exists bootubipart || env set bootubipart UBI; '
  508. 'env exists bootubivol || env set bootubivol boot; '
  509. 'if ubi part ${bootubipart} && ubifsmount ubi${devnum}:${bootubivol}; '
  510. 'then devtype=ubi; run scan_dev_for_boot; fi\\0')