The latest automated testing interview questions in 2023 to help you get hired quickly

1. What design patterns are used in automation code?
Singleton design pattern,
factory pattern,
PO design pattern
, data-driven pattern,
interface-oriented programming design pattern
 

2. What is assertion (Assert)?
Assertion Assert is used to verify in the code whether the actual results meet the expected results.
If the test case fails to execute, an exception will be thrown and the assertion log will be provided.
3. What is web automation testing? Web automation testing
is from For automated testing at the UI (user interface) level,
testers open the browser to test the business logic of the website by programming automated programs (test case scripts).
4. What is Selenium?
Selenium is an open source web automated testing framework that supports the development of automated test scripts in multiple programming languages ​​and supports testing across browser platforms. 5. Write 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, and they are all static methods:

By.id():
By.name():
By.tagName():
By.className():
By.cssSelector():
By linkText():
By partialLinkText():
By.xpath():
7. Xpath is What?
It is a way to find web page elements. It is equivalent to a path in the middle of the dom. It can be positioned using absolute paths and relative paths. It is very helpful
for defining dynamic page elements. It also requires Use with caution because if the page structure changes, the positioning information may need to change as well.
8. What is the difference between findElement() and findElements() methods?
Both methods are used to find page elements.
findElement(): When searching for a page element, only one WebElement object will be returned.
findElements(): Find all matching elements on the page and return Element collection
9. Is there any other way to click the login button besides using 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
and optimize the waiting time: use WebDriverWait Intelligent waiting replaces thread waiting for sleep and implicit waiting
to reduce unnecessary operations: such as directly entering a page instead of entering a page through a series of automated operations. If the server allows it, use multi-threading to implement concurrent execution of test cases.
11. How to automate testing of functions containing verification codes
1): Image recognition, technical difficulty, poor results, not recommended
2): Block verification codes, invite development processing, but not recommended in pre-production environment or production environment
3): Universal verification code, using a complex verification code that cannot be guessed by others.
12. How to verify whether the check button is selected?
You can use the isSelected() method of the element. If true is returned, it means it is selected, otherwise Indicates that it is not selected.
13. How to handle 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; //Confirm
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 this drop-down menu is not created through the select tag ,
locate the element directly through ).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 only closes the window that is currently being operated.
quit() is to close the window. 18.
Which defects do you think are used in automated testing?
The cost is relatively high, but the effectiveness may not be high.
The functions suitable for automated testing are limited.
Some functional operations are relatively complex, such as verification code
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 type upload) and
interact with windows windows, can be implemented using the pywin32 library.
20. Encountered <d1 class="inf-bar clearfix "> How to position this kind of control with spaces in the middle of the class through 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 to the iframe, and then locate the elements and operate them.
22. How to switch handles in Web-side function automation.
First get all window handles, and then use switch_ to.window() to switch to the specified window
23. What should you do if you encounter a control with readonly attribute in the test? Briefly describe the idea:
first modify and turn off the readonly attribute, 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 (return results are in descending order from the most to the least 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"} Does the following conditions meet?
1. Design a login program. Different usernames and corresponding passwords are stored in a dictionary. Enter the correct username and password to log in. 2.
First enter the username. If the username does not exist or is empty, it will always prompt that the input is correct. Username
3. When the username is correct, it will prompt you to enter the password. If the password does not correspond to the username, it will prompt you that the password is incorrect and please re-enter it.
4. If the wrong password is entered more than three times, the program will be interrupted.
5. When the wrong password is entered, it will prompt that there are still several opportunities.
6. When the user name and password are both entered successfully, it will prompt that the login is successful!

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


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

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


login()

26. Write a program:---I don’t understand it.

1. Can search for files whose file names contain the specified string in the current directory and all subdirectories of the current directory;

2. And print out the relative path.

import us

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 results 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 results 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 a dictionary. The requirement is: merge into {'A': 1, 'B': 2, 'C': 3}. Please use one line of code to achieve this.

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) )
# Execution result: {'c', 'winning', '1', 'string', 'b', 'a', 'python', 'A'} 31. Given a list, according to x in the

