Interviewed software testing interview questions organized by countless companies [with answers]

1. What design patterns are used in the automation code?

  • singleton design pattern

  • factory pattern
  • PO design pattern
  • data driven model
  • Interface Oriented Programming Design Patterns

2. What is an assertion (Assert)?

  • The assertion Assert is used to verify in the code whether the actual result meets the expected result,
  • If the test case fails to execute, an exception will be thrown and an assertion log will be provided

3. What is web automated testing

  • Web automated testing is automated testing from the UI (user interface) level,
  • Testers open the browser to test the business logic of the website by programming automation programs (test case scripts).

4. What is Selenium?

  • Selenium is an open source web automated testing framework that supports multiple programming languages ​​to develop automated test scripts and supports cross-browser platform testing

5. Write down the interfaces or classes you are most familiar with in Selenium

  • WebDriver、InternetExplorerDriver、 FirefoxDriver、 ChromeDriver、 WebElement、WebDriverWait、 By

6. What are the types of element positioning?

  The By class has a total of 8 element positioning methods, all of which are static methods:

  • By.id():
  • By.name():
  • By.tagName():
  • By.className():
  • By.cssSelector():
  • By linkText():
  • By partialLinkText():
  • By.xpath():

7. What is XPath?

  • It is a way to find web page elements, which is equivalent to a path in the middle of the dom, and can be located by absolute path and relative path
  • It is very helpful for defining dynamic page elements, but it also needs to be used with caution, because if the page structure changes, the positioning information may also need to change.

8. What is the difference between findElement() and findElements (methods

  • Both are ways to find page elements
  • findElement(): Find a page element and only return a WebElement object
  • findElements() : Find all matching elements on the page and return a collection of elements

9. Is there any other way to click on the login button besides the click method?

  • You can also use the submit() method, provided that the type of the input element is submit

10. How to improve the execution speed of Selenium scripts

  • Optimize waiting time: use WebDriverWait intelligent waiting instead of thread waiting for sleep and implicit waiting for implicitWait
  • Reduce unnecessary operations: such as directly entering a certain page instead of entering a certain page through a series of automated operations. If the server allows, use multi-threading to implement concurrent execution of test cases.

11. How to automate the testing of functions containing verification codes

  • 1) : Image recognition, technically difficult, poor effect, not recommended
  • 2) : Shield the verification code, invite development and processing, but it is not recommended in the pre-production environment or production environment
  • 3) : universal verification code, using a complex verification code that others cannot guess

12. How to verify whether the check button is selected

  • You can use the isSelected() method of the element. If it returns true, it means it is selected, otherwise it means it is not selected

13. How to deal with the alert pop-up window?

  • To handle the alert pop-up window, you first need to jump to the alert, and then click the OK or Cancel button.
  • Alert alert = driver.switchTo().alert(); //Switch to alert
  • alert.accept0; //OK
  • alert.dismiss0; // cancel

14. How to select a menu item in the drop-down menu?

  • If the drop-down menu is a select tag, use: selectByValue() or selectByIndex() or selectByVisibleText()
  • If the drop-down menu is not created through the select tag, locate the element directly through xpath and click to select

15. How to simulate the forward, backward and refresh operations of the browser

  • driver.navigate().back()://back
  • driver.navigate().forward()://forward
  • driver.navigate0.efresh()://refresh

16. How to get the URL of the current page?

  • String url = driver.getCurrentUrl();

17. What is the difference between WebDriver's close() and quit( methods?

  • The close() method just closes the currently operating window
  • quit() closes all open windows

18. What defects do you think automated testing uses?

  • The cost is relatively high, but the effect may not be high
  • Limited functionality suitable for automated testing
  • Some functional operations are relatively complex, such as verification codes
  • High maintenance costs, once the project requirements change, automated test scripts and use cases need to be improved

19. Web-side function automation, how to upload files (non-input upload)

  • Interacting with the windows window can be achieved using the pywin32 library.

20. When encountering <d1 class="inf-bar clearfix">, a control with a space in the middle of the class, how to locate it by class?

  • xpath positioning: direct //d1 [@class="inf_bar clearfx"]
  • css positioning: d1.inf_bar.clearfix

