testsuite.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203
  1. # Copyright (c) 2011-2019, Ulf Magnusson
  2. # SPDX-License-Identifier: ISC
  3. # This is the Kconfiglib test suite. It runs selftests on Kconfigs provided by
  4. # us and tests compatibility with the C Kconfig implementation by comparing the
  5. # output of Kconfiglib with the output of the scripts/kconfig/*conf utilities
  6. # for different targets and defconfigs. It should be run from the top-level
  7. # kernel directory with
  8. #
  9. # $ python Kconfiglib/testsuite.py
  10. #
  11. # Some additional options can be turned on by passing them as arguments. They
  12. # default to off.
  13. #
  14. # - obsessive:
  15. # By default, only valid arch/defconfig pairs are tested. In obsessive mode,
  16. # every arch will be tested with every defconfig. Increases the testing time
  17. # by an order of magnitude. Occasionally finds (usually obscure) bugs, and I
  18. # make sure everything passes with it.
  19. #
  20. # - obsessive-min-config:
  21. # Like obsessive, for the minimal configuation (defconfig) tests.
  22. #
  23. # - log:
  24. # Log timestamped defconfig test failures to the file test_defconfig_fails.
  25. # Handy in obsessive mode.
  26. #
  27. # For example, this commands runs the test suite in obsessive mode with logging
  28. # enabled:
  29. #
  30. # $ python(3) Kconfiglib/testsuite.py obsessive log
  31. #
  32. # pypy works too, and runs most tests much faster than CPython.
  33. #
  34. # All tests should pass. Report regressions to ulfalizer a.t Google's email
  35. # service.
  36. import difflib
  37. import errno
  38. import os
  39. import re
  40. import shutil
  41. import subprocess
  42. import sys
  43. import tempfile
  44. import textwrap
  45. from kconfiglib import Kconfig, Symbol, Choice, COMMENT, MENU, MenuNode, \
  46. BOOL, TRISTATE, HEX, \
  47. TRI_TO_STR, \
  48. escape, unescape, \
  49. expr_str, expr_items, split_expr, \
  50. _ordered_unique, \
  51. OR, AND, \
  52. KconfigError
  53. def shell(cmd):
  54. with open(os.devnull, "w") as devnull:
  55. subprocess.call(cmd, shell=True, stdout=devnull, stderr=devnull)
  56. all_passed = True
  57. def fail(msg=None):
  58. global all_passed
  59. all_passed = False
  60. if msg is not None:
  61. print("fail: " + msg)
  62. def verify(cond, msg):
  63. if not cond:
  64. fail(msg)
  65. def verify_equal(x, y):
  66. if x != y:
  67. fail("'{}' does not equal '{}'".format(x, y))
  68. # Prevent accidental loading of configuration files by removing
  69. # KCONFIG_ALLCONFIG from the environment
  70. os.environ.pop("KCONFIG_ALLCONFIG", None)
  71. obsessive = False
  72. obsessive_min_config = False
  73. log = False
  74. def run_tests():
  75. global obsessive, log
  76. for s in sys.argv[1:]:
  77. if s == "obsessive":
  78. obsessive = True
  79. print("Obsessive mode enabled")
  80. elif s == "obsessive-min-config":
  81. obsessive_min_config = True
  82. print("Obsessive minimal config mode enabled")
  83. elif s == "log":
  84. log = True
  85. print("Log mode enabled")
  86. else:
  87. print("Unrecognized option '{}'".format(s))
  88. return
  89. run_selftests()
  90. run_compatibility_tests()
  91. def run_selftests():
  92. #
  93. # Common helper functions. These all expect 'c' to hold the current
  94. # configuration.
  95. #
  96. def verify_value(sym_name, val):
  97. # Verifies that a symbol has a particular value.
  98. if isinstance(val, int):
  99. val = TRI_TO_STR[val]
  100. sym = c.syms[sym_name]
  101. verify(sym.str_value == val,
  102. 'expected {} to have the value "{}", had the value "{}"'
  103. .format(sym_name, val, sym.str_value))
  104. def assign_and_verify_value(sym_name, val, new_val):
  105. # Assigns 'val' to a symbol and verifies that its value becomes
  106. # 'new_val'. Assumes (and tests) that 'val' is valid for the
  107. # symbol type.
  108. if isinstance(new_val, int):
  109. new_val = TRI_TO_STR[new_val]
  110. sym = c.syms[sym_name]
  111. old_val = sym.str_value
  112. verify(sym.set_value(val),
  113. "assigning '{}' to {} unexpectedly failed"
  114. .format(val, sym_name))
  115. verify(sym.str_value == new_val,
  116. "expected {} to have the value '{}' after being assigned the "
  117. "value '{}'. Instead, the value is '{}'. The old value was "
  118. "'{}'."
  119. .format(sym_name, new_val, val, sym.str_value, old_val))
  120. def assign_and_verify(sym_name, user_val):
  121. # Like assign_and_verify_value(), with the expected value being the
  122. # value just set.
  123. assign_and_verify_value(sym_name, user_val, user_val)
  124. def assign_and_verify_user_value(sym_name, val, user_val, valid):
  125. # Assigns a user value to the symbol and verifies the new user value.
  126. # If valid is True, the user value is valid for the type, otherwise
  127. # not. This is used to test the set_value() return value.
  128. sym = c.syms[sym_name]
  129. sym_old_user_val = sym.user_value
  130. verify(sym.set_value(val) == valid,
  131. "expected the user value '{}' to be {} for {}, was not"
  132. .format(val, "valid" if valid else "invalid", sym_name))
  133. verify(sym.user_value == user_val,
  134. "the assigned user value '{}' wasn't reflected in user_value "
  135. "on the symbol {}. Instead, the new user_value was '{}'. The "
  136. "old user value was '{}'."
  137. .format(user_val, sym_name, sym.user_value, sym_old_user_val))
  138. #
  139. # Selftests
  140. #
  141. print("Testing string literal lexing")
  142. # Dummy empty configuration just to get a Kconfig object
  143. c = Kconfig("Kconfiglib/tests/empty")
  144. def verify_string_lex(s, expected):
  145. # Verifies that a constant symbol with the name 'res' is produced from
  146. # lexing 's'
  147. res = c._tokenize("if " + s)[1].name
  148. verify(res == expected,
  149. "expected <{}> to produced the constant symbol <{}>, "
  150. 'produced <{}>'.format(s[1:-1], expected, res))
  151. verify_string_lex(r""" "" """, "")
  152. verify_string_lex(r""" '' """, "")
  153. verify_string_lex(r""" "a" """, "a")
  154. verify_string_lex(r""" 'a' """, "a")
  155. verify_string_lex(r""" "ab" """, "ab")
  156. verify_string_lex(r""" 'ab' """, "ab")
  157. verify_string_lex(r""" "abc" """, "abc")
  158. verify_string_lex(r""" 'abc' """, "abc")
  159. verify_string_lex(r""" "'" """, "'")
  160. verify_string_lex(r""" '"' """, '"')
  161. verify_string_lex(r""" "\"" """, '"')
  162. verify_string_lex(r""" '\'' """, "'")
  163. verify_string_lex(r""" "\"\"" """, '""')
  164. verify_string_lex(r""" '\'\'' """, "''")
  165. verify_string_lex(r""" "\'" """, "'")
  166. verify_string_lex(r""" '\"' """, '"')
  167. verify_string_lex(r""" "\\" """, "\\")
  168. verify_string_lex(r""" '\\' """, "\\")
  169. verify_string_lex(r""" "\a\\'\b\c\"'d" """, 'a\\\'bc"\'d')
  170. verify_string_lex(r""" '\a\\"\b\c\'"d' """, "a\\\"bc'\"d")
  171. def verify_string_bad(s):
  172. # Verifies that tokenizing 's' throws a KconfigError. Strips the first
  173. # and last characters from 's' so we can use readable raw strings as
  174. # input.
  175. try:
  176. c.eval_string(s)
  177. except KconfigError:
  178. pass
  179. else:
  180. fail("expected tokenization of {} to fail, didn't".format(s[1:-1]))
  181. verify_string_bad(r""" " """)
  182. verify_string_bad(r""" ' """)
  183. verify_string_bad(r""" "' """)
  184. verify_string_bad(r""" '" """)
  185. verify_string_bad(r""" "\" """)
  186. verify_string_bad(r""" '\' """)
  187. verify_string_bad(r""" "foo """)
  188. verify_string_bad(r""" 'foo """)
  189. print("Testing escape() and unescape()")
  190. def verify_escape_unescape(s, sesc):
  191. # Verify that 's' escapes to 'sesc' and that 'sesc' unescapes to 's'
  192. verify_equal(escape(s), sesc)
  193. verify_equal(unescape(sesc), s)
  194. verify_escape_unescape(r'' , r'' )
  195. verify_escape_unescape(r'foo' , r'foo' )
  196. verify_escape_unescape(r'"' , r'\"' )
  197. verify_escape_unescape(r'""' , r'\"\"' )
  198. verify_escape_unescape('\\' , r'\\' )
  199. verify_escape_unescape(r'\\' , r'\\\\' )
  200. verify_escape_unescape(r'\"' , r'\\\"' )
  201. verify_escape_unescape(r'"ab\cd"ef"', r'\"ab\\cd\"ef\"')
  202. # Backslashes before any character should be unescaped, not just before "
  203. # and \
  204. verify_equal(unescape(r"\afoo\b\c\\d\\\e\\\\f"), r"afoobc\d\e\\f")
  205. print("Testing _ordered_unique()")
  206. verify_equal(_ordered_unique([]), [])
  207. verify_equal(_ordered_unique([1]), [1])
  208. verify_equal(_ordered_unique([1, 2]), [1, 2])
  209. verify_equal(_ordered_unique([1, 1]), [1])
  210. verify_equal(_ordered_unique([1, 1, 2]), [1, 2])
  211. verify_equal(_ordered_unique([1, 2, 1]), [1, 2])
  212. verify_equal(_ordered_unique([1, 2, 2]), [1, 2])
  213. verify_equal(_ordered_unique([1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 1, 0]),
  214. [1, 2, 3, 4, 0])
  215. print("Testing expression evaluation")
  216. c = Kconfig("Kconfiglib/tests/Keval", warn=False)
  217. def verify_eval(expr, val):
  218. res = c.eval_string(expr)
  219. verify(res == val,
  220. "'{}' evaluated to {}, expected {}".format(expr, res, val))
  221. # No modules
  222. verify_eval("n", 0)
  223. verify_eval("m", 0)
  224. verify_eval("y", 2)
  225. verify_eval("'n'", 0)
  226. verify_eval("'m'", 0)
  227. verify_eval("'y'", 2)
  228. verify_eval("M", 2)
  229. # Modules
  230. c.modules.set_value(2)
  231. verify_eval("n", 0)
  232. verify_eval("m", 1)
  233. verify_eval("y", 2)
  234. verify_eval("'n'", 0)
  235. verify_eval("'m'", 1)
  236. verify_eval("'y'", 2)
  237. verify_eval("M", 1)
  238. verify_eval("(Y || N) && (m && y)", 1)
  239. # Non-bool/non-tristate symbols are always n in a tristate sense
  240. verify_eval("Y_STRING", 0)
  241. verify_eval("Y_STRING || m", 1)
  242. # As are all constants besides y and m
  243. verify_eval('"foo"', 0)
  244. verify_eval('"foo" || "bar"', 0)
  245. verify_eval('"foo" || m', 1)
  246. # Test equality for symbols
  247. verify_eval("N = N", 2)
  248. verify_eval("N = n", 2)
  249. verify_eval("N = 'n'", 2)
  250. verify_eval("N != N", 0)
  251. verify_eval("N != n", 0)
  252. verify_eval("N != 'n'", 0)
  253. verify_eval("M = M", 2)
  254. verify_eval("M = m", 2)
  255. verify_eval("M = 'm'", 2)
  256. verify_eval("M != M", 0)
  257. verify_eval("M != m", 0)
  258. verify_eval("M != 'm'", 0)
  259. verify_eval("Y = Y", 2)
  260. verify_eval("Y = y", 2)
  261. verify_eval("Y = 'y'", 2)
  262. verify_eval("Y != Y", 0)
  263. verify_eval("Y != y", 0)
  264. verify_eval("Y != 'y'", 0)
  265. verify_eval("N != M", 2)
  266. verify_eval("N != Y", 2)
  267. verify_eval("M != Y", 2)
  268. verify_eval("Y_STRING = y", 2)
  269. verify_eval("Y_STRING = 'y'", 2)
  270. verify_eval('FOO_BAR_STRING = "foo bar"', 2)
  271. verify_eval('FOO_BAR_STRING != "foo bar baz"', 2)
  272. verify_eval('INT_37 = 37', 2)
  273. verify_eval("INT_37 = '37'", 2)
  274. verify_eval('HEX_0X37 = 0x37', 2)
  275. verify_eval("HEX_0X37 = '0x37'", 2)
  276. # These should also hold after 31847b67 (kconfig: allow use of relations
  277. # other than (in)equality)
  278. verify_eval("HEX_0X37 = '0x037'", 2)
  279. verify_eval("HEX_0X37 = '0x0037'", 2)
  280. # Constant symbol comparisons
  281. verify_eval('"foo" != "bar"', 2)
  282. verify_eval('"foo" = "bar"', 0)
  283. verify_eval('"foo" = "foo"', 2)
  284. # Undefined symbols get their name as their value
  285. c.warn = False
  286. verify_eval("'not_defined' = not_defined", 2)
  287. verify_eval("not_defined_2 = not_defined_2", 2)
  288. verify_eval("not_defined_1 != not_defined_2", 2)
  289. # Test less than/greater than
  290. # Basic evaluation
  291. verify_eval("INT_37 < 38", 2)
  292. verify_eval("38 < INT_37", 0)
  293. verify_eval("INT_37 < '38'", 2)
  294. verify_eval("'38' < INT_37", 0)
  295. verify_eval("INT_37 < 138", 2)
  296. verify_eval("138 < INT_37", 0)
  297. verify_eval("INT_37 < '138'", 2)
  298. verify_eval("'138' < INT_37", 0)
  299. verify_eval("INT_37 < -138", 0)
  300. verify_eval("-138 < INT_37", 2)
  301. verify_eval("INT_37 < '-138'", 0)
  302. verify_eval("'-138' < INT_37", 2)
  303. verify_eval("INT_37 < 37", 0)
  304. verify_eval("37 < INT_37", 0)
  305. verify_eval("INT_37 < 36", 0)
  306. verify_eval("36 < INT_37", 2)
  307. # Different formats in comparison
  308. verify_eval("INT_37 < 0x26", 2) # 38
  309. verify_eval("INT_37 < 0x25", 0) # 37
  310. verify_eval("INT_37 < 0x24", 0) # 36
  311. verify_eval("HEX_0X37 < 56", 2) # 0x38
  312. verify_eval("HEX_0X37 < 55", 0) # 0x37
  313. verify_eval("HEX_0X37 < 54", 0) # 0x36
  314. # Other int comparisons
  315. verify_eval("INT_37 <= 38", 2)
  316. verify_eval("INT_37 <= 37", 2)
  317. verify_eval("INT_37 <= 36", 0)
  318. verify_eval("INT_37 > 38", 0)
  319. verify_eval("INT_37 > 37", 0)
  320. verify_eval("INT_37 > 36", 2)
  321. verify_eval("INT_37 >= 38", 0)
  322. verify_eval("INT_37 >= 37", 2)
  323. verify_eval("INT_37 >= 36", 2)
  324. # Other hex comparisons
  325. verify_eval("HEX_0X37 <= 0x38", 2)
  326. verify_eval("HEX_0X37 <= 0x37", 2)
  327. verify_eval("HEX_0X37 <= 0x36", 0)
  328. verify_eval("HEX_0X37 > 0x38", 0)
  329. verify_eval("HEX_0X37 > 0x37", 0)
  330. verify_eval("HEX_0X37 > 0x36", 2)
  331. verify_eval("HEX_0X37 >= 0x38", 0)
  332. verify_eval("HEX_0X37 >= 0x37", 2)
  333. verify_eval("HEX_0X37 >= 0x36", 2)
  334. # A hex holding a value without a "0x" prefix should still be treated as
  335. # hexadecimal
  336. verify_eval("HEX_37 < 0x38", 2)
  337. verify_eval("HEX_37 < 0x37", 0)
  338. verify_eval("HEX_37 < 0x36", 0)
  339. # Symbol comparisons
  340. verify_eval("INT_37 < HEX_0X37", 2)
  341. verify_eval("INT_37 > HEX_0X37", 0)
  342. verify_eval("HEX_0X37 < INT_37 ", 0)
  343. verify_eval("HEX_0X37 > INT_37 ", 2)
  344. verify_eval("INT_37 < INT_37 ", 0)
  345. verify_eval("INT_37 <= INT_37 ", 2)
  346. verify_eval("INT_37 > INT_37 ", 0)
  347. verify_eval("INT_37 <= INT_37 ", 2)
  348. # Tristate value comparisons
  349. verify_eval("n < n", 0)
  350. verify_eval("n < m", 2)
  351. verify_eval("n < y", 2)
  352. verify_eval("n < N", 0)
  353. verify_eval("n < M", 2)
  354. verify_eval("n < Y", 2)
  355. verify_eval("0 > n", 0)
  356. verify_eval("1 > n", 2)
  357. verify_eval("2 > n", 2)
  358. verify_eval("m < n", 0)
  359. verify_eval("m < m", 0)
  360. verify_eval("m < y", 2)
  361. # Strings compare lexicographically
  362. verify_eval("'aa' < 'ab'", 2)
  363. verify_eval("'aa' > 'ab'", 0)
  364. verify_eval("'ab' < 'aa'", 0)
  365. verify_eval("'ab' > 'aa'", 2)
  366. # Comparisons where one of the operands doesn't parse as a number also give
  367. # a lexicographic comparison
  368. verify_eval("INT_37 < '37a' ", 2)
  369. verify_eval("'37a' > INT_37", 2)
  370. verify_eval("INT_37 <= '37a' ", 2)
  371. verify_eval("'37a' >= INT_37", 2)
  372. verify_eval("INT_37 >= '37a' ", 0)
  373. verify_eval("INT_37 > '37a' ", 0)
  374. verify_eval("'37a' < INT_37", 0)
  375. verify_eval("'37a' <= INT_37", 0)
  376. def verify_eval_bad(expr):
  377. try:
  378. c.eval_string(expr)
  379. except KconfigError:
  380. pass
  381. else:
  382. fail('expected eval_string("{}") to throw KconfigError, '
  383. "didn't".format(expr))
  384. # Verify that some bad stuff throws KconfigError's
  385. verify_eval_bad("")
  386. verify_eval_bad("&")
  387. verify_eval_bad("|")
  388. verify_eval_bad("!")
  389. verify_eval_bad("(")
  390. verify_eval_bad(")")
  391. verify_eval_bad("=")
  392. verify_eval_bad("(X")
  393. verify_eval_bad("X)")
  394. verify_eval_bad("X X")
  395. verify_eval_bad("!X X")
  396. verify_eval_bad("X !X")
  397. verify_eval_bad("(X) X")
  398. verify_eval_bad("X &&")
  399. verify_eval_bad("&& X")
  400. verify_eval_bad("X && && X")
  401. verify_eval_bad("X && !&&")
  402. verify_eval_bad("X ||")
  403. verify_eval_bad("|| X")
  404. print("Testing Symbol.__str__()/custom_str() and def_{int,hex,string}")
  405. def verify_str(item, s):
  406. verify_equal(str(item), s[1:-1])
  407. def verify_custom_str(item, s):
  408. verify_equal(item.custom_str(lambda sc: "[{}]".format(sc.name)),
  409. s[1:-1])
  410. c = Kconfig("Kconfiglib/tests/Kstr", warn=False)
  411. c.modules.set_value(2)
  412. verify_str(c.syms["UNDEFINED"], """
  413. """)
  414. verify_str(c.syms["BASIC_NO_PROMPT"], """
  415. config BASIC_NO_PROMPT
  416. bool
  417. help
  418. blah blah
  419. blah blah blah
  420. blah
  421. """)
  422. verify_str(c.syms["BASIC_PROMPT"], """
  423. config BASIC_PROMPT
  424. bool "basic"
  425. """)
  426. verify_str(c.syms["ADVANCED"], """
  427. config ADVANCED
  428. tristate "prompt" if DEP
  429. default DEFAULT_1
  430. default DEFAULT_2 if DEP
  431. select SELECTED_1
  432. select SELECTED_2 if DEP
  433. imply IMPLIED_1
  434. imply IMPLIED_2 if DEP
  435. help
  436. first help text
  437. config ADVANCED
  438. tristate "prompt 2"
  439. menuconfig ADVANCED
  440. tristate "prompt 3"
  441. config ADVANCED
  442. tristate
  443. depends on (A || !B || (C && D) || !(E && F) || G = H || (I && !J && (K || L) && !(M || N) && O = P)) && DEP4 && DEP3
  444. help
  445. second help text
  446. config ADVANCED
  447. tristate "prompt 4" if VIS
  448. depends on DEP4 && DEP3
  449. """)
  450. verify_custom_str(c.syms["ADVANCED"], """
  451. config ADVANCED
  452. tristate "prompt" if [DEP]
  453. default [DEFAULT_1]
  454. default [DEFAULT_2] if [DEP]
  455. select [SELECTED_1]
  456. select [SELECTED_2] if [DEP]
  457. imply [IMPLIED_1]
  458. imply [IMPLIED_2] if [DEP]
  459. help
  460. first help text
  461. config ADVANCED
  462. tristate "prompt 2"
  463. menuconfig ADVANCED
  464. tristate "prompt 3"
  465. config ADVANCED
  466. tristate
  467. depends on ([A] || ![B] || ([C] && [D]) || !([E] && [F]) || [G] = [H] || ([I] && ![J] && ([K] || [L]) && !([M] || [N]) && [O] = [P])) && [DEP4] && [DEP3]
  468. help
  469. second help text
  470. config ADVANCED
  471. tristate "prompt 4" if [VIS]
  472. depends on [DEP4] && [DEP3]
  473. """)
  474. verify_str(c.syms["ONLY_DIRECT_DEPS"], """
  475. config ONLY_DIRECT_DEPS
  476. int
  477. depends on DEP1 && DEP2
  478. """)
  479. verify_str(c.syms["STRING"], """
  480. config STRING
  481. string
  482. default "foo"
  483. default "bar" if DEP
  484. default STRING2
  485. default STRING3 if DEP
  486. """)
  487. verify_str(c.syms["INT"], """
  488. config INT
  489. int
  490. range 1 2
  491. range FOO BAR
  492. range BAZ QAZ if DEP
  493. default 7 if DEP
  494. """)
  495. verify_str(c.syms["HEX"], """
  496. config HEX
  497. hex
  498. range 0x100 0x200
  499. range FOO BAR
  500. range BAZ QAZ if DEP
  501. default 0x123
  502. """)
  503. verify_str(c.modules, """
  504. config MODULES
  505. bool "MODULES"
  506. option modules
  507. """)
  508. verify_str(c.syms["OPTIONS"], """
  509. config OPTIONS
  510. option allnoconfig_y
  511. option defconfig_list
  512. option env="ENV"
  513. """)
  514. verify_str(c.syms["CORRECT_PROP_LOCS_BOOL"], """
  515. config CORRECT_PROP_LOCS_BOOL
  516. bool "prompt 1"
  517. default DEFAULT_1
  518. default DEFAULT_2
  519. select SELECT_1
  520. select SELECT_2
  521. imply IMPLY_1
  522. imply IMPLY_2
  523. depends on LOC_1
  524. help
  525. help 1
  526. menuconfig CORRECT_PROP_LOCS_BOOL
  527. bool "prompt 2"
  528. default DEFAULT_3
  529. default DEFAULT_4
  530. select SELECT_3
  531. select SELECT_4
  532. imply IMPLY_3
  533. imply IMPLY_4
  534. depends on LOC_2
  535. help
  536. help 2
  537. config CORRECT_PROP_LOCS_BOOL
  538. bool "prompt 3"
  539. default DEFAULT_5
  540. default DEFAULT_6
  541. select SELECT_5
  542. select SELECT_6
  543. imply IMPLY_5
  544. imply IMPLY_6
  545. depends on LOC_3
  546. help
  547. help 2
  548. """)
  549. verify_str(c.syms["CORRECT_PROP_LOCS_INT"], """
  550. config CORRECT_PROP_LOCS_INT
  551. int
  552. range 1 2
  553. range 3 4
  554. depends on LOC_1
  555. config CORRECT_PROP_LOCS_INT
  556. int
  557. range 5 6
  558. range 7 8
  559. depends on LOC_2
  560. """)
  561. verify_str(c.syms["PROMPT_ONLY"], """
  562. config PROMPT_ONLY
  563. prompt "prompt only"
  564. """)
  565. verify_custom_str(c.syms["CORRECT_PROP_LOCS_INT"], """
  566. config CORRECT_PROP_LOCS_INT
  567. int
  568. range [1] [2]
  569. range [3] [4]
  570. depends on [LOC_1]
  571. config CORRECT_PROP_LOCS_INT
  572. int
  573. range [5] [6]
  574. range [7] [8]
  575. depends on [LOC_2]
  576. """)
  577. print("Testing Choice.__str__()/custom_str()")
  578. verify_str(c.named_choices["CHOICE"], """
  579. choice CHOICE
  580. tristate "foo"
  581. default CHOICE_1
  582. default CHOICE_2 if dep
  583. """)
  584. verify_str(c.named_choices["CHOICE"].nodes[0].next.item, """
  585. choice
  586. tristate "no name"
  587. optional
  588. """)
  589. verify_str(c.named_choices["CORRECT_PROP_LOCS_CHOICE"], """
  590. choice CORRECT_PROP_LOCS_CHOICE
  591. bool
  592. default CHOICE_3
  593. depends on LOC_1
  594. choice CORRECT_PROP_LOCS_CHOICE
  595. bool
  596. default CHOICE_4
  597. depends on LOC_2
  598. choice CORRECT_PROP_LOCS_CHOICE
  599. bool
  600. default CHOICE_5
  601. depends on LOC_3
  602. """)
  603. verify_custom_str(c.named_choices["CORRECT_PROP_LOCS_CHOICE"], """
  604. choice CORRECT_PROP_LOCS_CHOICE
  605. bool
  606. default [CHOICE_3]
  607. depends on [LOC_1]
  608. choice CORRECT_PROP_LOCS_CHOICE
  609. bool
  610. default [CHOICE_4]
  611. depends on [LOC_2]
  612. choice CORRECT_PROP_LOCS_CHOICE
  613. bool
  614. default [CHOICE_5]
  615. depends on [LOC_3]
  616. """)
  617. print("Testing MenuNode.__str__()/custom_str() for menus and comments")
  618. verify_str(c.syms["SIMPLE_MENU_HOOK"].nodes[0].next, """
  619. menu "simple menu"
  620. """)
  621. verify_str(c.syms["ADVANCED_MENU_HOOK"].nodes[0].next, """
  622. menu "advanced menu"
  623. depends on A
  624. visible if B && (C || D)
  625. """)
  626. verify_custom_str(c.syms["ADVANCED_MENU_HOOK"].nodes[0].next, """
  627. menu "advanced menu"
  628. depends on [A]
  629. visible if [B] && ([C] || [D])
  630. """)
  631. verify_str(c.syms["SIMPLE_COMMENT_HOOK"].nodes[0].next, """
  632. comment "simple comment"
  633. """)
  634. verify_str(c.syms["ADVANCED_COMMENT_HOOK"].nodes[0].next, """
  635. comment "advanced comment"
  636. depends on A && B
  637. """)
  638. verify_custom_str(c.syms["ADVANCED_COMMENT_HOOK"].nodes[0].next, """
  639. comment "advanced comment"
  640. depends on [A] && [B]
  641. """)
  642. print("Testing {MenuNode,Symbol,Choice}.orig_*")
  643. # Just test some corner cases here re. MenuNode.orig_*. They are already
  644. # indirectly tested above. Use MenuNode.__str__() as a proxy.
  645. verify_str(c.syms["DEP_REM_CORNER_CASES"], """
  646. config DEP_REM_CORNER_CASES
  647. bool
  648. default A
  649. depends on n
  650. config DEP_REM_CORNER_CASES
  651. bool
  652. default B if n
  653. config DEP_REM_CORNER_CASES
  654. bool
  655. default C
  656. depends on m && MODULES
  657. config DEP_REM_CORNER_CASES
  658. bool
  659. default D if A
  660. config DEP_REM_CORNER_CASES
  661. bool
  662. default E if !E1
  663. default F if F1 = F2
  664. default G if G1 || H1
  665. depends on !H
  666. config DEP_REM_CORNER_CASES
  667. bool
  668. default H
  669. depends on "foo" = "bar"
  670. config DEP_REM_CORNER_CASES
  671. bool "prompt" if FOO || BAR
  672. depends on BAZ && QAZ
  673. """)
  674. # Test {Symbol,Choice}.orig_*
  675. def verify_deps(elms, dep_index, expected):
  676. verify_equal(" ".join(expr_str(elm[dep_index]) for elm in elms),
  677. expected)
  678. verify_deps(c.syms["BOOL_SYM_ORIG"].orig_defaults, 1, "DEP y y")
  679. verify_deps(c.syms["BOOL_SYM_ORIG"].orig_selects, 1, "y DEP y")
  680. verify_deps(c.syms["BOOL_SYM_ORIG"].orig_implies, 1, "y y DEP")
  681. verify_deps(c.syms["INT_SYM_ORIG"].orig_ranges, 2, "DEP y DEP")
  682. verify_deps(c.named_choices["CHOICE_ORIG"].orig_defaults, 1, "y DEP DEP")
  683. print("Testing Symbol.__repr__()")
  684. def verify_repr(item, s):
  685. verify_equal(repr(item) + "\n", s[1:])
  686. c = Kconfig("Kconfiglib/tests/Krepr", warn=False)
  687. verify_repr(c.n, """
  688. <symbol n, tristate, value n, constant>
  689. """)
  690. verify_repr(c.m, """
  691. <symbol m, tristate, value m, constant>
  692. """)
  693. verify_repr(c.y, """
  694. <symbol y, tristate, value y, constant>
  695. """)
  696. verify_repr(c.syms["UNDEFINED"], """
  697. <symbol UNDEFINED, unknown, value "UNDEFINED", visibility n, direct deps n, undefined>
  698. """)
  699. verify_repr(c.syms["BASIC"], """
  700. <symbol BASIC, bool, value y, visibility n, direct deps y, Kconfiglib/tests/Krepr:9>
  701. """)
  702. verify_repr(c.syms["VISIBLE"], """
  703. <symbol VISIBLE, bool, "visible", value n, visibility y, direct deps y, Kconfiglib/tests/Krepr:14>
  704. """)
  705. c.syms["VISIBLE"].set_value(2)
  706. c.syms["STRING"].set_value("foo")
  707. verify_repr(c.syms["VISIBLE"], """
  708. <symbol VISIBLE, bool, "visible", value y, user value y, visibility y, direct deps y, Kconfiglib/tests/Krepr:14>
  709. """)
  710. verify_repr(c.syms["STRING"], """
  711. <symbol STRING, string, "visible", value "foo", user value "foo", visibility y, direct deps y, Kconfiglib/tests/Krepr:17>
  712. """)
  713. verify_repr(c.syms["DIR_DEP_N"], """
  714. <symbol DIR_DEP_N, unknown, value "DIR_DEP_N", visibility n, direct deps n, Kconfiglib/tests/Krepr:20>
  715. """)
  716. verify_repr(c.syms["OPTIONS"], """
  717. <symbol OPTIONS, unknown, value "OPTIONS", visibility n, allnoconfig_y, is the defconfig_list symbol, from environment variable ENV, direct deps y, Kconfiglib/tests/Krepr:23>
  718. """)
  719. verify_repr(c.syms["MULTI_DEF"], """
  720. <symbol MULTI_DEF, unknown, value "MULTI_DEF", visibility n, direct deps y, Kconfiglib/tests/Krepr:28, Kconfiglib/tests/Krepr:29>
  721. """)
  722. verify_repr(c.syms["CHOICE_1"], """
  723. <symbol CHOICE_1, tristate, "choice sym", value n, visibility m, choice symbol, direct deps m, Kconfiglib/tests/Krepr:36>
  724. """)
  725. verify_repr(c.modules, """
  726. <symbol MODULES, bool, value y, visibility n, is the modules symbol, direct deps y, Kconfiglib/tests/Krepr:1>
  727. """)
  728. print("Testing Choice.__repr__()")
  729. verify_repr(c.named_choices["CHOICE"], """
  730. <choice CHOICE, tristate, "choice", mode m, visibility y, Kconfiglib/tests/Krepr:33>
  731. """)
  732. c.named_choices["CHOICE"].set_value(2)
  733. verify_repr(c.named_choices["CHOICE"], """
  734. <choice CHOICE, tristate, "choice", mode y, user mode y, CHOICE_1 selected, visibility y, Kconfiglib/tests/Krepr:33>
  735. """)
  736. c.syms["CHOICE_2"].set_value(2)
  737. verify_repr(c.named_choices["CHOICE"], """
  738. <choice CHOICE, tristate, "choice", mode y, user mode y, CHOICE_2 selected, CHOICE_2 selected by user, visibility y, Kconfiglib/tests/Krepr:33>
  739. """)
  740. c.named_choices["CHOICE"].set_value(1)
  741. verify_repr(c.named_choices["CHOICE"], """
  742. <choice CHOICE, tristate, "choice", mode m, user mode m, CHOICE_2 selected by user (overridden), visibility y, Kconfiglib/tests/Krepr:33>
  743. """)
  744. verify_repr(c.syms["CHOICE_HOOK"].nodes[0].next.item, """
  745. <choice, tristate, "optional choice", mode n, visibility n, optional, Kconfiglib/tests/Krepr:46>
  746. """)
  747. print("Testing MenuNode.__repr__()")
  748. verify_repr(c.syms["BASIC"].nodes[0], """
  749. <menu node for symbol BASIC, deps y, has help, has next, Kconfiglib/tests/Krepr:9>
  750. """)
  751. verify_repr(c.syms["DIR_DEP_N"].nodes[0], """
  752. <menu node for symbol DIR_DEP_N, deps n, has next, Kconfiglib/tests/Krepr:20>
  753. """)
  754. verify_repr(c.syms["MULTI_DEF"].nodes[0], """
  755. <menu node for symbol MULTI_DEF, deps y, has next, Kconfiglib/tests/Krepr:28>
  756. """)
  757. verify_repr(c.syms["MULTI_DEF"].nodes[1], """
  758. <menu node for symbol MULTI_DEF, deps y, has next, Kconfiglib/tests/Krepr:29>
  759. """)
  760. verify_repr(c.syms["MENUCONFIG"].nodes[0], """
  761. <menu node for symbol MENUCONFIG, is menuconfig, deps y, has next, Kconfiglib/tests/Krepr:31>
  762. """)
  763. verify_repr(c.named_choices["CHOICE"].nodes[0], """
  764. <menu node for choice CHOICE, prompt "choice" (visibility y), deps y, has child, has next, Kconfiglib/tests/Krepr:33>
  765. """)
  766. verify_repr(c.syms["CHOICE_HOOK"].nodes[0].next, """
  767. <menu node for choice, prompt "optional choice" (visibility n), deps y, has next, Kconfiglib/tests/Krepr:46>
  768. """)
  769. verify_repr(c.syms["NO_VISIBLE_IF_HOOK"].nodes[0].next, """
  770. <menu node for menu, prompt "no visible if" (visibility y), deps y, 'visible if' deps y, has next, Kconfiglib/tests/Krepr:53>
  771. """)
  772. verify_repr(c.syms["VISIBLE_IF_HOOK"].nodes[0].next, """
  773. <menu node for menu, prompt "visible if" (visibility y), deps y, 'visible if' deps m, has next, Kconfiglib/tests/Krepr:58>
  774. """)
  775. verify_repr(c.syms["COMMENT_HOOK"].nodes[0].next, """
  776. <menu node for comment, prompt "comment" (visibility y), deps y, Kconfiglib/tests/Krepr:64>
  777. """)
  778. print("Testing Kconfig.__repr__()")
  779. verify_repr(c, """
  780. <configuration with 15 symbols, main menu prompt "Main menu", srctree is current directory, config symbol prefix "CONFIG_", warnings disabled, printing of warnings to stderr enabled, undef. symbol assignment warnings disabled, overriding symbol assignment warnings enabled, redundant symbol assignment warnings enabled>
  781. """)
  782. os.environ["srctree"] = "Kconfiglib"
  783. os.environ["CONFIG_"] = "CONFIG_ value"
  784. c = Kconfig("tests/Krepr", warn=False)
  785. c.warn = True
  786. c.warn_to_stderr = False
  787. c.warn_assign_override = False
  788. c.warn_assign_redun = False
  789. c.warn_assign_undef = True
  790. verify_repr(c, """
  791. <configuration with 15 symbols, main menu prompt "Main menu", srctree "Kconfiglib", config symbol prefix "CONFIG_ value", warnings enabled, printing of warnings to stderr disabled, undef. symbol assignment warnings enabled, overriding symbol assignment warnings disabled, redundant symbol assignment warnings disabled>
  792. """)
  793. os.environ.pop("srctree", None)
  794. os.environ.pop("CONFIG_", None)
  795. print("Testing tricky help strings")
  796. c = Kconfig("Kconfiglib/tests/Khelp")
  797. def verify_help(node, s):
  798. verify_equal(node.help, s[1:-1])
  799. verify_help(c.syms["TWO_HELP_STRINGS"].nodes[0], """
  800. first help string
  801. """)
  802. verify_help(c.syms["TWO_HELP_STRINGS"].nodes[1], """
  803. second help string
  804. """)
  805. verify_help(c.syms["NO_BLANK_AFTER_HELP"].nodes[0], """
  806. help for
  807. NO_BLANK_AFTER_HELP
  808. """)
  809. verify_help(c.named_choices["CHOICE_HELP"].nodes[0], """
  810. help for
  811. CHOICE_HELP
  812. """)
  813. verify_help(c.syms["HELP_TERMINATED_BY_COMMENT"].nodes[0], """
  814. a
  815. b
  816. c
  817. """)
  818. verify_help(c.syms["TRICKY_HELP"].nodes[0], """
  819. a
  820. b
  821. c
  822. d
  823. e
  824. f
  825. g
  826. h
  827. i
  828. """)
  829. print("Testing locations, source/rsource/gsource/grsource, and "
  830. "Kconfig.kconfig_filenames")
  831. def verify_locations(nodes, *expected_locs):
  832. verify(len(nodes) == len(expected_locs),
  833. "Wrong number of locations for " + repr(nodes))
  834. for node, expected_loc in zip(nodes, expected_locs):
  835. node_loc = "{}:{}".format(node.filename, node.linenr)
  836. verify(node_loc == expected_loc,
  837. "expected {} to have the location {}, had the location {}"
  838. .format(repr(node), expected_loc, node_loc))
  839. # Expanded in the 'source' statement in Klocation
  840. os.environ["TESTS_DIR_FROM_ENV"] = "tests"
  841. os.environ["SUB_DIR_FROM_ENV"] = "sub"
  842. os.environ["_SOURCED"] = "_sourced"
  843. os.environ["_RSOURCED"] = "_rsourced"
  844. os.environ["_GSOURCED"] = "_gsourced"
  845. os.environ["_GRSOURCED"] = "_grsourced"
  846. # Test twice, with $srctree as a relative and an absolute path,
  847. # respectively
  848. for srctree in "Kconfiglib", os.path.abspath("Kconfiglib"):
  849. os.environ["srctree"] = srctree
  850. # Has symbol with empty help text, so disable warnings
  851. c = Kconfig("tests/Klocation", warn=False)
  852. verify_locations(c.syms["UNDEFINED"].nodes)
  853. verify_equal(c.syms["UNDEFINED"].name_and_loc, "UNDEFINED (undefined)")
  854. verify_locations(c.syms["ONE_DEF"].nodes, "tests/Klocation:4")
  855. verify_equal(c.syms["ONE_DEF"].name_and_loc,
  856. "ONE_DEF (defined at tests/Klocation:4)")
  857. verify_locations(c.syms["TWO_DEF"].nodes,
  858. "tests/Klocation:7",
  859. "tests/Klocation:10")
  860. verify_equal(c.syms["TWO_DEF"].name_and_loc,
  861. "TWO_DEF (defined at tests/Klocation:7, tests/Klocation:10)")
  862. verify_locations(c.syms["MANY_DEF"].nodes,
  863. "tests/Klocation:13",
  864. "tests/Klocation:43",
  865. "tests/Klocation:45",
  866. "tests/Klocation_sourced:3",
  867. "tests/sub/Klocation_rsourced:2",
  868. "tests/sub/Klocation_gsourced1:1",
  869. "tests/sub/Klocation_gsourced2:1",
  870. "tests/sub/Klocation_gsourced1:1",
  871. "tests/sub/Klocation_gsourced2:1",
  872. "tests/sub/Klocation_grsourced1:1",
  873. "tests/sub/Klocation_grsourced2:1",
  874. "tests/sub/Klocation_grsourced1:1",
  875. "tests/sub/Klocation_grsourced2:1",
  876. "tests/Klocation:78")
  877. verify_locations(c.named_choices["CHOICE_ONE_DEF"].nodes,
  878. "tests/Klocation_sourced:5")
  879. verify_equal(c.named_choices["CHOICE_ONE_DEF"].name_and_loc,
  880. "<choice CHOICE_ONE_DEF> (defined at tests/Klocation_sourced:5)")
  881. verify_locations(c.named_choices["CHOICE_TWO_DEF"].nodes,
  882. "tests/Klocation_sourced:9",
  883. "tests/Klocation_sourced:13")
  884. verify_equal(c.named_choices["CHOICE_TWO_DEF"].name_and_loc,
  885. "<choice CHOICE_TWO_DEF> (defined at tests/Klocation_sourced:9, tests/Klocation_sourced:13)")
  886. verify_locations([c.syms["MENU_HOOK"].nodes[0].next],
  887. "tests/Klocation_sourced:20")
  888. verify_locations([c.syms["COMMENT_HOOK"].nodes[0].next],
  889. "tests/Klocation_sourced:26")
  890. # Test Kconfig.kconfig_filenames
  891. verify_equal(c.kconfig_filenames, [
  892. "tests/Klocation",
  893. "tests/Klocation_sourced",
  894. "tests/sub/Klocation_rsourced",
  895. "tests/sub/Klocation_gsourced1",
  896. "tests/sub/Klocation_gsourced2",
  897. "tests/sub/Klocation_gsourced1",
  898. "tests/sub/Klocation_gsourced2",
  899. "tests/sub/Klocation_grsourced1",
  900. "tests/sub/Klocation_grsourced2",
  901. "tests/sub/Klocation_grsourced1",
  902. "tests/sub/Klocation_grsourced2"
  903. ])
  904. # Test recursive 'source' detection
  905. try:
  906. Kconfig("tests/Krecursive1")
  907. except KconfigError as e:
  908. verify_equal(str(e), """
  909. tests/Krecursive2:1: recursive 'source' of 'tests/Krecursive1' detected. Check that environment variables are set correctly.
  910. Include path:
  911. tests/Krecursive1:1
  912. tests/Krecursive2:1
  913. """[:-1])
  914. except:
  915. fail("recursive 'source' raised wrong exception")
  916. else:
  917. fail("recursive 'source' did not raise exception")
  918. # Verify that source and rsource throw exceptions for missing files
  919. # TODO: Make an exception test helper
  920. try:
  921. Kconfig("tests/Kmissingsource")
  922. except KconfigError as e:
  923. if "not found" not in str(e):
  924. fail("'source' with missing file raised wrong KconfigError")
  925. except:
  926. fail("'source' with missing file raised wrong exception")
  927. else:
  928. fail("'source' with missing file did not raise exception")
  929. try:
  930. Kconfig("tests/Kmissingrsource")
  931. except KconfigError as e:
  932. if "not found" not in str(e):
  933. fail("'rsource' with missing file raised wrong KconfigError")
  934. except:
  935. fail("'rsource' with missing file raised wrong exception")
  936. else:
  937. fail("'rsource' with missing file did not raise exception")
  938. # Test a tricky case involving symlinks. $srctree is tests/symlink, which
  939. # points to tests/sub/sub, meaning tests/symlink/.. != tests/. Previously,
  940. # using 'rsource' from a file sourced with an absolute path triggered an
  941. # unsafe relpath() with tests/symlink/.. in it, crashing.
  942. os.environ["srctree"] = "Kconfiglib/tests/symlink"
  943. os.environ["KCONFIG_SYMLINK_2"] = os.path.abspath(
  944. "Kconfiglib/tests/sub/Kconfig_symlink_2")
  945. if not os.path.isabs(
  946. Kconfig("Kconfig_symlink_1").syms["FOUNDME"].nodes[0].filename):
  947. fail("Symlink + rsource issues")
  948. print("Testing Kconfig.node_iter()")
  949. # Reuse tests/Klocation. The node_iter(unique_syms=True) case already gets
  950. # plenty of testing from write_config() as well.
  951. os.environ["srctree"] = "Kconfiglib"
  952. c = Kconfig("tests/Klocation", warn=False)
  953. verify_equal(
  954. [node.item.name for node in c.node_iter()
  955. if isinstance(node.item, Symbol)],
  956. ["ONE_DEF", "TWO_DEF", "TWO_DEF", "MANY_DEF", "HELP_1", "HELP_2",
  957. "HELP_3", "MANY_DEF", "MANY_DEF", "MANY_DEF", "MENU_HOOK",
  958. "COMMENT_HOOK"] + 10*["MANY_DEF"])
  959. verify_equal(
  960. [node.item.name for node in c.node_iter(True)
  961. if isinstance(node.item, Symbol)],
  962. ["ONE_DEF", "TWO_DEF", "MANY_DEF", "HELP_1", "HELP_2", "HELP_3",
  963. "MENU_HOOK", "COMMENT_HOOK"])
  964. verify_equal(
  965. [node.prompt[0] for node in c.node_iter()
  966. if not isinstance(node.item, Symbol)],
  967. ["one-def choice", "two-def choice 1", "two-def choice 2",
  968. "menu", "comment"])
  969. verify_equal(
  970. [node.prompt[0] for node in c.node_iter(True)
  971. if not isinstance(node.item, Symbol)],
  972. ["one-def choice", "two-def choice 1", "two-def choice 2",
  973. "menu", "comment"])
  974. print("Testing MenuNode.include_path")
  975. os.environ["srctree"] = "Kconfiglib/tests"
  976. c = Kconfig("Kinclude_path")
  977. def verify_node_path(node, *expected):
  978. if node.include_path != expected:
  979. fail("Wrong include path for node {!r}. Got {}, expected {}."
  980. .format(node, node.include_path, expected))
  981. def verify_sym_path(sym_name, node_i, *expected):
  982. verify_node_path(c.syms[sym_name].nodes[node_i], *expected)
  983. verify_sym_path("TOP", 0)
  984. verify_sym_path("TOP", 1)
  985. verify_sym_path("TOP", 2)
  986. verify_sym_path("ONE_DOWN", 0, ("Kinclude_path", 4))
  987. verify_sym_path("ONE_DOWN", 1, ("Kinclude_path", 4))
  988. verify_sym_path("ONE_DOWN", 2, ("Kinclude_path", 4))
  989. verify_sym_path("ONE_DOWN", 3, ("Kinclude_path", 9))
  990. verify_sym_path("ONE_DOWN", 4, ("Kinclude_path", 9))
  991. verify_sym_path("ONE_DOWN", 5, ("Kinclude_path", 9))
  992. verify_sym_path("TWO_DOWN", 0,
  993. ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
  994. verify_sym_path("TWO_DOWN", 1,
  995. ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 9))
  996. verify_sym_path("TWO_DOWN", 2,
  997. ("Kinclude_path", 9), ("Kinclude_path_sourced_1", 4))
  998. verify_sym_path("TWO_DOWN", 3,
  999. ("Kinclude_path", 9), ("Kinclude_path_sourced_1", 9))
  1000. verify_node_path(c.top_node)
  1001. verify_node_path(c.menus[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
  1002. verify_node_path(c.comments[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
  1003. verify_node_path(c.choices[0].nodes[0], ("Kinclude_path", 4), ("Kinclude_path_sourced_1", 4))
  1004. os.environ.pop("srctree", None)
  1005. print("Testing Kconfig.choices/menus/comments")
  1006. c = Kconfig("Kconfiglib/tests/Kitemlists")
  1007. def verify_prompts(items, *expected_prompts):
  1008. verify(len(items) == len(expected_prompts),
  1009. "Wrong number of prompts for {}".format(items))
  1010. for item, expected_prompt in zip(items, expected_prompts):
  1011. if not isinstance(item, MenuNode):
  1012. item = item.nodes[0]
  1013. verify(item.prompt[0] == expected_prompt,
  1014. "Wrong prompt for {}, expected '{}'"
  1015. .format(repr(item), expected_prompt))
  1016. verify_prompts(c.choices, "choice 1", "choice 2", "choice 3", "choice 2")
  1017. verify_prompts(c.menus, "menu 1", "menu 2", "menu 3", "menu 4", "menu 5")
  1018. verify_prompts(c.comments, "comment 1", "comment 2", "comment 3")
  1019. print("Testing Symbol/Choice.direct_dep")
  1020. c = Kconfig("Kconfiglib/tests/Kdirdep")
  1021. verify_equal(expr_str(c.syms["NO_DEP_SYM"].direct_dep), 'y')
  1022. verify_equal(expr_str(c.syms["DEP_SYM"].direct_dep), "A || (B && C) || !D")
  1023. verify_equal(expr_str(c.named_choices["NO_DEP_CHOICE"].direct_dep), 'y')
  1024. verify_equal(expr_str(c.named_choices["DEP_CHOICE"].direct_dep),
  1025. "A || B || C")
  1026. print("Testing expr_items()")
  1027. c = Kconfig("Kconfiglib/tests/Kexpr_items")
  1028. def verify_expr_items(expr, *sym_names):
  1029. verify_equal(tuple(sorted(item.name for item in expr_items(expr))),
  1030. sym_names)
  1031. verify_expr_items(
  1032. c.syms["TEST"].defaults[0][0],
  1033. "A", "B", "C", "D", "E", "F", "G", "H"
  1034. )
  1035. verify_expr_items(
  1036. c.syms["TEST_CHOICE"].nodes[0].prompt[1],
  1037. "A", "CHOICE"
  1038. )
  1039. print("Testing MenuNode/Symbol/Choice.referenced")
  1040. c = Kconfig("Kconfiglib/tests/Kreferenced", warn=False)
  1041. def verify_deps(item, *dep_names):
  1042. verify_equal(tuple(sorted(item.name for item in item.referenced)),
  1043. dep_names)
  1044. verify_deps(c.top_node, "y")
  1045. verify_deps(c.syms["NO_REFS"].nodes[0], "y")
  1046. verify_deps(c.syms["JUST_DEPENDS_ON_REFS"].nodes[0], "A", "B")
  1047. verify_deps(c.syms["LOTS_OF_REFS"].nodes[0],
  1048. *(chr(n) for n in range(ord("A"), ord("Z") + 1)))
  1049. verify_deps(c.syms["INT_REFS"].nodes[0],
  1050. "A", "B", "C", "D", "E", "F", "G", "H", "y")
  1051. verify_deps(c.syms["CHOICE_REF"].nodes[0], "CHOICE")
  1052. verify_deps(c.menus[0], "A", "B", "C", "D")
  1053. verify_deps(c.comments[0], "A", "B")
  1054. verify_deps(c.syms["MULTI_DEF_SYM"], "A", "B", "C", "y")
  1055. verify_deps(c.named_choices["MULTI_DEF_CHOICE"], "A", "B", "C")
  1056. print("Testing split_expr()")
  1057. c = Kconfig("Kconfiglib/tests/empty")
  1058. c.warn = False
  1059. def verify_split(to_split, op, operand_strs):
  1060. # The same hackage as in Kconfig.eval_string()
  1061. c._tokens = c._tokenize("if " + to_split)[1:]
  1062. c._tokens_i = 0
  1063. operands = split_expr(c._parse_expr(False), op)
  1064. verify(len(operands) == len(operand_strs),
  1065. "Wrong number of operands when {} was split by {}"
  1066. .format(to_split, "OR" if op == OR else "AND"))
  1067. for operand, operand_str in zip(operands, operand_strs):
  1068. verify_equal(expr_str(operand), operand_str)
  1069. verify_split("A", OR, ("A", ))
  1070. verify_split("!A", OR, ("!A", ))
  1071. verify_split("A = B", OR, ("A = B", ))
  1072. verify_split("A && B", OR, ("A && B", ))
  1073. verify_split("A || B", OR, ("A", "B" ))
  1074. verify_split("(A || B) || C", OR, ("A", "B", "C" ))
  1075. verify_split("A || (B || C)", OR, ("A", "B", "C" ))
  1076. verify_split("A || !(B || C)", OR, ("A", "!(B || C)" ))
  1077. verify_split("A || (B && (C || D))", OR, ("A", "B && (C || D)"))
  1078. verify_split("(A && (B || C)) || D", OR, ("A && (B || C)", "D"))
  1079. verify_split("A", AND, ("A", ))
  1080. verify_split("!A", AND, ("!A", ))
  1081. verify_split("A = B", AND, ("A = B", ))
  1082. verify_split("A || B", AND, ("A || B", ))
  1083. verify_split("A && B", AND, ("A", "B" ))
  1084. verify_split("(A && B) && C", AND, ("A", "B", "C" ))
  1085. verify_split("A && (B && C)", AND, ("A", "B", "C" ))
  1086. verify_split("A && !(B && C)", AND, ("A", "!(B && C)" ))
  1087. verify_split("A && (B || (C && D))", AND, ("A", "B || (C && D)"))
  1088. verify_split("(A || (B && C)) && D", AND, ("A || (B && C)", "D"))
  1089. print("Testing visibility")
  1090. c = Kconfig("Kconfiglib/tests/Kvisibility")
  1091. def verify_visibility(item, no_module_vis, module_vis):
  1092. c.modules.set_value(0)
  1093. verify(item.visibility == no_module_vis,
  1094. "expected {} to have visibility {} without modules, had "
  1095. "visibility {}".
  1096. format(repr(item), no_module_vis, item.visibility))
  1097. c.modules.set_value(2)
  1098. verify(item.visibility == module_vis,
  1099. "expected {} to have visibility {} with modules, had "
  1100. "visibility {}".
  1101. format(repr(item), module_vis, item.visibility))
  1102. # Symbol visibility
  1103. verify_visibility(c.syms["NO_PROMPT"], 0, 0)
  1104. verify_visibility(c.syms["BOOL_N"], 0, 0)
  1105. verify_visibility(c.syms["BOOL_M"], 0, 2)
  1106. verify_visibility(c.syms["BOOL_MOD"], 2, 2)
  1107. verify_visibility(c.syms["BOOL_Y"], 2, 2)
  1108. verify_visibility(c.syms["TRISTATE_M"], 0, 1)
  1109. verify_visibility(c.syms["TRISTATE_MOD"], 2, 1)
  1110. verify_visibility(c.syms["TRISTATE_Y"], 2, 2)
  1111. verify_visibility(c.syms["BOOL_IF_N"], 0, 0)
  1112. verify_visibility(c.syms["BOOL_IF_M"], 0, 2)
  1113. verify_visibility(c.syms["BOOL_IF_Y"], 2, 2)
  1114. verify_visibility(c.syms["BOOL_MENU_N"], 0, 0)
  1115. verify_visibility(c.syms["BOOL_MENU_M"], 0, 2)
  1116. verify_visibility(c.syms["BOOL_MENU_Y"], 2, 2)
  1117. verify_visibility(c.syms["BOOL_CHOICE_N"], 0, 0)
  1118. # Non-tristate symbols in tristate choices are only visible if the choice
  1119. # is in y mode
  1120. # The choice can't be brought to y mode because of the 'if m'
  1121. verify_visibility(c.syms["BOOL_CHOICE_M"], 0, 0)
  1122. c.syms["BOOL_CHOICE_M"].choice.set_value(2)
  1123. verify_visibility(c.syms["BOOL_CHOICE_M"], 0, 0)
  1124. # The choice gets y mode only when running without modules, because it
  1125. # defaults to m mode
  1126. verify_visibility(c.syms["BOOL_CHOICE_Y"], 2, 0)
  1127. c.syms["BOOL_CHOICE_Y"].choice.set_value(2)
  1128. # When set to y mode, the choice symbol becomes visible both with and
  1129. # without modules
  1130. verify_visibility(c.syms["BOOL_CHOICE_Y"], 2, 2)
  1131. verify_visibility(c.syms["TRISTATE_IF_N"], 0, 0)
  1132. verify_visibility(c.syms["TRISTATE_IF_M"], 0, 1)
  1133. verify_visibility(c.syms["TRISTATE_IF_Y"], 2, 2)
  1134. verify_visibility(c.syms["TRISTATE_MENU_N"], 0, 0)
  1135. verify_visibility(c.syms["TRISTATE_MENU_M"], 0, 1)
  1136. verify_visibility(c.syms["TRISTATE_MENU_Y"], 2, 2)
  1137. verify_visibility(c.syms["TRISTATE_CHOICE_N"], 0, 0)
  1138. verify_visibility(c.syms["TRISTATE_CHOICE_M"], 0, 1)
  1139. verify_visibility(c.syms["TRISTATE_CHOICE_Y"], 2, 2)
  1140. verify_visibility(c.named_choices["BOOL_CHOICE_N"], 0, 0)
  1141. verify_visibility(c.named_choices["BOOL_CHOICE_M"], 0, 2)
  1142. verify_visibility(c.named_choices["BOOL_CHOICE_Y"], 2, 2)
  1143. verify_visibility(c.named_choices["TRISTATE_CHOICE_N"], 0, 0)
  1144. verify_visibility(c.named_choices["TRISTATE_CHOICE_M"], 0, 1)
  1145. verify_visibility(c.named_choices["TRISTATE_CHOICE_Y"], 2, 2)
  1146. verify_visibility(c.named_choices["TRISTATE_CHOICE_IF_M_AND_Y"], 0, 1)
  1147. verify_visibility(c.named_choices["TRISTATE_CHOICE_MENU_N_AND_Y"], 0, 0)
  1148. # Verify that 'visible if' visibility gets propagated to prompts
  1149. verify_visibility(c.syms["VISIBLE_IF_N"], 0, 0)
  1150. verify_visibility(c.syms["VISIBLE_IF_M"], 0, 1)
  1151. verify_visibility(c.syms["VISIBLE_IF_Y"], 2, 2)
  1152. verify_visibility(c.syms["VISIBLE_IF_M_2"], 0, 1)
  1153. # Verify that string/int/hex symbols with m visibility accept a user value
  1154. assign_and_verify("STRING_m", "foo bar")
  1155. assign_and_verify("INT_m", "123")
  1156. assign_and_verify("HEX_m", "0x123")
  1157. print("Testing .assignable")
  1158. c = Kconfig("Kconfiglib/tests/Kassignable")
  1159. def verify_assignable_imp(item, assignable_no_modules, assignable_modules):
  1160. # Verifies the assignable values for 'item', with and without modules.
  1161. for modules_val, assignable in (0, assignable_no_modules), \
  1162. (2, assignable_modules):
  1163. c.modules.set_value(modules_val)
  1164. module_msg = "without modules" if modules_val == 0 else \
  1165. "with modules"
  1166. verify(item.assignable == assignable,
  1167. "Incorrect assignable values for {} {}. Should be {}, "
  1168. "was {}."
  1169. .format(item.name, module_msg, assignable, item.assignable))
  1170. # Verify that the values can actually be assigned too
  1171. for val in item.assignable:
  1172. item.set_value(val)
  1173. verify(item.tri_value == val,
  1174. "Unable to set {} to {} {}, even though it was in "
  1175. ".assignable".format(item.name, val, module_msg))
  1176. def verify_assignable(sym_name, assignable_no_modules, assignable_modules):
  1177. verify_assignable_imp(c.syms[sym_name],
  1178. assignable_no_modules,
  1179. assignable_modules)
  1180. def verify_const_unassignable(sym_name):
  1181. verify_assignable_imp(c.const_syms[sym_name], (), ())
  1182. # Things that shouldn't be .assignable
  1183. verify_const_unassignable("n")
  1184. verify_const_unassignable("m")
  1185. verify_const_unassignable("y")
  1186. verify_const_unassignable("const")
  1187. verify_assignable("UNDEFINED", (), ())
  1188. verify_assignable("NO_PROMPT", (), ())
  1189. verify_assignable("STRING", (), ())
  1190. verify_assignable("INT", (), ())
  1191. verify_assignable("HEX", (), ())
  1192. # Non-selected symbols
  1193. verify_assignable("Y_VIS_BOOL", (0, 2), (0, 2))
  1194. verify_assignable("M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
  1195. verify_assignable("N_VIS_BOOL", ( ), ( ))
  1196. verify_assignable("Y_VIS_TRI", (0, 2), (0, 1, 2))
  1197. verify_assignable("M_VIS_TRI", ( ), (0, 1 ))
  1198. verify_assignable("N_VIS_TRI", ( ), ( ))
  1199. # Symbols selected to y
  1200. verify_assignable("Y_SEL_Y_VIS_BOOL", (2,), (2,))
  1201. verify_assignable("Y_SEL_M_VIS_BOOL", ( ), (2,)) # Vis. promoted
  1202. verify_assignable("Y_SEL_N_VIS_BOOL", ( ), ( ))
  1203. verify_assignable("Y_SEL_Y_VIS_TRI", (2,), (2,))
  1204. verify_assignable("Y_SEL_M_VIS_TRI", ( ), (2,))
  1205. verify_assignable("Y_SEL_N_VIS_TRI", ( ), ( ))
  1206. # Symbols selected to m
  1207. verify_assignable("M_SEL_Y_VIS_BOOL", (2,), ( 2,)) # Value promoted
  1208. verify_assignable("M_SEL_M_VIS_BOOL", ( ), ( 2,)) # Vis./value promoted
  1209. verify_assignable("M_SEL_N_VIS_BOOL", ( ), ( ))
  1210. verify_assignable("M_SEL_Y_VIS_TRI", (2,), (1, 2 ))
  1211. verify_assignable("M_SEL_M_VIS_TRI", ( ), (1, ))
  1212. verify_assignable("M_SEL_N_VIS_TRI", ( ), ( ))
  1213. # Symbols implied to y
  1214. verify_assignable("Y_IMP_Y_VIS_BOOL", (0, 2), (0, 2))
  1215. verify_assignable("Y_IMP_M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
  1216. verify_assignable("Y_IMP_N_VIS_BOOL", ( ), ( ))
  1217. verify_assignable("Y_IMP_Y_VIS_TRI", (0, 2), (0, 2)) # m removed by imply
  1218. verify_assignable("Y_IMP_M_VIS_TRI", ( ), (0, 2)) # m promoted to y by imply
  1219. verify_assignable("Y_IMP_N_VIS_TRI", ( ), ( ))
  1220. # Symbols implied to m (never affects assignable values)
  1221. verify_assignable("M_IMP_Y_VIS_BOOL", (0, 2), (0, 2))
  1222. verify_assignable("M_IMP_M_VIS_BOOL", ( ), (0, 2)) # Vis. promoted
  1223. verify_assignable("M_IMP_N_VIS_BOOL", ( ), ( ))
  1224. verify_assignable("M_IMP_Y_VIS_TRI", (0, 2), (0, 1, 2))
  1225. verify_assignable("M_IMP_M_VIS_TRI", ( ), (0, 1 ))
  1226. verify_assignable("M_IMP_N_VIS_TRI", ( ), ( ))
  1227. # Symbols in y-mode choice
  1228. verify_assignable("Y_CHOICE_BOOL", (2,), (2,))
  1229. verify_assignable("Y_CHOICE_TRISTATE", (2,), (2,))
  1230. verify_assignable("Y_CHOICE_N_VIS_TRISTATE", ( ), ( ))
  1231. # Symbols in m/y-mode choice, starting out in m mode, or y mode when
  1232. # running without modules
  1233. verify_assignable("MY_CHOICE_BOOL", (2,), ( ))
  1234. verify_assignable("MY_CHOICE_TRISTATE", (2,), (0, 1))
  1235. verify_assignable("MY_CHOICE_N_VIS_TRISTATE", ( ), ( ))
  1236. c.named_choices["MY_CHOICE"].set_value(2)
  1237. # Symbols in m/y-mode choice, now in y mode
  1238. verify_assignable("MY_CHOICE_BOOL", (2,), (2,))
  1239. verify_assignable("MY_CHOICE_TRISTATE", (2,), (2,))
  1240. verify_assignable("MY_CHOICE_N_VIS_TRISTATE", ( ), ( ))
  1241. def verify_choice_assignable(choice_name, assignable_no_modules,
  1242. assignable_modules):
  1243. verify_assignable_imp(c.named_choices[choice_name],
  1244. assignable_no_modules,
  1245. assignable_modules)
  1246. # Choices with various possible modes
  1247. verify_choice_assignable("Y_CHOICE", (2, ), ( 2,))
  1248. verify_choice_assignable("MY_CHOICE", (2, ), ( 1, 2 ))
  1249. verify_choice_assignable("NMY_CHOICE", (0, 2), (0, 1, 2 ))
  1250. verify_choice_assignable("NY_CHOICE", (0, 2), (0, 2 ))
  1251. verify_choice_assignable("NM_CHOICE", ( ), (0, 1 ))
  1252. verify_choice_assignable("M_CHOICE", ( ), ( 1, ))
  1253. verify_choice_assignable("N_CHOICE", ( ), ( ))
  1254. print("Testing object relations")
  1255. c = Kconfig("Kconfiglib/tests/Krelation")
  1256. verify(c.syms["A"].nodes[0].parent is c.top_node,
  1257. "A's parent should be the top node")
  1258. verify(c.syms["B"].nodes[0].parent.item is c.named_choices["CHOICE_1"],
  1259. "B's parent should be the first choice")
  1260. verify(c.syms["C"].nodes[0].parent.item is c.syms["B"],
  1261. "C's parent should be B (due to auto menus)")
  1262. verify(c.syms["E"].nodes[0].parent.item == MENU,
  1263. "E's parent should be a menu")
  1264. verify(c.syms["E"].nodes[0].parent.parent is c.top_node,
  1265. "E's grandparent should be the top node")
  1266. verify(c.syms["G"].nodes[0].parent.item is c.named_choices["CHOICE_2"],
  1267. "G's parent should be the second choice")
  1268. verify(c.syms["G"].nodes[0].parent.parent.item == MENU,
  1269. "G's grandparent should be a menu")
  1270. print("Testing hex/int ranges")
  1271. c = Kconfig("Kconfiglib/tests/Krange", warn=False)
  1272. for sym_name in "HEX_NO_RANGE", "INT_NO_RANGE", "HEX_40", "INT_40":
  1273. sym = c.syms[sym_name]
  1274. verify(not sym.ranges,
  1275. "{} should not have ranges".format(sym_name))
  1276. for sym_name in "HEX_ALL_RANGES_DISABLED", "INT_ALL_RANGES_DISABLED", \
  1277. "HEX_RANGE_10_20_LOW_DEFAULT", \
  1278. "INT_RANGE_10_20_LOW_DEFAULT":
  1279. sym = c.syms[sym_name]
  1280. verify(sym.ranges, "{} should have ranges".format(sym_name))
  1281. # hex/int symbols without defaults should get no default value
  1282. verify_value("HEX_NO_RANGE", "")
  1283. verify_value("INT_NO_RANGE", "")
  1284. # And neither if all ranges are disabled
  1285. verify_value("HEX_ALL_RANGES_DISABLED", "")
  1286. verify_value("INT_ALL_RANGES_DISABLED", "")
  1287. # Make sure they are assignable though, and test that the form of the user
  1288. # value is reflected in the value for hex symbols
  1289. assign_and_verify("HEX_NO_RANGE", "0x123")
  1290. assign_and_verify("HEX_NO_RANGE", "123")
  1291. assign_and_verify("INT_NO_RANGE", "123")
  1292. # Defaults outside of the valid range should be clamped
  1293. verify_value("HEX_RANGE_10_20_LOW_DEFAULT", "0x10")
  1294. verify_value("HEX_RANGE_10_20_HIGH_DEFAULT", "0x20")
  1295. verify_value("INT_RANGE_10_20_LOW_DEFAULT", "10")
  1296. verify_value("INT_RANGE_10_20_HIGH_DEFAULT", "20")
  1297. # Defaults inside the valid range should be preserved. For hex symbols,
  1298. # they should additionally use the same form as in the assignment.
  1299. verify_value("HEX_RANGE_10_20_OK_DEFAULT", "0x15")
  1300. verify_value("HEX_RANGE_10_20_OK_DEFAULT_ALTERNATE", "15")
  1301. verify_value("INT_RANGE_10_20_OK_DEFAULT", "15")
  1302. # hex/int symbols with no defaults but valid ranges should default to the
  1303. # lower end of the range if it's > 0
  1304. verify_value("HEX_RANGE_10_20", "0x10")
  1305. verify_value("HEX_RANGE_0_10", "")
  1306. verify_value("INT_RANGE_10_20", "10")
  1307. verify_value("INT_RANGE_0_10", "")
  1308. verify_value("INT_RANGE_NEG_10_10", "")
  1309. # User values and dependent ranges
  1310. # Avoid warnings for assigning values outside the active range
  1311. c.warn = False
  1312. def verify_range(sym_name, low, high, default):
  1313. # Verifies that all values in the range 'low'-'high' can be assigned,
  1314. # and that assigning values outside the range reverts the value back to
  1315. # 'default' (None if it should revert back to "").
  1316. is_hex = (c.syms[sym_name].type == HEX)
  1317. for i in range(low, high + 1):
  1318. assign_and_verify_user_value(sym_name, str(i), str(i), True)
  1319. if is_hex:
  1320. # The form of the user value should be preserved for hex
  1321. # symbols
  1322. assign_and_verify_user_value(sym_name, hex(i), hex(i), True)
  1323. # Verify that assigning a user value just outside the range causes
  1324. # defaults to be used
  1325. if default is None:
  1326. default_str = ""
  1327. else:
  1328. default_str = hex(default) if is_hex else str(default)
  1329. if is_hex:
  1330. too_low_str = hex(low - 1)
  1331. too_high_str = hex(high + 1)
  1332. else:
  1333. too_low_str = str(low - 1)
  1334. too_high_str = str(high + 1)
  1335. assign_and_verify_value(sym_name, too_low_str, default_str)
  1336. assign_and_verify_value(sym_name, too_high_str, default_str)
  1337. verify_range("HEX_RANGE_10_20_LOW_DEFAULT", 0x10, 0x20, 0x10)
  1338. verify_range("HEX_RANGE_10_20_HIGH_DEFAULT", 0x10, 0x20, 0x20)
  1339. verify_range("HEX_RANGE_10_20_OK_DEFAULT", 0x10, 0x20, 0x15)
  1340. verify_range("INT_RANGE_10_20_LOW_DEFAULT", 10, 20, 10)
  1341. verify_range("INT_RANGE_10_20_HIGH_DEFAULT", 10, 20, 20)
  1342. verify_range("INT_RANGE_10_20_OK_DEFAULT", 10, 20, 15)
  1343. verify_range("HEX_RANGE_10_20", 0x10, 0x20, 0x10)
  1344. verify_range("INT_RANGE_10_20", 10, 20, 10)
  1345. verify_range("INT_RANGE_0_10", 0, 10, None)
  1346. verify_range("INT_RANGE_NEG_10_10", -10, 10, None)
  1347. # Dependent ranges
  1348. verify_value("HEX_40", "40")
  1349. verify_value("INT_40", "40")
  1350. c.syms["HEX_RANGE_10_20"].unset_value()
  1351. c.syms["INT_RANGE_10_20"].unset_value()
  1352. verify_value("HEX_RANGE_10_40_DEPENDENT", "0x10")
  1353. verify_value("INT_RANGE_10_40_DEPENDENT", "10")
  1354. c.syms["HEX_RANGE_10_20"].set_value("15")
  1355. c.syms["INT_RANGE_10_20"].set_value("15")
  1356. verify_value("HEX_RANGE_10_40_DEPENDENT", "0x15")
  1357. verify_value("INT_RANGE_10_40_DEPENDENT", "15")
  1358. c.unset_values()
  1359. verify_range("HEX_RANGE_10_40_DEPENDENT", 0x10, 0x40, 0x10)
  1360. verify_range("INT_RANGE_10_40_DEPENDENT", 10, 40, 10)
  1361. # Ranges and symbols defined in multiple locations
  1362. verify_value("INACTIVE_RANGE", "2")
  1363. verify_value("ACTIVE_RANGE", "1")
  1364. print("Testing defconfig_filename")
  1365. c = Kconfig("Kconfiglib/tests/empty")
  1366. verify(c.defconfig_filename is None,
  1367. "defconfig_filename should be None with no defconfig_list symbol")
  1368. c = Kconfig("Kconfiglib/tests/Kdefconfig_nonexistent")
  1369. verify(c.defconfig_filename is None,
  1370. "defconfig_filename should be None when none of the files in the "
  1371. "defconfig_list symbol exist")
  1372. # Referenced in Kdefconfig_existent(_but_n)
  1373. os.environ["FOO"] = "defconfig_2"
  1374. c = Kconfig("Kconfiglib/tests/Kdefconfig_existent_but_n")
  1375. verify(c.defconfig_filename is None,
  1376. "defconfig_filename should be None when the condition is n for all "
  1377. "the defaults")
  1378. c = Kconfig("Kconfiglib/tests/Kdefconfig_existent")
  1379. verify(c.defconfig_filename == "Kconfiglib/tests/defconfig_2",
  1380. "defconfig_filename should return the existing file "
  1381. "Kconfiglib/tests/defconfig_2")
  1382. # Should also look relative to $srctree if the specified defconfig is a
  1383. # relative path and can't be opened
  1384. c = Kconfig("Kconfiglib/tests/Kdefconfig_srctree")
  1385. verify(c.defconfig_filename == "Kconfiglib/tests/defconfig_2",
  1386. "defconfig_filename gave wrong file with $srctree unset")
  1387. os.environ["srctree"] = "Kconfiglib/tests"
  1388. c = Kconfig("Kdefconfig_srctree")
  1389. verify(c.defconfig_filename == "Kconfiglib/tests/sub/defconfig_in_sub",
  1390. "defconfig_filename gave wrong file with $srctree set")
  1391. os.environ.pop("srctree", None)
  1392. print("Testing mainmenu_text")
  1393. c = Kconfig("Kconfiglib/tests/empty")
  1394. verify(c.mainmenu_text == "Main menu",
  1395. "An empty Kconfig should get a default main menu prompt")
  1396. # Expanded in the mainmenu text
  1397. os.environ["FOO"] = "bar baz"
  1398. c = Kconfig("Kconfiglib/tests/Kmainmenu")
  1399. verify(c.mainmenu_text == "---bar baz---",
  1400. "Wrong mainmenu text")
  1401. print("Testing user_value")
  1402. # References undefined env. var. Disable warnings.
  1403. c = Kconfig("Kconfiglib/tests/Kmisc", warn=False)
  1404. # Avoid warnings from assigning invalid user values and assigning user
  1405. # values to symbols without prompts
  1406. c.warn = False
  1407. syms = [c.syms[name] for name in
  1408. ("BOOL", "TRISTATE", "STRING", "INT", "HEX")]
  1409. for sym in syms:
  1410. verify(sym.user_value is None,
  1411. "{} should not have a user value to begin with")
  1412. # Assign valid values for the types
  1413. assign_and_verify_user_value("BOOL", 0, 0, True)
  1414. assign_and_verify_user_value("BOOL", 2, 2, True)
  1415. assign_and_verify_user_value("TRISTATE", 0, 0, True)
  1416. assign_and_verify_user_value("TRISTATE", 1, 1, True)
  1417. assign_and_verify_user_value("TRISTATE", 2, 2, True)
  1418. assign_and_verify_user_value("STRING", "foo bar", "foo bar", True)
  1419. assign_and_verify_user_value("INT", "123", "123", True)
  1420. assign_and_verify_user_value("HEX", "0x123", "0x123", True)
  1421. # Assign invalid values for the types. They should retain their old user
  1422. # value.
  1423. assign_and_verify_user_value("BOOL", 1, 2, False)
  1424. assign_and_verify_user_value("BOOL", "foo", 2, False)
  1425. assign_and_verify_user_value("BOOL", "1", 2, False)
  1426. assign_and_verify_user_value("TRISTATE", "foo", 2, False)
  1427. assign_and_verify_user_value("TRISTATE", "1", 2, False)
  1428. assign_and_verify_user_value("STRING", 0, "foo bar", False)
  1429. assign_and_verify_user_value("INT", "foo", "123", False)
  1430. assign_and_verify_user_value("INT", 0, "123", False)
  1431. assign_and_verify_user_value("HEX", "foo", "0x123", False)
  1432. assign_and_verify_user_value("HEX", 0, "0x123", False)
  1433. assign_and_verify_user_value("HEX", "-0x1", "0x123", False)
  1434. for s in syms:
  1435. s.unset_value()
  1436. verify(s.user_value is None,
  1437. "{} should not have a user value after being reset".
  1438. format(s.name))
  1439. print("Testing is_menuconfig")
  1440. c = Kconfig("Kconfiglib/tests/Kmenuconfig")
  1441. for not_menuconfig in c.syms["NOT_MENUCONFIG_1"].nodes[0], \
  1442. c.syms["NOT_MENUCONFIG_2"].nodes[0], \
  1443. c.syms["MENUCONFIG_MULTI_DEF"].nodes[0], \
  1444. c.syms["COMMENT_HOOK"].nodes[0].next:
  1445. verify(not not_menuconfig.is_menuconfig,
  1446. "'{}' should have is_menuconfig False".format(not_menuconfig))
  1447. for menuconfig in c.top_node, \
  1448. c.syms["MENUCONFIG_1"].nodes[0], \
  1449. c.syms["MENUCONFIG_MULTI_DEF"].nodes[1], \
  1450. c.syms["MENU_HOOK"].nodes[0].next, \
  1451. c.syms["CHOICE_HOOK"].nodes[0].next:
  1452. verify(menuconfig.is_menuconfig,
  1453. "'{}' should have is_menuconfig True".format(menuconfig))
  1454. print("Testing 'option env' semantics")
  1455. os.environ["ENV_VAR"] = "ENV_VAR value"
  1456. # References undefined env. var., so disable warnings
  1457. c = Kconfig("Kconfiglib/tests/Kmisc", warn=False)
  1458. # Verify that 'option env' is treated like a default
  1459. verify_value("FROM_ENV", "ENV_VAR value")
  1460. verify_value("FROM_ENV_MISSING", "missing")
  1461. verify_value("FROM_ENV_WEIRD", "weird")
  1462. print("Testing defined vs undefined symbols")
  1463. for name in "A", "B", "C", "D", "BOOL", "TRISTATE", "STRING", "INT", "HEX":
  1464. verify(c.syms[name].nodes,
  1465. "{} should be defined".format(name))
  1466. for name in "NOT_DEFINED_1", "NOT_DEFINED_2", "NOT_DEFINED_3", \
  1467. "NOT_DEFINED_4":
  1468. sym = c.syms[name]
  1469. verify(not c.syms[name].nodes,
  1470. "{} should not be defined".format(name))
  1471. print("Testing Symbol.choice")
  1472. for name in "A", "B", "C", "D":
  1473. verify(c.syms[name].choice is not None,
  1474. "{} should be a choice symbol".format(name))
  1475. for name in "Q1", "Q2", "Q3", "BOOL", "TRISTATE", "STRING", "INT", "HEX", \
  1476. "FROM_ENV", "FROM_ENV_MISSING", "NOT_DEFINED_1", \
  1477. "NOT_DEFINED_2", "NOT_DEFINED_3", "NOT_DEFINED_4":
  1478. verify(c.syms[name].choice is None,
  1479. "{} should not be a choice symbol".format(name))
  1480. print("Testing is_allnoconfig_y")
  1481. verify(not c.syms["NOT_ALLNOCONFIG_Y"].is_allnoconfig_y,
  1482. "NOT_ALLNOCONFIG_Y should not be allnoconfig_y")
  1483. verify(c.syms["ALLNOCONFIG_Y"].is_allnoconfig_y,
  1484. "ALLNOCONFIG_Y should be allnoconfig_y")
  1485. print("Testing .config reading and writing")
  1486. config_test_file = "Kconfiglib/tests/config_test"
  1487. def verify_file_contents(fname, contents):
  1488. with open(fname, "r") as f:
  1489. file_contents = f.read()
  1490. verify(file_contents == contents,
  1491. "{} contains '{}'. Expected '{}'."
  1492. .format(fname, file_contents, contents))
  1493. # Writing/reading strings with characters that need to be escaped
  1494. c = Kconfig("Kconfiglib/tests/Kescape")
  1495. # Test the default value
  1496. c.write_config(config_test_file + "_from_def")
  1497. verify_file_contents(config_test_file + "_from_def",
  1498. r'''CONFIG_STRING="\"\\"''' "\n")
  1499. # Write our own value
  1500. c.syms["STRING"].set_value(r'''\"a'\\''')
  1501. c.write_config(config_test_file + "_from_user")
  1502. verify_file_contents(config_test_file + "_from_user",
  1503. r'''CONFIG_STRING="\\\"a'\\\\"''' "\n")
  1504. # Read back the two configs and verify the respective values
  1505. c.load_config(config_test_file + "_from_def")
  1506. verify_value("STRING", '"\\')
  1507. c.load_config(config_test_file + "_from_user")
  1508. verify_value("STRING", r'''\"a'\\''')
  1509. # Appending values from a .config
  1510. c = Kconfig("Kconfiglib/tests/Kappend")
  1511. # Values before assigning
  1512. verify_value("BOOL", "n")
  1513. verify_value("STRING", "")
  1514. # Assign BOOL
  1515. c.load_config("Kconfiglib/tests/config_set_bool", replace=False)
  1516. verify_value("BOOL", "y")
  1517. verify_value("STRING", "")
  1518. # Assign STRING
  1519. c.load_config("Kconfiglib/tests/config_set_string", replace=False)
  1520. verify_value("BOOL", "y")
  1521. verify_value("STRING", "foo bar")
  1522. # Reset BOOL
  1523. c.load_config("Kconfiglib/tests/config_set_string")
  1524. verify_value("BOOL", "n")
  1525. verify_value("STRING", "foo bar")
  1526. # Loading a completely empty .config should reset values
  1527. c.load_config("Kconfiglib/tests/empty")
  1528. verify_value("STRING", "")
  1529. # An indented assignment in a .config should be ignored
  1530. c.load_config("Kconfiglib/tests/config_indented")
  1531. verify_value("IGNOREME", "y")
  1532. # Symbol order in headers and minimal configuration files should match
  1533. # definition order, like in .config files
  1534. c = Kconfig("Kconfiglib/tests/Korder")
  1535. c.write_autoconf(config_test_file)
  1536. verify_file_contents(config_test_file, """
  1537. #define CONFIG_O 0
  1538. #define CONFIG_R 1
  1539. #define CONFIG_D 2
  1540. #define CONFIG_E 3
  1541. #define CONFIG_R2 4
  1542. #define CONFIG_I 5
  1543. #define CONFIG_N 6
  1544. #define CONFIG_G 7
  1545. """[1:])
  1546. # Differs from defaults
  1547. c.syms["O"].set_value("-1")
  1548. c.syms["R"].set_value("-1")
  1549. c.syms["E"].set_value("-1")
  1550. c.syms["R2"].set_value("-1")
  1551. c.syms["N"].set_value("-1")
  1552. c.syms["G"].set_value("-1")
  1553. c.write_min_config(config_test_file)
  1554. verify_file_contents(config_test_file, """
  1555. CONFIG_O=-1
  1556. CONFIG_R=-1
  1557. CONFIG_E=-1
  1558. CONFIG_R2=-1
  1559. CONFIG_N=-1
  1560. CONFIG_G=-1
  1561. """[1:])
  1562. # Test header strings in configuration files and headers
  1563. os.environ["KCONFIG_CONFIG_HEADER"] = "config header from env.\n"
  1564. os.environ["KCONFIG_AUTOHEADER_HEADER"] = "header header from env.\n"
  1565. c = Kconfig("Kconfiglib/tests/Kheader")
  1566. c.write_config(config_test_file, header="config header from param\n")
  1567. verify_file_contents(config_test_file, """\
  1568. config header from param
  1569. CONFIG_FOO=y
  1570. """)
  1571. c.write_min_config(config_test_file, header="min. config header from param\n")
  1572. verify_file_contents(config_test_file, """\
  1573. min. config header from param
  1574. """)
  1575. c.write_config(config_test_file)
  1576. verify_file_contents(config_test_file, """\
  1577. config header from env.
  1578. CONFIG_FOO=y
  1579. """)
  1580. c.write_min_config(config_test_file)
  1581. verify_file_contents(config_test_file, """\
  1582. config header from env.
  1583. """)
  1584. c.write_autoconf(config_test_file, header="header header from param\n")
  1585. verify_file_contents(config_test_file, """\
  1586. header header from param
  1587. #define CONFIG_FOO 1
  1588. """)
  1589. c.write_autoconf(config_test_file)
  1590. verify_file_contents(config_test_file, """\
  1591. header header from env.
  1592. #define CONFIG_FOO 1
  1593. """)
  1594. del os.environ["KCONFIG_CONFIG_HEADER"]
  1595. del os.environ["KCONFIG_AUTOHEADER_HEADER"]
  1596. print("Testing Kconfig fetching and separation")
  1597. for c in Kconfig("Kconfiglib/tests/Kmisc", warn=False), \
  1598. Kconfig("Kconfiglib/tests/Kmisc", warn=False):
  1599. for item in c.syms["BOOL"], \
  1600. c.syms["BOOL"].nodes[0], \
  1601. c.named_choices["OPTIONAL"], \
  1602. c.named_choices["OPTIONAL"].nodes[0], \
  1603. c.syms["MENU_HOOK"].nodes[0].next, \
  1604. c.syms["COMMENT_HOOK"].nodes[0].next:
  1605. verify(item.kconfig is c,
  1606. ".kconfig not properly set for " + repr(item))
  1607. print("Testing imply semantics")
  1608. c = Kconfig("Kconfiglib/tests/Kimply")
  1609. verify_value("IMPLY_DIRECT_DEPS", "y")
  1610. verify_value("UNMET_DIRECT_1", "n")
  1611. verify_value("UNMET_DIRECT_2", "n")
  1612. verify_value("UNMET_DIRECT_3", "n")
  1613. verify_value("MET_DIRECT_1", "y")
  1614. verify_value("MET_DIRECT_2", "y")
  1615. verify_value("MET_DIRECT_3", "y")
  1616. verify_value("MET_DIRECT_4", "y")
  1617. verify_value("IMPLY_COND", "y")
  1618. verify_value("IMPLIED_N_COND", "n")
  1619. verify_value("IMPLIED_M_COND", "m")
  1620. verify_value("IMPLIED_Y_COND", "y")
  1621. verify_value("IMPLY_N_1", "n")
  1622. verify_value("IMPLY_N_2", "n")
  1623. verify_value("IMPLIED_FROM_N_1", "n")
  1624. verify_value("IMPLIED_FROM_N_2", "n")
  1625. verify_value("IMPLY_M", "m")
  1626. verify_value("IMPLIED_M", "m")
  1627. verify_value("IMPLIED_M_BOOL", "y")
  1628. verify_value("IMPLY_M_TO_Y", "y")
  1629. verify_value("IMPLIED_M_TO_Y", "y")
  1630. # Test user value semantics
  1631. # Verify that IMPLIED_TRISTATE is invalidated if the direct
  1632. # dependencies change
  1633. assign_and_verify("IMPLY", 2)
  1634. assign_and_verify("DIRECT_DEP", 2)
  1635. verify_value("IMPLIED_TRISTATE", 2)
  1636. assign_and_verify("DIRECT_DEP", 0)
  1637. verify_value("IMPLIED_TRISTATE", 0)
  1638. # Set back for later tests
  1639. assign_and_verify("DIRECT_DEP", 2)
  1640. # Verify that IMPLIED_TRISTATE can be set to anything when IMPLY has value
  1641. # n, and that it gets the value n by default (for non-imply-related
  1642. # reasons)
  1643. assign_and_verify("IMPLY", 0)
  1644. assign_and_verify("IMPLIED_TRISTATE", 0)
  1645. assign_and_verify("IMPLIED_TRISTATE", 1)
  1646. assign_and_verify("IMPLIED_TRISTATE", 2)
  1647. c.syms["IMPLIED_TRISTATE"].unset_value()
  1648. verify_value("IMPLIED_TRISTATE", "n")
  1649. # Same as above for m. Anything still goes, but m by default now.
  1650. assign_and_verify("IMPLY", 1)
  1651. assign_and_verify("IMPLIED_TRISTATE", 0)
  1652. assign_and_verify("IMPLIED_TRISTATE", 1)
  1653. assign_and_verify("IMPLIED_TRISTATE", 2)
  1654. c.syms["IMPLIED_TRISTATE"].unset_value()
  1655. verify_value("IMPLIED_TRISTATE", 1)
  1656. # Same as above for y. Only n and y should be accepted. m gets promoted to
  1657. # y. Default should be y.
  1658. assign_and_verify("IMPLY", 2)
  1659. assign_and_verify("IMPLIED_TRISTATE", 0)
  1660. assign_and_verify_value("IMPLIED_TRISTATE", 1, 2)
  1661. assign_and_verify("IMPLIED_TRISTATE", 2)
  1662. c.syms["IMPLIED_TRISTATE"].unset_value()
  1663. verify_value("IMPLIED_TRISTATE", 2)
  1664. # Being implied to either m or y should give a bool the value y
  1665. c.syms["IMPLY"].unset_value()
  1666. verify_value("IMPLIED_BOOL", 0)
  1667. assign_and_verify("IMPLY", 0)
  1668. verify_value("IMPLIED_BOOL", 0)
  1669. assign_and_verify("IMPLY", 1)
  1670. verify_value("IMPLIED_BOOL", 2)
  1671. assign_and_verify("IMPLY", 2)
  1672. verify_value("IMPLIED_BOOL", 2)
  1673. # A bool implied to m or y can take the values n and y
  1674. c.syms["IMPLY"].set_value(1)
  1675. assign_and_verify("IMPLIED_BOOL", 0)
  1676. assign_and_verify("IMPLIED_BOOL", 2)
  1677. c.syms["IMPLY"].set_value(2)
  1678. assign_and_verify("IMPLIED_BOOL", 0)
  1679. assign_and_verify("IMPLIED_BOOL", 2)
  1680. print("Testing choice semantics")
  1681. # Would warn for choice value symbols defined without a type, even
  1682. # though the type is automatically derived. This is probably more
  1683. # helpful than ignoring those cases, as this feature isn't used
  1684. # deliberately anywhere from what I've seen.
  1685. c = Kconfig("Kconfiglib/tests/Kchoice", warn=False)
  1686. for name in "BOOL", "BOOL_OPT", "BOOL_M", "DEFAULTS":
  1687. verify(c.named_choices[name].orig_type == BOOL,
  1688. "choice {} should have type bool".format(name))
  1689. for name in "TRISTATE", "TRISTATE_OPT", "TRISTATE_M":
  1690. verify(c.named_choices[name].orig_type == TRISTATE,
  1691. "choice {} should have type tristate".format(name))
  1692. def select_and_verify(sym):
  1693. choice = sym.nodes[0].parent.item
  1694. choice.set_value(2)
  1695. sym.set_value(2)
  1696. verify(sym.choice.selection is sym,
  1697. sym.name + " should be the selected symbol")
  1698. verify(choice.user_selection is sym,
  1699. sym.name + " should be the user selection of the choice")
  1700. verify(sym.tri_value == 2,
  1701. sym.name + " should have value y when selected")
  1702. verify(sym.user_value == 2,
  1703. sym.name + " should have user value y when selected")
  1704. for sibling in choice.syms:
  1705. if sibling is not sym:
  1706. verify(sibling.tri_value == 0,
  1707. sibling.name + " should be n when not selected")
  1708. def select_and_verify_all(choice_name):
  1709. choice = c.named_choices[choice_name]
  1710. # Select in forward order
  1711. for sym in choice.syms:
  1712. select_and_verify(sym)
  1713. # Select in reverse order
  1714. for sym in reversed(choice.syms):
  1715. select_and_verify(sym)
  1716. def verify_mode(choice_name, no_modules_mode, modules_mode):
  1717. choice = c.named_choices[choice_name]
  1718. c.modules.set_value(0)
  1719. verify(choice.tri_value == no_modules_mode,
  1720. 'Wrong mode for choice {} with no modules. Expected {}, got {}.'
  1721. .format(choice.name, no_modules_mode, choice.tri_value))
  1722. c.modules.set_value(2)
  1723. verify(choice.tri_value == modules_mode,
  1724. 'Wrong mode for choice {} with modules. Expected {}, got {}.'
  1725. .format(choice.name, modules_mode, choice.tri_value))
  1726. verify_mode("BOOL", 2, 2)
  1727. verify_mode("BOOL_OPT", 0, 0)
  1728. verify_mode("TRISTATE", 2, 1)
  1729. verify_mode("TRISTATE_OPT", 0, 0)
  1730. verify_mode("BOOL_M", 0, 2)
  1731. verify_mode("TRISTATE_M", 0, 1)
  1732. # Test defaults
  1733. choice = c.named_choices["DEFAULTS"]
  1734. c.syms["TRISTATE_SYM"].set_value(0)
  1735. verify(choice.selection is c.syms["OPT_4"],
  1736. "Wrong choice default with TRISTATE_SYM = n")
  1737. c.syms["TRISTATE_SYM"].set_value(2)
  1738. verify(choice.selection is c.syms["OPT_2"],
  1739. "Wrong choice default with TRISTATE_SYM = y")
  1740. c.syms["OPT_1"].set_value(2)
  1741. verify(choice.selection is c.syms["OPT_1"],
  1742. "User selection should override defaults")
  1743. verify(c.named_choices["DEFAULTS_NOT_VISIBLE"].selection
  1744. is c.syms["OPT_8"],
  1745. "Non-visible choice symbols should cause the next default to be "
  1746. "considered")
  1747. # Test y mode selection
  1748. c.modules.set_value(2)
  1749. select_and_verify_all("BOOL")
  1750. select_and_verify_all("BOOL_OPT")
  1751. select_and_verify_all("TRISTATE")
  1752. select_and_verify_all("TRISTATE_OPT")
  1753. # For BOOL_M, the mode should have been promoted
  1754. select_and_verify_all("BOOL_M")
  1755. # Test m mode selection
  1756. c.named_choices["TRISTATE"].set_value(1)
  1757. verify(c.named_choices["TRISTATE"].tri_value == 1,
  1758. "TRISTATE choice should have mode m after explicit mode assignment")
  1759. assign_and_verify_value("T_1", 0, 0)
  1760. assign_and_verify_value("T_2", 0, 0)
  1761. assign_and_verify_value("T_1", 1, 1)
  1762. assign_and_verify_value("T_2", 1, 1)
  1763. assign_and_verify_value("T_1", 2, 1)
  1764. assign_and_verify_value("T_2", 2, 1)
  1765. # Switching to y mode should cause T_2 to become selected
  1766. c.named_choices["TRISTATE"].set_value(2)
  1767. verify_value("T_1", 0)
  1768. verify_value("T_2", 2)
  1769. # Verify that choices with no explicitly specified type get the type of the
  1770. # first contained symbol with a type
  1771. verify(c.named_choices["NO_TYPE_BOOL"].orig_type == BOOL,
  1772. "Expected first choice without explicit type to have type bool")
  1773. verify(c.named_choices["NO_TYPE_TRISTATE"].orig_type == TRISTATE,
  1774. "Expected second choice without explicit type to have type "
  1775. "tristate")
  1776. # Verify that symbols without a type in the choice get the type of the
  1777. # choice
  1778. for name in "MMT_1", "MMT_2", "MMT_4", "MMT_5":
  1779. verify(c.syms[name].orig_type == BOOL,
  1780. "Expected {} to get type bool".format(name))
  1781. verify(c.syms["MMT_3"].orig_type == TRISTATE,
  1782. "Expected MMT_3 to have type tristate")
  1783. # Verify that the default selection can change depending on the
  1784. # visibility of the choice symbols
  1785. default_with_dep_choice = c.named_choices["DEFAULT_WITH_DEP"]
  1786. verify(default_with_dep_choice.selection is c.syms["B"],
  1787. "Wrong choice default with unsatisfied deps on default")
  1788. c.syms["DEP"].set_value("y")
  1789. verify(default_with_dep_choice.selection is c.syms["A"],
  1790. "Wrong choice default with satisfied deps on default")
  1791. c.syms["DEP"].set_value("n")
  1792. verify(default_with_dep_choice.selection is c.syms["B"],
  1793. "Wrong choice default with unsatisfied deps on default (round two)")
  1794. # Verify that symbols in choices that depend on the preceding symbol aren't
  1795. # considered choice symbols
  1796. weird_choice = c.named_choices["WEIRD_SYMS"]
  1797. def verify_is_normal_choice_symbol(name):
  1798. sym = c.syms[name]
  1799. verify(sym.choice is not None and
  1800. sym in weird_choice.syms and
  1801. sym.nodes[0].parent.item is weird_choice,
  1802. "{} should be a normal choice symbol".format(sym.name))
  1803. def verify_is_weird_choice_symbol(name):
  1804. sym = c.syms[name]
  1805. verify(sym.choice is None and
  1806. sym not in weird_choice.syms,
  1807. "{} should be a weird (non-)choice symbol"
  1808. .format(sym.name))
  1809. verify_is_normal_choice_symbol("WS1")
  1810. verify_is_weird_choice_symbol("WS2")
  1811. verify_is_weird_choice_symbol("WS3")
  1812. verify_is_weird_choice_symbol("WS4")
  1813. verify_is_weird_choice_symbol("WS5")
  1814. verify_is_normal_choice_symbol("WS6")
  1815. verify_is_weird_choice_symbol("WS7")
  1816. verify_is_weird_choice_symbol("WS8")
  1817. verify_is_normal_choice_symbol("WS9")
  1818. print("Testing 'if' node removal")
  1819. c = Kconfig("Kconfiglib/tests/Kifremoval", warn=False)
  1820. nodes = tuple(c.node_iter())
  1821. verify_equal(nodes[0].item.name, "A")
  1822. verify_equal(nodes[1].item.name, "B")
  1823. verify_equal(nodes[2].item.name, "C")
  1824. verify_equal(nodes[3].item.name, "D")
  1825. verify_equal(nodes[4].prompt[0], "E")
  1826. verify_equal(nodes[5].prompt[0], "F")
  1827. verify_equal(nodes[6].prompt[0], "G")
  1828. verify_equal(nodes[7].item.name, "H")
  1829. verify_equal(nodes[8].item.name, "I")
  1830. verify_equal(nodes[9].item.name, "J")
  1831. verify(len(nodes) == 10,
  1832. "Wrong number of nodes after 'if' removal")
  1833. print("Testing multi.def. property copying")
  1834. c = Kconfig("Kconfiglib/tests/Kdepcopy", warn=False)
  1835. def verify_props(desc, props, prop_names):
  1836. actual = [prop[0].name for prop in props]
  1837. expected = prop_names.split()
  1838. verify(actual == expected,
  1839. "Wrong {} properties, expected '{}', got '{}'"
  1840. .format(desc, expected, actual))
  1841. verify_props("default", c.syms["MULTIDEF"].defaults,
  1842. "A B C D E F G H I J K L M N O P Q R")
  1843. verify_props("select", c.syms["MULTIDEF"].selects,
  1844. "AA BB CC DD EE FF GG HH II JJ")
  1845. verify_props("imply", c.syms["MULTIDEF"].selects,
  1846. "AA BB CC DD EE FF GG HH II JJ")
  1847. verify_props("select", c.syms["MULTIDEF_CHOICE"].selects,
  1848. "A B C")
  1849. verify_props("range", c.syms["MULTIDEF_RANGE"].ranges,
  1850. "A B C D E F")
  1851. verify_props("default", c.choices[1].defaults,
  1852. "A B C D E")
  1853. print("Testing dependency loop detection")
  1854. # These are all expected to raise dependency loop errors
  1855. for i in range(11):
  1856. filename = "Kconfiglib/tests/Kdeploop" + str(i)
  1857. try:
  1858. Kconfig(filename)
  1859. except KconfigError as e:
  1860. if "Dependency loop" not in str(e):
  1861. fail("dependency loop in {} raised wrong KconfigError"
  1862. .format(filename))
  1863. except:
  1864. fail("dependency loop in {} raised wrong exception"
  1865. .format(filename))
  1866. else:
  1867. fail("dependency loop in {} not detected".format(filename))
  1868. # Check the most complicated message completely
  1869. try:
  1870. Kconfig("Kconfiglib/tests/Kdeploop10")
  1871. except KconfigError as e:
  1872. verify_equal(str(e), """
  1873. Dependency loop
  1874. ===============
  1875. A (defined at Kconfiglib/tests/Kdeploop10:1), with definition...
  1876. config A
  1877. bool
  1878. depends on B
  1879. ...depends on B (defined at Kconfiglib/tests/Kdeploop10:5), with definition...
  1880. config B
  1881. bool
  1882. depends on C = 7
  1883. ...depends on C (defined at Kconfiglib/tests/Kdeploop10:9), with definition...
  1884. config C
  1885. int
  1886. range D 8
  1887. ...depends on D (defined at Kconfiglib/tests/Kdeploop10:13), with definition...
  1888. config D
  1889. int
  1890. default 3 if E
  1891. default 8
  1892. ...depends on E (defined at Kconfiglib/tests/Kdeploop10:18), with definition...
  1893. config E
  1894. bool
  1895. (select-related dependencies: F && G)
  1896. ...depends on G (defined at Kconfiglib/tests/Kdeploop10:25), with definition...
  1897. config G
  1898. bool
  1899. depends on H
  1900. ...depends on the choice symbol H (defined at Kconfiglib/tests/Kdeploop10:32), with definition...
  1901. config H
  1902. bool "H"
  1903. depends on I && <choice>
  1904. ...depends on the choice symbol I (defined at Kconfiglib/tests/Kdeploop10:41), with definition...
  1905. config I
  1906. bool "I"
  1907. depends on <choice>
  1908. ...depends on <choice> (defined at Kconfiglib/tests/Kdeploop10:38), with definition...
  1909. choice
  1910. bool "choice" if J
  1911. ...depends on J (defined at Kconfiglib/tests/Kdeploop10:46), with definition...
  1912. config J
  1913. bool
  1914. depends on A
  1915. ...depends again on A (defined at Kconfiglib/tests/Kdeploop10:1)
  1916. """[:-1])
  1917. except:
  1918. fail("Loop detection message check raised wrong exception")
  1919. else:
  1920. fail("Loop detection message check did not raise exception")
  1921. print("Testing preprocessor")
  1922. os.environ["ENV_1"] = "env_1"
  1923. os.environ["ENV_2"] = "env_2"
  1924. os.environ["ENV_3"] = "env_3"
  1925. os.environ["ENV_4"] = "env_4"
  1926. os.environ["ENV_5"] = "n"
  1927. os.environ["ENV_6"] = "Kconfiglib/tests/empty"
  1928. os.environ["ENV_7"] = "env_7"
  1929. # We verify warnings manually
  1930. c = Kconfig("Kconfiglib/tests/Kpreprocess", warn_to_stderr=False)
  1931. def verify_variable(name, unexp_value, exp_value, recursive, *args):
  1932. var = c.variables[name]
  1933. verify(var.value == unexp_value,
  1934. "expected variable '{}' to have the unexpanded value '{}', had "
  1935. "the value '{}'".format(name, unexp_value, var.value))
  1936. if not args:
  1937. verify(var.expanded_value == exp_value,
  1938. "expected expanded_value for {} to be '{}', was '{}'"
  1939. .format(name, exp_value, var.expanded_value))
  1940. verify(var.expanded_value_w_args(*args) == exp_value,
  1941. "expected expanded_value_w_args() for '{}' to be '{}', was '{}'"
  1942. .format(name, exp_value, var.expanded_value_w_args(*args)))
  1943. verify(var.is_recursive == recursive,
  1944. "{} was {}, shouldn't be"
  1945. .format(name, "recursive" if var.is_recursive else "simple"))
  1946. verify_variable("simple-recursive", "foo", "foo", True)
  1947. verify_variable("simple-immediate", "bar", "bar", False)
  1948. verify_variable("simple-recursive-2", "baz", "baz", True)
  1949. verify_variable("whitespaced", "foo", "foo", True)
  1950. verify_variable("preserve-recursive", "foo bar", "foo bar", True)
  1951. verify_variable("preserve-immediate", "foo bar", "foo bar", False)
  1952. verify_variable("recursive",
  1953. "$(foo) $(bar) $($(b-char)a$(z-char)) $(indir)",
  1954. "abc def ghi jkl mno",
  1955. True)
  1956. verify_variable("immediate", "foofoo", "foofoo", False)
  1957. verify_variable("messy-fn-res",
  1958. "$($(fn-indir)-unused-arg, a b (,) , c d )",
  1959. 'surround-rev-quote " c d " " a b (,) " surround-rev-quote ',
  1960. True)
  1961. verify_variable("special-chars-fn-res",
  1962. "$(fn,$(comma)$(dollar)$(left-paren)foo$(right-paren))",
  1963. '",$(foo)"',
  1964. True)
  1965. verify_variable("quote", '"$(1)" "$(2)"', '"" ""', True)
  1966. verify_variable("quote", '"$(1)" "$(2)"', '"one" ""', True,
  1967. "one")
  1968. verify_variable("quote", '"$(1)" "$(2)"', '"one" "two"', True,
  1969. "one", "two")
  1970. verify_variable("quote", '"$(1)" "$(2)"', '"one" "two"', True,
  1971. "one", "two", "three")
  1972. verify_str(c.syms["PRINT_ME"], r"""
  1973. config PRINT_ME
  1974. string "env_1" if (FOO && BAR) || !BAZ || !QAZ
  1975. default "\"foo\"" if "foo \"bar\" baz" = ""
  1976. """)
  1977. verify_str(c.syms["PRINT_ME_TOO"], r"""
  1978. config PRINT_ME_TOO
  1979. bool "foo"
  1980. default FOOBARBAZQAZ if QAZ && QAZFOO && xxx
  1981. """)
  1982. def verify_repr(name, s):
  1983. verify_equal(repr(c.variables[name]), s)
  1984. verify_repr(
  1985. "simple-immediate",
  1986. "<variable simple-immediate, immediate, value 'bar'>")
  1987. verify_repr(
  1988. "messy-fn-res",
  1989. "<variable messy-fn-res, recursive, value '$($(fn-indir)-unused-arg, a b (,) , c d )'>")
  1990. def verify_recursive(name):
  1991. try:
  1992. c.variables[name].expanded_value
  1993. except KconfigError:
  1994. pass
  1995. else:
  1996. fail("Expected '{}' expansion to flag recursive expansion, didn't"
  1997. .format(name))
  1998. verify_recursive("rec-1")
  1999. # Indirectly verifies that it's not recursive
  2000. verify_variable("safe-fn-rec-res",
  2001. "$(safe-fn-rec,safe-fn-rec-2)",
  2002. "foo",
  2003. True)
  2004. verify_recursive("unsafe-fn-rec")
  2005. verify_variable("foo-bar-baz", "$(rhs)", "value", True)
  2006. verify_variable("space-var-res", "$(foo bar)", "value", True)
  2007. verify_variable("shell-res",
  2008. "$(shell,false && echo foo bar || echo baz qaz)",
  2009. "baz qaz",
  2010. True)
  2011. verify_variable("shell-stderr-res", "", "", False)
  2012. verify_variable("parens-res",
  2013. "pre-$(shell,echo '(a,$(b-char),(c,d),e)')-post",
  2014. "pre-(a,b,(c,d),e)-post",
  2015. True)
  2016. verify_variable("location-res",
  2017. "Kconfiglib/tests/Kpreprocess:129",
  2018. "Kconfiglib/tests/Kpreprocess:129",
  2019. False)
  2020. verify_variable("warning-res", "", "", False)
  2021. verify_variable("error-n-res", "", "", False)
  2022. try:
  2023. c.variables["error-y-res"].expanded_value
  2024. except KconfigError:
  2025. pass
  2026. else:
  2027. fail("expanding error-y-res didn't raise an exception")
  2028. # Check Kconfig.env_vars
  2029. verify_equal(c.env_vars,
  2030. set(("ENV_1", "ENV_2", "ENV_3", "ENV_4", "ENV_5", "ENV_6")))
  2031. # Check that the expected warnings were generated
  2032. verify_equal(c.warnings, [
  2033. "Kconfiglib/tests/Kpreprocess:122: warning: 'echo message on stderr >&2' wrote to stderr: message on stderr",
  2034. "Kconfiglib/tests/Kpreprocess:134: warning: a warning"
  2035. ])
  2036. print("Testing user-defined preprocessor functions")
  2037. # Make Kconfiglib/tests/kconfigfunctions.py importable
  2038. sys.path.insert(0, "Kconfiglib/tests")
  2039. c = Kconfig("Kconfiglib/tests/Kuserfunctions")
  2040. verify_variable("add-zero", "$(add)", "0", True)
  2041. verify_variable("add-one", "$(add,1)", "1", True)
  2042. verify_variable("add-three", "$(add,1,-1,2,1)", "3", True)
  2043. verify_variable("one-one", "$(one,foo bar)", "onefoo barfoo bar", True)
  2044. verify_variable("one-or-more-one", "$(one-or-more,foo)", "foo + ", True)
  2045. verify_variable("one-or-more-three", "$(one-or-more,foo,bar,baz)",
  2046. "foo + bar,baz", True)
  2047. verify_variable("location-1", "Kconfiglib/tests/Kuserfunctions:13",
  2048. "Kconfiglib/tests/Kuserfunctions:13", False)
  2049. verify_variable("location-2", "Kconfiglib/tests/Kuserfunctions:14",
  2050. "Kconfiglib/tests/Kuserfunctions:14", False)
  2051. def verify_bad_argno(name):
  2052. try:
  2053. c.variables[name].expanded_value
  2054. except KconfigError:
  2055. pass
  2056. else:
  2057. fail("Expected '{}' expansion to flag wrong number of arguments, "
  2058. "didn't".format(name))
  2059. verify_bad_argno("one-zero")
  2060. verify_bad_argno("one-two")
  2061. verify_bad_argno("one-or-more-zero")
  2062. sys.path.pop(0)
  2063. # This test can fail on older Python 3.x versions, because they don't
  2064. # preserve dict insertion order during iteration. The output is still
  2065. # correct, just different.
  2066. if not (3, 0) <= sys.version_info <= (3, 5):
  2067. print("Testing KCONFIG_WARN_UNDEF")
  2068. os.environ["KCONFIG_WARN_UNDEF"] = "y"
  2069. c = Kconfig("Kconfiglib/tests/Kundef", warn_to_stderr=False)
  2070. verify_equal("\n".join(c.warnings), """
  2071. warning: the int symbol INT (defined at Kconfiglib/tests/Kundef:8) has a non-int range [UNDEF_2 (undefined), 8 (undefined)]
  2072. warning: undefined symbol UNDEF_1:
  2073. - Referenced at Kconfiglib/tests/Kundef:4:
  2074. config BOOL
  2075. bool "foo" if DEF || !UNDEF_1
  2076. default UNDEF_2
  2077. - Referenced at Kconfiglib/tests/Kundef:19:
  2078. menu "menu"
  2079. depends on UNDEF_1
  2080. visible if UNDEF_3
  2081. warning: undefined symbol UNDEF_2:
  2082. - Referenced at Kconfiglib/tests/Kundef:4:
  2083. config BOOL
  2084. bool "foo" if DEF || !UNDEF_1
  2085. default UNDEF_2
  2086. - Referenced at Kconfiglib/tests/Kundef:8:
  2087. config INT
  2088. int
  2089. range UNDEF_2 8
  2090. range 5 15
  2091. default 10
  2092. warning: undefined symbol UNDEF_3:
  2093. - Referenced at Kconfiglib/tests/Kundef:19:
  2094. menu "menu"
  2095. depends on UNDEF_1
  2096. visible if UNDEF_3
  2097. """[1:-1])
  2098. os.environ.pop("KCONFIG_WARN_UNDEF")
  2099. print("\nAll selftests passed\n" if all_passed else
  2100. "\nSome selftests failed\n")
  2101. def run_compatibility_tests():
  2102. # Runs tests on configurations from the kernel. Tests compability with the
  2103. # C implementation by comparing outputs.
  2104. # Referenced inside the kernel Kconfig files.
  2105. #
  2106. # The str() makes the type of the value 'str' on both Python 2 and Python 3,
  2107. # which is nice for some later dictionary key sanity checks.
  2108. os.environ["KERNELVERSION"] = str(
  2109. subprocess.check_output("make kernelversion", shell=True)
  2110. .decode("utf-8").rstrip()
  2111. )
  2112. os.environ["CC_VERSION_TEXT"] = str(
  2113. subprocess.check_output("gcc --version | head -n1", shell=True)
  2114. .decode("utf-8").rstrip()
  2115. )
  2116. os.environ["srctree"] = "."
  2117. os.environ["CC"] = "gcc"
  2118. os.environ["LD"] = "ld"
  2119. if not os.path.exists("scripts/kconfig/conf"):
  2120. print("\nscripts/kconfig/conf does not exist -- running "
  2121. "'make allnoconfig' to build it...")
  2122. shell("make allnoconfig")
  2123. print("Running compatibility tests...\n")
  2124. test_fns = (test_defconfig,
  2125. # Fails for a few defconfigs due to a bug in the C tools. Will
  2126. # be enabled once patches get in.
  2127. #test_min_config,
  2128. test_alldefconfig,
  2129. test_allnoconfig,
  2130. test_allnoconfig_walk,
  2131. test_allmodconfig,
  2132. test_allyesconfig,
  2133. test_sanity)
  2134. for test_fn in test_fns:
  2135. # The test description is taken from the docstring of the corresponding
  2136. # function
  2137. print(textwrap.dedent(test_fn.__doc__))
  2138. for arch, srcarch in all_arch_srcarch():
  2139. # Referenced inside the Kconfig files
  2140. os.environ["ARCH"] = arch
  2141. os.environ["SRCARCH"] = srcarch
  2142. rm_configs()
  2143. test_fn(arch, srcarch)
  2144. if all_passed:
  2145. print("All selftests and compatibility tests passed")
  2146. else:
  2147. sys.exit("Some tests failed")
  2148. def all_arch_srcarch():
  2149. for srcarch in os.listdir("arch"):
  2150. # arc and h8300 are currently broken with the C tools on linux-next as
  2151. # well. Perhaps they require cross-compilers to be installed.
  2152. #
  2153. # User-mode Linux has an unorthodox Kconfig setup that would require a
  2154. # different testing setup. Skip it too.
  2155. if srcarch in ("arc", "h8300", "um"):
  2156. continue
  2157. if os.path.exists(os.path.join("arch", srcarch, "Kconfig")):
  2158. yield (srcarch, srcarch)
  2159. # Some arches define additional ARCH settings with ARCH != SRCARCH
  2160. # (search for "Additional ARCH settings for" in the top-level Makefile)
  2161. yield ("i386", "x86")
  2162. yield ("x86_64", "x86")
  2163. yield ("sparc32", "sparc")
  2164. yield ("sparc64", "sparc")
  2165. yield ("sh64", "sh")
  2166. def test_allnoconfig(arch, srcarch):
  2167. """
  2168. Verify that allnoconfig.py generates the same .config as
  2169. 'make allnoconfig', for each architecture. Runs the script via
  2170. 'make scriptconfig'.
  2171. """
  2172. shell("make scriptconfig SCRIPT=Kconfiglib/allnoconfig.py "
  2173. "PYTHONCMD='{}'".format(sys.executable))
  2174. shell("mv .config ._config")
  2175. shell("scripts/kconfig/conf --allnoconfig Kconfig")
  2176. compare_configs(arch)
  2177. def test_allnoconfig_walk(arch, srcarch):
  2178. """
  2179. Verify that examples/allnoconfig_walk.py generates the same .config as
  2180. 'make allnoconfig', for each architecture. Runs the script via
  2181. 'make scriptconfig'.
  2182. """
  2183. shell("make scriptconfig SCRIPT=Kconfiglib/examples/allnoconfig_walk.py "
  2184. "PYTHONCMD='{}'".format(sys.executable))
  2185. shell("mv .config ._config")
  2186. shell("scripts/kconfig/conf --allnoconfig Kconfig")
  2187. compare_configs(arch)
  2188. def test_allmodconfig(arch, srcarch):
  2189. """
  2190. Verify that allmodconfig.py generates the same .config as
  2191. 'make allmodconfig', for each architecture. Runs the script via
  2192. 'make scriptconfig'.
  2193. """
  2194. shell("make scriptconfig SCRIPT=Kconfiglib/allmodconfig.py "
  2195. "PYTHONCMD='{}'".format(sys.executable))
  2196. shell("mv .config ._config")
  2197. shell("scripts/kconfig/conf --allmodconfig Kconfig")
  2198. compare_configs(arch)
  2199. def test_allyesconfig(arch, srcarch):
  2200. """
  2201. Verify that allyesconfig.py generates the same .config as
  2202. 'make allyesconfig', for each architecture. Runs the script via
  2203. 'make scriptconfig'.
  2204. """
  2205. shell("make scriptconfig SCRIPT=Kconfiglib/allyesconfig.py "
  2206. "PYTHONCMD='{}'".format(sys.executable))
  2207. shell("mv .config ._config")
  2208. shell("scripts/kconfig/conf --allyesconfig Kconfig")
  2209. compare_configs(arch)
  2210. def test_sanity(arch, srcarch):
  2211. """
  2212. Do sanity checks on each configuration and call all public methods on all
  2213. symbols, choices, and menu nodes for all architectures to make sure we
  2214. never crash or hang.
  2215. """
  2216. print("For {}...".format(arch))
  2217. kconf = Kconfig()
  2218. for sym in kconf.defined_syms:
  2219. verify(sym._visited == 2,
  2220. "{} has broken dependency loop detection (_visited = {})"
  2221. .format(sym.name, sym._visited))
  2222. kconf.modules
  2223. kconf.defconfig_list
  2224. kconf.defconfig_filename
  2225. # Legacy warning functions
  2226. kconf.enable_redun_warnings()
  2227. kconf.disable_redun_warnings()
  2228. kconf.enable_undef_warnings()
  2229. kconf.disable_undef_warnings()
  2230. kconf.enable_warnings()
  2231. kconf.disable_warnings()
  2232. kconf.enable_stderr_warnings()
  2233. kconf.disable_stderr_warnings()
  2234. kconf.mainmenu_text
  2235. kconf.unset_values()
  2236. kconf.write_autoconf("/dev/null")
  2237. # No tempfile.TemporaryDirectory in Python 2
  2238. tmpdir = tempfile.mkdtemp()
  2239. kconf.sync_deps(os.path.join(tmpdir, "deps")) # Create
  2240. kconf.sync_deps(os.path.join(tmpdir, "deps")) # Update
  2241. shutil.rmtree(tmpdir)
  2242. # Python 2/3 compatible
  2243. for key, sym in kconf.syms.items():
  2244. verify(isinstance(key, str), "weird key '{}' in syms dict".format(key))
  2245. verify(not sym.is_constant, sym.name + " in 'syms' and constant")
  2246. verify(sym not in kconf.const_syms,
  2247. sym.name + " in both 'syms' and 'const_syms'")
  2248. for dep in sym._dependents:
  2249. verify(not dep.is_constant,
  2250. "the constant symbol {} depends on {}"
  2251. .format(dep.name, sym.name))
  2252. sym.__repr__()
  2253. sym.__str__()
  2254. sym.assignable
  2255. kconf.disable_warnings()
  2256. sym.set_value(2)
  2257. sym.set_value("foo")
  2258. sym.unset_value()
  2259. kconf.enable_warnings() # Legacy warning function
  2260. sym.str_value
  2261. sym.tri_value
  2262. sym.type
  2263. sym.user_value
  2264. sym.visibility
  2265. for sym in kconf.defined_syms:
  2266. verify(sym.nodes, sym.name + " is defined but lacks menu nodes")
  2267. verify(not (sym.orig_type not in (BOOL, TRISTATE) and sym.choice),
  2268. sym.name + " is a choice symbol but not bool/tristate")
  2269. for key, sym in kconf.const_syms.items():
  2270. verify(isinstance(key, str),
  2271. "weird key '{}' in const_syms dict".format(key))
  2272. verify(sym.is_constant,
  2273. '"{}" is in const_syms but not marked constant'
  2274. .format(sym.name))
  2275. verify(not sym.nodes,
  2276. '"{}" is constant but has menu nodes'.format(sym.name))
  2277. verify(not sym._dependents,
  2278. '"{}" is constant but is a dependency of some symbol'
  2279. .format(sym.name))
  2280. verify(not sym.choice,
  2281. '"{}" is constant and a choice symbol'.format(sym.name))
  2282. sym.__repr__()
  2283. sym.__str__()
  2284. sym.assignable
  2285. kconf.disable_warnings()
  2286. sym.set_value(2)
  2287. sym.set_value("foo")
  2288. sym.unset_value()
  2289. kconf.enable_warnings() # Legacy warning function
  2290. sym.str_value
  2291. sym.tri_value
  2292. sym.type
  2293. sym.visibility
  2294. for choice in kconf.choices:
  2295. for sym in choice.syms:
  2296. verify(sym.choice is choice,
  2297. "{0} is in choice.syms but 'sym.choice' is not the choice"
  2298. .format(sym.name))
  2299. verify(sym.type in (BOOL, TRISTATE),
  2300. "{} is a choice symbol but is not a bool/tristate"
  2301. .format(sym.name))
  2302. choice.__str__()
  2303. choice.__repr__()
  2304. choice.str_value
  2305. choice.tri_value
  2306. choice.user_value
  2307. choice.assignable
  2308. choice.selection
  2309. choice.type
  2310. choice.visibility
  2311. # Menu nodes
  2312. node = kconf.top_node
  2313. while 1:
  2314. # Everything else should be well exercised elsewhere
  2315. node.__repr__()
  2316. node.__str__()
  2317. verify(isinstance(node.item, (Symbol, Choice)) or \
  2318. node.item in (MENU, COMMENT),
  2319. "'{}' appeared as a menu item".format(node.item))
  2320. if node.list is not None:
  2321. node = node.list
  2322. elif node.next is not None:
  2323. node = node.next
  2324. else:
  2325. while node.parent is not None:
  2326. node = node.parent
  2327. if node.next is not None:
  2328. node = node.next
  2329. break
  2330. else:
  2331. break
  2332. def test_alldefconfig(arch, srcarch):
  2333. """
  2334. Verify that alldefconfig.py generates the same .config as
  2335. 'make alldefconfig', for each architecture. Runs the script via
  2336. 'make scriptconfig'.
  2337. """
  2338. shell("make scriptconfig SCRIPT=Kconfiglib/alldefconfig.py "
  2339. "PYTHONCMD='{}'".format(sys.executable))
  2340. shell("mv .config ._config")
  2341. shell("scripts/kconfig/conf --alldefconfig Kconfig")
  2342. compare_configs(arch)
  2343. def test_defconfig(arch, srcarch):
  2344. """
  2345. Verify that Kconfiglib generates the same .config as scripts/kconfig/conf,
  2346. for each architecture/defconfig pair. In obsessive mode, this test includes
  2347. nonsensical groupings of arches with defconfigs from other arches (every
  2348. arch/defconfig combination) and takes an order of magnitude longer time to
  2349. run.
  2350. With logging enabled, this test appends any failures to a file
  2351. test_defconfig_fails in the root.
  2352. """
  2353. kconf = Kconfig()
  2354. if obsessive:
  2355. defconfigs = []
  2356. # Collect all defconfigs. This could be done once instead, but it's
  2357. # a speedy operation comparatively.
  2358. for srcarch_ in os.listdir("arch"):
  2359. defconfigs.extend(defconfig_files(srcarch_))
  2360. else:
  2361. defconfigs = defconfig_files(srcarch)
  2362. # Test architecture for each defconfig
  2363. for defconfig in defconfigs:
  2364. rm_configs()
  2365. kconf.load_config(defconfig)
  2366. kconf.write_config("._config")
  2367. shell("scripts/kconfig/conf --defconfig='{}' Kconfig".
  2368. format(defconfig))
  2369. arch_defconfig_str = " {:14}with {:60} ".format(arch, defconfig)
  2370. if equal_configs():
  2371. print(arch_defconfig_str + "OK")
  2372. else:
  2373. print(arch_defconfig_str + "FAIL")
  2374. fail()
  2375. if log:
  2376. with open("test_defconfig_fails", "a") as fail_log:
  2377. fail_log.write("{} with {} did not match\n"
  2378. .format(arch, defconfig))
  2379. def test_min_config(arch, srcarch):
  2380. """
  2381. Verify that Kconfiglib generates the same .config as 'make savedefconfig'
  2382. for each architecture/defconfig pair.
  2383. """
  2384. kconf = Kconfig()
  2385. if obsessive_min_config:
  2386. defconfigs = []
  2387. for srcarch_ in os.listdir("arch"):
  2388. defconfigs.extend(defconfig_files(srcarch_))
  2389. else:
  2390. defconfigs = defconfig_files(srcarch)
  2391. for defconfig in defconfigs:
  2392. rm_configs()
  2393. kconf.load_config(defconfig)
  2394. kconf.write_min_config("._config")
  2395. shell("cp {} .config".format(defconfig))
  2396. shell("scripts/kconfig/conf --savedefconfig=.config Kconfig")
  2397. arch_defconfig_str = " {:14}with {:60} ".format(arch, defconfig)
  2398. if equal_configs():
  2399. print(arch_defconfig_str + "OK")
  2400. else:
  2401. print(arch_defconfig_str + "FAIL")
  2402. #
  2403. # Helper functions
  2404. #
  2405. def defconfig_files(srcarch):
  2406. # Yields a list of defconfig file filenames for a particular srcarch
  2407. # subdirectory (arch/<srcarch>/)
  2408. srcarch_dir = os.path.join("arch", srcarch)
  2409. # Some arches have a defconfig in the root of their arch/<arch>/ directory
  2410. root_defconfig = os.path.join(srcarch_dir, "defconfig")
  2411. if os.path.exists(root_defconfig):
  2412. yield root_defconfig
  2413. # Assume all files in the arch/<arch>/configs/ directory (if it exists) are
  2414. # configurations
  2415. defconfigs_dir = os.path.join(srcarch_dir, "configs")
  2416. if not os.path.isdir(defconfigs_dir):
  2417. return
  2418. for dirpath, _, filenames in os.walk(defconfigs_dir):
  2419. for filename in filenames:
  2420. yield os.path.join(dirpath, filename)
  2421. def rm_configs():
  2422. # Delete any old ".config" (generated by the C implementation) and
  2423. # "._config" (generated by us), if present.
  2424. def rm_if_exists(f):
  2425. if os.path.exists(f):
  2426. os.remove(f)
  2427. rm_if_exists(".config")
  2428. rm_if_exists("._config")
  2429. def compare_configs(arch):
  2430. if equal_configs():
  2431. print("{:14}OK".format(arch))
  2432. else:
  2433. print("{:14}FAIL".format(arch))
  2434. fail()
  2435. def equal_configs():
  2436. with open(".config") as f:
  2437. their = f.readlines()
  2438. # Strip the header generated by 'conf'
  2439. i = 0
  2440. for line in their:
  2441. if not line.startswith("#") or \
  2442. re.match(r"# CONFIG_(\w+) is not set", line):
  2443. break
  2444. i += 1
  2445. their = their[i:]
  2446. try:
  2447. f = open("._config")
  2448. except EnvironmentError as e:
  2449. if e.errno != errno.ENOENT:
  2450. raise
  2451. print("._config not found. Did you forget to apply the Makefile patch?")
  2452. return False
  2453. else:
  2454. with f:
  2455. our = f.readlines()
  2456. if their == our:
  2457. return True
  2458. # Print a unified diff to help debugging
  2459. print("Mismatched .config's! Unified diff:")
  2460. sys.stdout.writelines(difflib.unified_diff(their, our, fromfile="their",
  2461. tofile="our"))
  2462. return False
  2463. if __name__ == "__main__":
  2464. run_tests()