اختبار نتائج الدوال
عندما تكتب دالة، اختبرها بأمثلة تعرف نتيجتها مسبقًا. يوفر تيكبامين أداة تعليمية صغيرة اسمها check_result(actual, expected). تقارن الأداة بين القيمة التي أنتجها الكود والقيمة التي توقعتها. إذا تطابقت القيمتان يستمر التنفيذ، وإذا اختلفتا تحصل على خطأ واضح.
def double(x):
return x * 2
check_result(double(3), 6)
check_result(double(10), 20)
الاختبار المفيد يجب أن يفشل أيضًا عندما تكون الدالة خاطئة. غيّر double مؤقتًا بحيث تعيد قيمة غير صحيحة، ثم شغّل استدعاءات check_result نفسها واقرأ رسالة الخطأ. بعد ذلك أعد تنفيذ الدالة الصحيح.
أكمل القيم المتوقعة في الاختبارين التاليين:
def double(x):
return x * 2
def quadruple(x):
return double(double(x))
check_result(quadruple(2), ...)
check_result(quadruple(5), ...)
استبدل كل ... بالنتيجة الصحيحة التي يجب أن تعيدها quadruple.
من فوائد الاختبارات أيضًا أن أي شخص يستطيع قراءتها وفهم أمثلة واضحة وغير ملتبسة عن وظيفة الدالة. وهذا مفيد خصوصًا عندما يصعب وصف الدالة بالكلمات.
مثلًا، انظر إلى الاختبارين:
check_result(surround("more", "++"), "++more++")
check_result(surround("the same", "="), "=the same=")
لا نحتاج إلى شرح طويل لما تفعله surround؛ الأمثلة توضحه مباشرة.
اكتب دالة surround تجتاز هذين الاختبارين، وتبدأ هكذا:
def surround(string, sides):
The argument
sidesshould be added before and afterstring.Use string concatenation to do this.
Make sure the body is indented.
Make sure you
returnsomething at the end.Make sure that you don't call
surroundinside the function body ofsurround. Check your indentation.
ممتاز! اكتب الآن دالة alert تجتاز الاختبارين التاليين:
check_result(alert("Warning", 2), "!! Warning !!")
check_result(alert("DANGER", 4), "!!!! DANGER !!!!")
لا يُسمح لجسم alert أن يحتوي على العامل +. استخدم الدالة surround بدلًا منه. يجب أن تبدأ الدالة هكذا:
def alert(string, level):
الفكرة أن تحيط النص أولًا بالمسافات، ثم تضيف زوجًا من علامات التعجب في كل دورة حتى تصل إلى المستوى المطلوب، مع استخدام القيمة التي تعيدها surround في كل مرة.
stringshould be surrounded by one space andlevelexclamation marks (!) on each side.Include the definition of
surroundfrom before in your program and call it inalert.Use
surroundfor the spaces.Use
surroundfor the exclamation marks.You're not allowed to combine several exclamation marks into one string, so call
surroundseveral times.That is, call
surroundonce for each pair of exclamation marks.So call
surround(..., '!')several times.Use a loop to call it several times.
Use
range(n)to make your loop haveniterations.Make sure you use the return value from
surround.Think of how you would build up strings with
+=. Repeatedly update the same variable, building up your result.That is, write
something = surround(something, '!')in your loop.Make sure you
returnsomething at the end ofalert.Make sure you don't
returninside the loop, but after it. Check your indentation.Make sure that you don't call
alertinside the function body ofalert. Check your indentation.
عمل ممتاز! أساليب الاختبار التي تعلمتها ستصبح مفيدة جدًا في الدروس القادمة.