21. Selenium automation, how to deal with iframe?

  • Use switch_to.frame to switch into the iframe, and then locate the elements in it and operate

22. How to switch the handle in the function automation of the Web side.

  • Get all window handles first, then use switch_to.window() to switch to the specified window

23. When encountering a control with the readonly attribute in the test, what should I do? Briefly describe the idea

  • Modify the close readonly attribute first, and then operate the element.

Requirement: Given an array that only contains positive integers and is not empty, return the top N numbers with the most repetitions in the array (the returned results are in descending order of the number of repetitions), please use a familiar language to implement this requirement. Write it in 10 minutes

a = [1, 6, 7, 4, 4, 5, 4, 5, 4, 5, 5, 6, 7, 8, 5, 6, 7, 3, 4, 2, 2, 1, 4, 8, 9, 4, 5, 6]


def get_datas(a):
    result = []
    data_dict = {}
    # 键值对:键:数字,值:在列表中的次数
    for item in set(a):
        data_dict[str(item)] = a.count(item)
    print(data_dict)
    # 将键值对按值(数字出现的次数)排序 ---从高到低排序
    res = sorted(data_dict.values(),reverse=True)
    for num in res:
        for key,value in data_dict.items():
            # 如果值在列表中不存在,则添加到结果列表中
            if num == value and key not in result:
                result.append(key)

    return result


a1 = get_datas(a)

Results of the:

25. For example: passwd={"admin'":"123321","user1":"123456"} Satisfy the following conditions?

  • 1. Design a login program. Different user names and corresponding passwords are stored in a dictionary. Enter the correct user and password to log in.
  • 2. First enter the user name, if the user name does not exist or is empty, it will always prompt to enter the correct user name
  • 3. When the user name is correct, it will prompt to enter the password. If the password does not correspond to the user name, it will prompt that the password is wrong, please re-enter.
  • 4. If the wrong password is entered more than three times, the program will be interrupted.
  • 5. When the wrong password is entered, there are still several chances to be prompted
  • 6. When both the user name and password are successfully entered, it will prompt that the login is successful!

users = {"admin": "123456", "user1": " 123456"} 
count = 0 


def login(): 
    global count 
    username = input("Please enter username:") 
    if username == None or username == "": 
        login() 
    if username not in users.keys(): 
        print("The username input is incorrect, please re-enter the username:") 
        login() 

    while (count < 3): 
        passwd = input("Please enter Password: ") 
        if passwd == users[username]: 
            print("Successful login!!") 
            count = 3 
        else: 
            count += 1 
            print("Wrong password entered, you have {0} chances.".format (3 - count)) 


login()

26. Write a program:---I don't understand

1. It can search for files whose file names contain specified strings in the current directory and all subdirectories of the current directory;

2, and print out the relative path.

import os

paths = []


def get_paths(dir, relate_dir=None, search_str=None):
    global paths
    if search_str == None:
        return os.listdir(dir)

    for item in os.listdir(dir):
        if relate_dir == None:
            relate_dir == os.curdir

        if os.path.isfile(os.path.join(dir, item)):
            if item.find(search_str) != -1:
                paths.append(os.path.join(relate_dir, item))
        elif os.path.isdir(os.path.join(dir, item)):
            paths = get_paths(os.path.join(dir, item), os.path.join(relate_dir, item), search_str)

    return paths


dir = os.getcwd()
search_str = "fun"
print(get_paths(dir, search_str=search_str))

27. Please write the running result of the following code

def f(str1, *args, **kwargs):
    print(str1, args, kwargs)


l = [1, 2, 3]
t = [4, 5, 6]
d = {"a": 7, "b": 8, "c": 9}

f(1, 2)
f(1, 2, 3, "python")
f("python", l, d)
f("python", *t)
f("python", *l, **d)
f("python", q="winning", **d)

Results of the:

1 (2,) {}
1 (2, 3, 'python') {}
python ([1, 2, 3], {'a': 7, 'b': 8, 'c': 9}) {}
python (4, 5, 6) {}
python (1, 2, 3) {'a': 7, 'b': 8, 'c': 9}
python () {'q': 'winning', 'a': 7, 'b': 8, 'c': 9}

28. Please write the running result of the following code

import copy 