dictionary , sort this list from large to small
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)
#Execution result: [{'x': 3, 'y': 4}, {' x': 2, 'y': 3}, {'x': 1, 'y': 2}]
32. What is the basic structure of Html and 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 the 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 to 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 down 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 session?
The so-called session is a session, and session is a server caching technology, which is controlled by the server. When
a user logs in to the system, the logged-in user's information will generally be saved in the session object, and then the id (JSESSIONID) corresponding to the session will be returned. Therefore, most systems will use the session
mechanism to implement authentication. Session saves data in key-value format.
38. What is a token?
The so-called token is actually a string returned by the server (somewhat similar to: xys73494954sdhcdr83435). What algorithm 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 called the login interface ---" logged in to system b ---" the server generated a unique token information (assumed to be c), and then made a mapping with the
user's ID (assumed to be d): c - d,
and then store this mapping relationship in a cache such as database or redis,
and then return this token to the client ---> When the client calls other interfaces that require authentication,
it only needs to cache this The token is brought to the verification--》The server checks whether there is logged-in user information based on this token to determine whether the request is for a logged-in authorized user. (How the client obtains this token, how to store it, and how to bring it when requesting again are explained in the interface authentication section above).
39. When you do interface automation, what database is used for the project, and what database is used to operate
Mysql. You can use jdbc to implement operations such as addition, deletion, query, and modification of the database.
40. Have you ever used a unit testing framework? What kind of framework is it? What common annotations
have you used? Junit (you don’t need to mention it if you are not familiar with it), testng. These testing frameworks all support us to define test suites and manage our test cases. At the same time, the rich annotations provided by these test frameworks can not only easily control the execution order of test cases to control the entire test process, but also provide support for the implementation of various test scenarios.
Commonly used notes:

@Test, used to mark the test method
@BeforeSuite, suitable for the global initialization of the suite, @BeforeTest is executed before the entire suite is executed,
suitable for the initialization of the Test test set,
@BeforeClass is executed before the test set is executed, suitable for the initialization of the Class test class , execute @BeforeMethod when the test class is called
, suitable for initialization before the test method is executed, execute
@After... before the test method, compare the above to answer, the execution order is just opposite to the above, and the effect is suitable for some recycling resource.
@Parameters: Parameterized annotations to facilitate parameterization
@DataProvider: Data provider, which can be used to provide batch test data for testing
41. Tell me about your understanding of interfaces.
Interfaces are services, function point implementations, and data transfers. Channel is also a server-side function that implements a certain protocol (such as http protocol...) and mapping mechanism (when accessing a urlI, it will be parsed through the server-side mapping processing mechanism and fall into the corresponding processing function), interface parameters They 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 interface testing? Are there any familiar tools?
Have done it (even if you have not used visual tools to do interface testing before, but now you have learned interface automation testing, you have experience).
Familiar Tools:

Visual tools such as: jmeter, postman, soapui, etc. (which ones have been used will be mentioned)
Code: httpclient outsourcing technology to implement interface testing.
42. Tools can already complete automated testing, so why do you still need to use code to complete it? 
Tools for automated testing have strong dependencies and limitations. Some tools provide assertion methods and expressions, but the cost of getting started is high, and they are already provided Existing assertion expressions may not meet the data verification of some special rules, but the code is quite 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, get and post?
Get:

a. Generally, requests to retrieve data from the server can be set to the get method. b.
When passing parameters in the Get method, the parameters are usually directly spliced ​​into 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 generally the parameters are spliced ​​on the url, and the browser has restrictions on the length of the url) d.Get request because the data is directly spliced
​​on the url, so The security is not as strong as post (relatively), but the execution efficiency of get is faster than post
Post:

a. Generally, requests to submit data to the server will be set to the post method.
b. When passing parameters in the Post method, the parameters will generally be placed in the request body and not spliced ​​into the URL. c.
The amount of data that can be submitted by the Post request method is not limited
. d. Post request parameters are safer than get (relatively but not absolutely), but the execution efficiency of post is not as good as get.
44. Briefly describe the delayed waiting methods you know.
Forced waiting:

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

Delayed waiting completed by implicitly Wait. Note that this is a wait for global settings. For example, if the timeout is set to 10 seconds, after using implicitlyWait, if the element is not found for the first time, it will continue to loop to find it within 10 seconds. If the element is not found after 10 seconds, an exception is thrown. Explicit
wait:

Also known as smart waiting, the specified waiting time is specified for positioning the specified element, and the element is searched within the specified time range. If the element is found, it will be returned directly. If the element is not found after the timeout, an exception will be thrown. 45. What is the output result
?

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