a = [1, 2, 3, 4, ["a", "b"]] b 
= a 
c = copy.copy(a) 
d = copy.copy(a) 
a.append(5) 
a[ 4].append("c") 

# Please fill in the output content according to the above rules 
print('a=', b) 
print('b=', b) 
print('c=', c) 
print('d= ', d)

Results of the:

a= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c= [1, 2, 3, 4, ['a', 'b', 'c']]
d= [1, 2, 3, 4, ['a', 'b', 'c']]

29. Merge two lists of equal length into one dictionary, request: merge into {'A': 1, 'B': 2, 'C': 3}, please use one line of code to achieve

keys = ["A", "B", "C"]
values = ["1", "2", "3"]
print(dict(zip(keys, [int(x) for x in values])))

30. Merge two lists and eliminate duplicate values

list_1 = ["a", "b", "c", "1", "A", "winning"]
list_2 = ["a", "python", "string"]
print(set(list_1 + list_2))
# 执行结果:{'c', 'winning', '1', 'string', 'b', 'a', 'python', 'A'}

31. Given a list, sort the list from large to small according to x in the dictionary

a = [{"x": 1, "y": 2}, {"x": 2, "y": 3}, {"x": 3, "y": 4}]
aa1 = sorted(a, key=lambda item: item["x"], reverse=True)
print(aa1)
# 执行结果:[{'x': 3, 'y': 4}, {'x': 2, 'y': 3}, {'x': 1, 'y': 2}]

32. What is the basic structure of Html, how to draw a 2X2 table

<html>
<head>
<title>两行量列的表格</title>
-<head>
<body>
<tatle width="200" border="1">
<tr><td> </td>
<td> </td>
-</tr>
<td> </td>
<td> </td>
-</tr>
-</table>
-</body>

</html>

33. Write a statement to print "let's go", she said

print("\"let's go\",she said")

34. Please write a piece of code to randomly generate 10 numbers and write them into a file

import random

fs = open("num.txt", "a")
list1 = []
for index in range(10):
    num = random.randint(0, 10)
    list1.append(str(num))

print(list1)
fs.write(",".join(list1))
fs.close()

Results of the:

35. Please write the code execution results separately

a = 1 


def fun(a): 
    a = 2 


fun(a) 
print(a) 
# Execution result: 1

===============

b = [] 


def fun(b): 
    b.append(1) 


fun(b) 
print(b) 

execution result: [1]

36. What are the categories of automated testing: AB

  • A, UI automation
  • B, interface automation
  • C. Web automation
  • D, terminal automation

37. What is a conversation?

  • The so-called session is session, and session is a server cache technology, created by the server side,
  • When the user logs in to the system, the information of the logged-in user is generally saved in the session object, and then the id ( JSESSIONID ) corresponding to the session is returned.
  • Therefore, most systems will use the session mechanism to achieve authentication. Session saves data in the form of key-value.

38. What is a token?

  • The so-called token is actually a string returned by the server (a string similar to: xys73494954sdhcdr83435). The algorithm that this data is based on needs to be confirmed by the developer. Generally, this data is unique, and the token returned by the server will be different every time. Same.

The reason why Token can be used for authentication is as follows:

  • User a calls the login interface---"logged in to system b---"the server generates a unique token information (assumed to be c),
  • Then a mapping will be made with the user's number id (assumed to be d): c - d,
  • Then store such a mapping relationship in a cache such as a database or redis,
  • Then return this token to the client---"When the client calls other interfaces that require authentication,
  • You only need to bring the cached token to the verification--"The server checks whether there is login user information based on the token to determine whether the request is a logged-in authorized user. (Here, how the client gets the token, how to save it, and how to bring it back when requesting again, the interface authentication part has been explained above).

39. You do interface automation, what database is used for the project, and what is used to operate this database

  • Mysql, you can use jdbc to implement operations such as adding, deleting, checking, and modifying the database.

40. Have you ever used a unit testing framework, what framework is it, and what common annotations are there?

  • Used, junit (if you are not familiar with it), testng, these test frameworks support us to define test suites to manage our test case code, and some rich annotations provided by these test frameworks are not only very convenient Control the execution sequence of test cases to control the entire test process, and also provide support for the realization of various test scenarios.

Common annotations:

  • @Test , used to mark test methods
  • @BeforeSuite, suitable for global initialization of the suite, executed before the entire suite is executed
  • @BeforeTest, suitable for the initialization of the Test test set, executed before the test set is executed
  • @BeforeClass, suitable for the initialization of the Class test class, executed when the test class is called
  • @BeforeMethod, suitable for initialization before the test method is executed, and executed before the test method
  • @After... , compared to the above to answer, the execution sequence is just the opposite of the above, and the function is suitable for recycling resources.
  • @Parameters : Parameterized annotations to facilitate parameterization
  • @DataProvider : data provider, which can be used to provide batch test data for testing

41. Talk about your understanding of the interface

  • An interface is a service, a function point implementation, a channel for data transmission, and a server-side implementation of a certain protocol (such as the http protocol..) and a mapping mechanism (when accessing a urlI, it will be parsed through the server-side mapping processing mechanism , falling into the corresponding processing function), the interface parameters are the parameters of the function, and the response data of the interface is the return value of the function.

41. Have you ever done an interface test, and what tools are you familiar with?

  • Have done it (even if you haven't used a visual tool to do interface testing before, but you have learned interface automation testing now that you have experience).

Familiar tools:

  • Visualization tools such as: jmeter, postman, soapui, etc. (say what you have used)
  • Code: Httpclient sends packets to implement interface testing.

42. The tool can already complete automated testing, why use code to complete it? 

  • Tools for automated testing rely on and have limitations. Some tools provide assertion methods and expressions, but the cost of getting started is high, and the existing assertion expressions that have been provided may not meet the data validation of some special rules, while the code It is quite more flexible, and the assertion method can be designed according to your own ideas.

43. Please briefly talk about the difference between the two request methods of get and post?

Get :

  • a. Generally, the request to fetch data from the server can be set to the get method
  • b. When passing parameters in the Get method, the parameters are generally spliced ​​directly on the url (for example: http://xxx?id=1&type=2 )
  • c. The amount of parameter data that can be passed by the Get request method is limited (because the general parameters are spliced ​​on the url, and the browser has restrictions on the length of the url)
  • d. Get request is not as secure as post (relatively) because the data is directly spliced ​​on the url, but the execution efficiency of get is faster than post

Post :

  • a. Generally, the request to submit data to the server will be set to post mode
  • b.Post method to pass parameters generally puts the parameters in the request body instead of concatenating them in the url
  • c. The amount of data that can be submitted by the Post request method is not limited
  • d. Post request parameter passing is safer than get (relatively not absolute), but the execution efficiency of post is not as good as get.

44. Briefly describe the delayed waiting methods you know

Forced wait:

  • Also called thread waiting, the waiting is completed by thread sleep, such as waiting for 5 seconds: Thread sleep(5000),

Implicit wait:

  • Delayed waiting completed by implicitly Wait, note that this is a wait for global settings, such as setting the timeout to 10 seconds, after using implicitlyWait, if the element is not found for the first time, it will continue to cycle within 10 seconds to find element, if it is not found for more than 10 seconds, an exception is thrown

Explicitly wait:

  • Also known as intelligent waiting, the specified waiting time is specified for the specified element location, and the element is searched within the specified time range. If the element is found, it will return directly. If the element is not found within the timeout, an exception will be thrown.

45. What is the output?

def f(x, l=[]):
    for i in range(x):
        l.append(i * i)
        print(l)
f(2)
f(3, [3, 2, 1])
f(3)

结果:
[0]
[0, 1]
[3, 2, 1, 0]
[3, 2, 1, 0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0]
[0, 1, 0, 1]
[0, 1, 0, 1, 4]

46. ​​How do you automate the interface?

  • Reference answer: Interface use cases will be designed according to the interface document, and then the interface request will be realized by using python's requests library, and the test data will be managed by excel. And use the unittest test framework in the code to realize the assertion processing of the interface use case.

47. How to use webdriver to perform right mouse click operation?

Using the ActionChains class

ac= ActionChains(driver);

ac.context_click(element object).perform()

48. When you write the automation framework, where do you save the test cases? What do you use to read them?

  • Save the test case to Excel, and use the third-party library openpyxI to complete the operation on Excel

49. Write a piece of code in python, calculate the integer divisible by 7 within 1-1000, divide by 5 and leave 3, and print it by line

for i in range(1, 1000): 
    if i % 7 == 0 and i % 5 ==3: 
        print(i) 


execution result: 
28 
63 
98 
133 
168 
........

50. Xiao Ming has 100 yuan. He wants to buy 100 books. English books cost 5 yuan, math books cost 3 yuan, and Chinese books cost 0.5 yuan. How many ways can he buy? Please programmatically solve this problem, you can use any programming language, including pseudo-languages.

According to the meaning of the question, you want to buy one hundred books, one hundred yuan, see how many ways to buy it (you don’t have to spend all the money, as long as you can buy one hundred books):

The prices of the three books are: 5, 3, 0.5, so the most you can buy is 20 math books, 33 English books, and 200 Chinese books. But there is also a combined buying method, so it can be realized through a triple for loop. ijk represents the number of purchased mathematics, English, and Chinese books respectively. The loop conditions are i<=20, j<=33, k<=200, then As long as i+j+k == 100, 5*i+3*j+0.5*k<= 100 is enough. The final count of all combinations is the number of buying methods.

n = 0
for i in range(21):
    for j in range(34):
        for k in range(201):
            if 5 * i + 3 * j + k * 0.5 <= 100 and i + j + k == 100:
                n += 1
print(n)

51. How to submit the bug after using monkey test?

  • When monkey tests the APP, we will use adb shell monkey-p package name -f script -VV -v >D:log.txt to output the log to the local, and take a screenshot of the log when an error occurs, and take a screenshot of the log And the bug description is submitted to ZenTao and assigned to the corresponding development. But before submitting the bug, the bug will be reproduced manually.

52. If you want to create a hyperlink in an HTML page, which method is there?

  • Hyperlink: <a href="url" target=". blank">content</a>
  • target="_ blank" opens in a new window.
  • JS jump link: <a href="#" οnclick="javascript:location.href='URL";">content</a>
  • Meta tag jump link: <meta http-equiv="refresh" content="3;URL = URL">
    • (Number 3 is seconds)  

53. Which of the following statements about automated testing is wrong: (ABCD)

A. Automated testing can completely replace manual testing

B. Automated testing can greatly reduce the workload of the testing team

C. Performance testing cannot be automated

D. Automated testing can find a large number of new defects

How does a custom function in Python pass dynamic parameters?

  • Parameters use *args or *kwargs

55. What is a lambda function? What are its benefits?

  • lambda function: no function name, it is an anonymous function.
  • Advantages: only do simple calculations, receive any multi-parameters and return values, without complex function bodies. It can be used as a callback function and passed to some applications, such as message processing.

56. How does the subclass call the constructor of the parent class in the Python language?

  • If the subclass does not define a constructor, the subclass will call the constructor of the parent class by default;
  • If the subclass defines a constructor, then in the constructor of the subclass, call the constructor of the parent class: In python3, use super()._ _init_ _()

57. It is known that L = ["a", "b", "c", "d", "e", "f", "g"], then the value of L[3] is _ L[::5 ] is __L[::2] is _

L = ["a", "b", "c", "d", "e", "F", "g"]

print(L[3])
print(L[::5])
print(L[::2])

执行结果:
d
['a', 'F']
['a', 'c', 'e', 'g']

58. Given the list x=[1, 2], then the value of the expression list(enumerate(x))

x = [1, 2] 
a1 = list(enumerate(x)) 
print(a1) 
# Execution result: [(0, 1), (1, 2)]

59. The python built-in function to check the variable type is type

60. The python function to view the variable memory address is id

61. The expression sum(range(1, 10, 2)) evaluates to 25

print(sum(range(1, 10, 2))) # Take a sum of two bits each: 1,3,5,7,9 
# Execution result: 25

62. Python's ordered sequence is: list, tuple, character

Xiao Feifei buys many bottles, and each pair of bottles will have the same number on it. Xiao Feifei counted his bottles and found that the number of bottles was an odd number N, that is, there was an unpaired bottle. Now Xiao Feifei is going to get a new bottle. May I ask what number he needs to mark on the new bottle so that all the bottles are matched. For example, he has seven bottles ( N=7 ), then the labels can be: 1, 6, 13, 1, 6, 13, 13

Then the new bottle will be marked as 13, after adding there will be (1, 1), (6, 6), (13, 13), (13, 13) these 4 pairs

Input: a positive integer N (1<=N<=1000) in the first line of the test data indicates that there are N numbers, and N is guaranteed to be an odd number, and the second line has N natural numbers, each of which is less than 10^9

Output: output an integer on a line, the number of the new bottle

Example:

  • enter:
  • 9
  • 121233441
  • Output: 1

def func(n, data): 
    if 0 <= n <= 1000 and n % 2 == 1 and len(data) == n: 
        for i in data: 
            if 0 < i < (10 ** 9): 
                if data.count(i) % 2 != 0: 
                    return i 
                else: 
                    print("The number of the bottle is a natural number and less than 10^9") 
    else: 
        print("The parameter passed in is wrong") 


res = func( 7, [1, 6, 1, 6, 13, 13, 13]) 
print(res)

63. Write a function in python to output the given substring characters in a string from small to large, and the position of the first character is 0

  • Such as: myOrder(abejykhsesm',2,5)
  • Output: ehjky

def my_order(s, start, len): 
    # First slice 
    s = s[start:start + len] 
    # Mandatory conversion to a list 
    li = list(s) 
    # Sorting 
    li.sort() 
    # Splicing into a string 
    res = " ".join(li) 
    print("The output result is: ", res) 


my_order("abcedfgh", 2, 4) 

The result is: cdef

64. For the input integer array, output the maximum value, the number of maximum values, the minimum value and the number of minimum values ​​in the array elements

Function name: max_ and_ min(list)

Input parameter: list integer array

Output: list integer array, with four values, respectively representing the maximum value, the number of maximum values, the minimum value and the number of minimum values

  • Example: max and.min([1,4,21,5,6,1,1]) => [21,1,1,3]
  • max_ and. min(1]) => [1,1,1,1]

def max_and_min(a):
    b = sorted(a, reverse=True)
    max = b[0]
    max_num = b.count(max)
    min = b[-1]
    min_num = b.count(min)
    return [max, max_num, min, min_num]


a = [5, 5, 5, 4, 3, 2, 2]
print(max_and_min(a))
# 执行结果:[5, 3, 2, 2]

65. Right fill the string, fill str to src according to the length of len

Function name: rpad(src,len,str)

Input parameters:: src original string, len target string length, str used to fill the string

Output: the padded string

Example:

  • rpad ("abcd",10,"12") =>"abcd121212"
  • rpad ("abcd",11,"12") =>"abcd1212121"
  • rpad ("abcd",10,"12") =>"abcd121212”
  • rpad ("abd",12,"0") =>*"bd0000000”
  • rpad ("abcd",12,") =>"abcd

66. How can automated testing be done for products presented on the web? Talk about your thinking and direction.

reference:

  • Automated testing on the web side basically simulates manual testers to do functional testing.
  • Replace human operations with automatic execution of machines.
  • There are two directions for automated testing of products presented on the web: the interface layer and the interface operation layer, and the automation ratio of the interface layer is higher than that of the interface operation layer.
  • And it mainly conducts automated testing on the stable functions of the product, which is mainly used for smoke testing and regression testing of the core functions of the product.
  • Start with the most core functions of the system, and then slowly spread out according to the situation.

67. Please describe the idea of ​​realizing automated testing of user login simulation

reference:

Automated testing ideas based on user login:

  • Use python+selenium framework to write all test cases for login,
  • Use the unittest framework to organize test cases.
  • Use Htmltestrunner to form an html version of the test report, and use the mail module to send the test report to the relevant personnel of the project team.

Finally:【I hope my previous self-study materials can help you】

If necessary, you can ask me to help revise your resume, and my friends who I recognize can also help with internal referrals. Thanks to everyone who reads my article carefully, watching the fans' rising and following all the way, how to find out what is wrong with the editor or have better suggestions, I hope everyone will actively leave a message in the comment area! ! ! [Brothers, the interview questions are not easy to post, if you want to, just click the small card below]

Guess you like

Origin blog.csdn.net/xiao1542/article/details/131945920
Recommended