Result:
[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 interfaces?
Reference answer: You will design interface use cases based on interface documents, then use python’s requests library to implement interface requests, and use excel to manage test data. And use the unittest testing framework in the code to implement assertion processing of interface use cases.
47. How to use webdriver to perform right-click operation?
Use ActionChains class

ac= ActionChains(driver);

ac.context _click(element object).perform()

48. When you write an automation framework, where are the test cases saved? What are you using to read them? The
test cases are saved in Excel and use the third-party library openpyxI to complete the operation of Excel
. 49. Use python to write a piece of code to calculate 1- An integer within 1000 that can be divisible by 7, divided by 5 and a remainder of 3, is printed line by line.

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


执行结果:
28
63
98
133
168
........

50. Xiao Ming has 100 yuan. He wants to buy 100 books. English books are 5 yuan each, math books are 3 yuan each, and Chinese books are 0.5 yuan each. How many ways can he buy them? Please programmatically solve this problem, you can use any programming language, including pseudo-language.
According to the question, you want to buy one hundred books for one hundred yuan. It depends on how many ways you can 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, and 0.5 respectively. Then the most purchased mathematics books are 20 books, 33 English books, and 200 Chinese books. But there is also a combined purchase method, so it can be achieved 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 and 5*i+3*j+0.5*k<= 100 are satisfied. Finally, counting 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 a bug when 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, submit the screenshot of the log and the description of the bug to ZenTao, and assign it to the corresponding developer. But before submitting the bug, I will manually reproduce the bug.
52. If you want to create a hyperlink in an HTML page, what is the implementation method?
Hyperlink: <a href="Website" target=". blank">Content</a>
target="_ blank" is a new window Open.
JS jump link: <a href="#" οnclick="javascript:location.href='website";">Content</a>
meta tag jump link: <meta http-equiv="refresh" content=" 3; URL = website ">
(The number 3 is seconds)  
53. Which of the following statements about automated testing are wrong: (ABCD)
A. Automated testing can completely replace manual testing

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

C. Performance testing cannot be automated

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

How do custom functions in Python pass dynamic parameters?
Parameters use *args or *kwargs.
55. What is a lambda function? What are its benefits?
Lambda function: It has no function name and is an anonymous function.
Advantages: It only performs simple operations, receives any multiple parameters and returns a value, and there is no complex function body. It can be used as a callback function and passed to certain applications, such as message processing.
56. How does a 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 _ The value of L[::5] is __L[::2] The value 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. It is known that the list x=[1, 2], then the value of the expression list(enumerate(x))
= [1, 2]
a1 = list(enumerate(x))
print(a1)
#Execution result: [ (0, 1), (1, 2)]
59. The python built-in function to view 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)) The value is 25
print(sum(range(1, 10, 2))) # Take the sum of each two digits: 1,3,5,7,9
# Execution result: 25
62. Python’s ordered sequence is: list , Yuanzu, character
Xiao Feifei buys a lot of 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 unmatched bottle. Now Xiao Feifei is going to get a new bottle. Please ask him what number he needs to mark on the new bottle so that all the bottles are matched. For example, if 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 4 pairs (1, 1), (6, 6), (13, 13), (13, 13).

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

Output: Output one integer per line, the number of the new bottle

Example:

Input:
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 value 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. Use python to write a function that outputs the given substring characters in a string from small to large. The position of the first character is 0.

  • For example: myOrder(abejykhsesm',2,5)
  • Output: ehjky

def my_order(s, start, len):
    # First slice
    s = s[start:start + len]
    # Convert to list
    li = list(s)
    # Sort
    li.sort()
    # Then concatenate into 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 parameters: list integer array

Output: list integer array, with four values, 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))
#Execution result: [5, 3, 2, 2]

65. Right padding of the string, padding str into src according to the length of len.
Function name: rpad(src,len,str)

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

Output: completed 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 based on the Web? Let’s talk about you ideas and directions.
refer to:

Automated testing on the web side basically simulates manual testers to do functional testing.
Replace human operations with machine automation.
There are two directions for automated testing of products presented on the web: the interface layer and the interface operation layer, and the proportion of automation in the interface layer is higher than that in the interface operation layer.
And it mainly conducts automated testing on the stable functions of the product, 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 expand according to the situation.
67. Please describe the idea of ​​​​implementing user login simulation automated testing
. Reference:

Automated testing ideas based on user login:

Use the python+selenium framework to write all test cases for login, and
use the unittest framework to organize test cases.
Use Htmltestrunner to form an HTML version of the test report, and use the email module to send the test report to relevant personnel in the project team.
Finally: [I hope my previous self-study materials can help you]

How to obtain documents:

This document should be the most comprehensive and complete preparation warehouse for friends who want to engage in [software testing]. This warehouse has also accompanied me through the most difficult journey. I hope it can also help you!

All of the above can be shared. You only need to search the vx official account: Programmer Hugo to get it for free.

Guess you like

Origin blog.csdn.net/2301_77645573/article/details/132839780