A framework is a collection of code that is leveraged in the development process by providing ready-made components. Through the use of frameworks, architectural patterns and structures are created, which help speed up the development process. This Zone contains helpful resources for developers to learn about and further explore popular frameworks such as the Spring framework, Drupal, Angular, Eclipse, and more.
As developers, we are always on the lookout for tools and technologies that can improve our products and services. In this article, we will discuss the key differences between Tornado and FastAPI, two popular web frameworks for Python. Additionally, we will explain why we at Rеblаzе decided to switch from Tornado to FastAPI to enhance our offerings. Background: Tornado and FastAPI Tornado is an asynchronous networking library and web framework designed for handling long-lived connections and providing real-time updates in web applications. It has been around since 2009 and is well-established in the Python ecosystem. FastAPI, on the other hand, is a relatively newer web framework, first released in 2018. It is built on top of the Starlette framework and the Pydantic library, providing a high-performance and easy-to-use solution for developing APIs. FastAPI has gained significant traction in recent years and is known for its speed, simplicity, and versatility. Key Differences Between Tornado and FastAPI Performance FastAPI is known for its outstanding performance, thanks to its asynchronous nature and the underlying ASGI (Asynchronous Server Gateway Interface) server. It offers better concurrency and can handle a larger number of simultaneous connections compared to Tornado, which is built on the WSGI (Web Server Gateway Interface) standard. We made a performance test but will be better if I add a link to a full comparison of different Python's rest frameworks. Type Annotations and Validation FastAPI takes full advantage of Python's type annotations and the Pydantic library to automatically validate request and response data. This feature helps reduce the amount of boilerplate code and potential errors in data validation. Tornado, however, lacks built-in support for type annotations and requires additional libraries or manual validation. Automatic Documentation FastAPI аutomatically generates interactive API documentation using OpenAPI and JSON Schema standards. This feature simplifies the process of testing and debugging APIs and ensures accurate documentation. Tornado does not have built-in support for automatic API documentation, and developers must rely on third-party tools or manually maintain API documentation. Dependency Injection FastAPI has a built-in dependency injection system that simplifies managing dependencies, reduces boilerplate code, and enforces a clear separation of concerns. Tornado does not provide a built-in dependency injection mechanism, requiring manual dependency management or the use of external libraries. Learning Curve and Community FastAPI boasts comprehensive and well-structured documentation, making it easier for developers to learn and adopt. Additionally, the FastAPI community has been growing rapidly, providing a wealth of resources and support. While Tornado has a mature community, its documentation and learning resources may not be as extensive or beginner-friendly as FastAPI's. Example: Creating a simple "Hello, World!" API endpoint Tornado: Python import tornado.ioloop import tornado.web class HelloWorldHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, World!") def make_app(): return tornado.web.Application([ (r"/", HelloWorldHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8080) tornado.ioloop.IOLoop.current().start() FastApi: Python from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/") def hello_world(): return {"message": "Hello, World!"} if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8080) Why We Switched From Tornado to FastAPI Considering the key differences outlined above, we at Rеblаzе decided to make the switch from Tornado to FastAPI for the following reasons: Improved Performance: FastAPI's better concurrency and ability to handle more simultaneous connections allow us to serve our customers more efficiently and ensure the best possible user experience. Simplified Development: The automatic validation, documentation, and dependency injection features of FastAPI streamline our development process, reduce potential errors, and allow us to focus on delivering high-quality features and functionality. Future-Proofing: FastAPI's growing popularity and active community ensure that we have access to the latest features, updates, and best practices, allowing us to stay ahead of the curve and maintain a competitive edge. Conclusion Switching from Tornado to FastAPI has provided Rеblаzе with numerous benefits, including improved performance, simplified development, and better future-proofing. While Tornado remains a powerful and capable web framework, FastAPI's modern features and active community make it an excellent choice.
As I talked about in my other article about some of the top Java REST API frameworks, in today's world of modern software development, REST API frameworks play a crucial role in developing efficient and scalable microservices. Java has several frameworks for developing REST APIs, but three of the most popular ones are Spring Boot, Quarkus, and Micronaut. In this article, we will compare these frameworks, their features, and their pros and cons. Spring Boot Spring Boot is a popular Java-based framework that is widely used for developing RESTful APIs. It is built on top of the Spring Framework and provides a simplified and opinionated approach to building microservices. Spring Boot provides a lot of built-in features and functionalities that make it easy to get started with microservices. Pros Easy to learn and get started with Large community support and active development Provides a lot of built-in features and functionalities Good support for testing, security, and database integration Good support for building and deploying containerized applications Cons Can be heavy and slow, especially for smaller applications Configuration can be complex and verbose Some features are opinionated, which can limit flexibility Can require a lot of boilerplate code Quarkus Quarkus is a relatively new Java-based framework that is designed specifically for developing lightweight and fast microservices. It is built on top of popular libraries like Hibernate, Eclipse MicroProfile, and Vert.x, and provides a container-first approach to building microservices. Pros Extremely fast startup time and low memory footprint Good support for building containerized applications Provides a lot of built-in features and functionalities Good support for testing, security, and database integration Good support for building reactive applications Cons Limited community support compared to Spring Boot Fewer features and functionalities than Spring Boot Requires a different mindset and approach to development Limited support for legacy applications and frameworks Micronaut Micronaut is another Java-based framework that is designed for building lightweight and modular microservices. It is built on top of popular libraries like Netty, RxJava, and Groovy, and provides a lot of built-in features and functionalities that make it easy to get started with microservices. Pros Extremely fast startup time and low memory footprint Good support for building containerized applications Provides a lot of built-in features and functionalities Good support for testing, security, and database integration Good support for building reactive applications Cons Limited community support compared to Spring Boot Fewer features and functionalities than Spring Boot Requires a different mindset and approach to development Limited support for legacy applications and frameworks Basic Code Examples Here are some basic code examples for each framework: Spring Boot To create a RESTful web service using Spring Boot, you can start with the following code example: kotlin @RestController public class GreetingController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } } This code defines a REST endpoint at /hello that returns a string "Hello, World!" when accessed. Quarkus To create a RESTful web service using Quarkus, you can start with the following code example: less @Path("/hello") public class GreetingResource { @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return "Hello, World!"; } } This code defines a REST endpoint at /hello that returns a string "Hello, World!" when accessed. Micronaut To create a RESTful web service using Micronaut, you can start with the following code example: less @Controller("/hello") public class GreetingController { @Get @Produces(MediaType.TEXT_PLAIN) public String hello() { return "Hello, World!"; } } This code defines a REST endpoint at /hello that returns a string "Hello, World!" when accessed. Note that these code examples are very basic and don't demonstrate the full capabilities of each framework. Each framework has its own set of features and functionalities that make it unique and suitable for different use cases. Performance In terms of performance, all three frameworks have their own strengths and weaknesses. Here's a brief comparison: Spring Boot Spring Boot is a mature and widely-used framework, with a large and active community. It has been optimized for performance over the years and provides a lot of configuration options to fine-tune performance. However, Spring Boot can be memory-intensive, especially when dealing with large applications or running on limited resources. Quarkus Quarkus is a relatively new framework that is designed to be fast and lightweight. It has been optimized for low memory usage and fast startup times, making it ideal for containerized environments such as Kubernetes. Quarkus is based on a reactive programming model, which can help improve performance by allowing for better utilization of resources. Micronaut Micronaut is also a lightweight and fast framework, designed to be used in microservices architectures. It uses compile-time DI and AOP to minimize runtime overhead, which can help improve performance. Micronaut also has a low memory footprint and fast startup times, making it ideal for serverless architectures. Conclusion In conclusion, all three frameworks - Spring Boot, Quarkus, and Micronaut - have their own strengths and weaknesses. Spring Boot is the most popular and feature-rich framework, but it can be heavy and slow. Quarkus and Micronaut are designed specifically for developing lightweight and fast microservices, but they may have limited community support and features. The choice of framework ultimately depends on the specific requirements of your project and your personal preferences. Overall, each framework has its own strengths and can perform well under different circumstances. It's important to choose the right framework for your use case, based on factors such as the size of your application, the resources you have available, and your performance requirements.
In this article, we’re going to compare some essential metrics of web applications using two different Java stacks: Spring Boot and Eclipse MicroProfile. More precisely, we’ll implement the same web application in Spring Boot 3.0.2 and Eclipse MicroProfile 4.2. These releases are the most recent at the time of this writing. Since there are several implementations of Eclipse MicroProfile, we’ll be using one of the most famous: Quarkus. At the time of this writing, the most recent Quarkus release is 2.16.2. This mention is important regarding Eclipse MicroProfile because, as opposed to Spring Boot, which isn’t based on any specification and, consequently, the question of the implementation doesn’t exist, Eclipse MicroProfile has largely been adopted by many editors who provide different implementations, among which Quarkus, Wildfly, Open Liberty and Payara are from the most evangelical. In this article, we will implement the same web application using two different technologies, Spring Boot and Quarkus, such that to compare their respective two essential metrics: RSS (Resident Set Size) and TFR (Time to First Request). The Use Case The use case that we’ve chosen for the web application to be implemented is a quite standard one: the one of a microservice responsible to manage press releases. A press release is an official statement delivered to members of the news media for the purpose of providing information, creating an official statement, or making a public announcement. In our simplified case, a press release consists in a set of data like a unique name describing its subject, an author, and a publisher. The microservice used to manage press releases is very straightforward. As with any microservice, it exposes a REST API allowing for CRUD press releases. All the required layers, like domain, model, entities, DTOs, mapping, persistence, and service, are present as well. Our point here is not to discuss the microservices structure and modus operandi but to propose a common use case to be implemented in the two similar technologies, Spring Boot and Quarkus, to be able to compare their respective performances through the mentioned metrics. Resident Set Size (RSS) RSS is the amount of RAM occupied by a process and consists of the sum of the following JVM spaces: Heap space Class metadata Thread stacks Compiled code Garbage collection RSS is a very accurate metric, and comparing applications based on it is a very reliable way to measure their associated performances and footprints. Time to First Request (TFR) There is a common concern about measuring and comparing applications' startup times. However, logging it, which is how this is generally done, isn’t enough. The time you’re seeing in your log file as being the application startup time isn’t accurate because it represents the time your application or web server started, but not the one required that your application starts to receive requests. Application and web servers, or servlet containers, might start in a couple of milliseconds, but this doesn’t mean your application can process requests. These platforms often delay work through the process and may give a false, lazy initialization indication about the TFR. Hence, to accurately determine the TFR, in this report, we’re using Clément Escofier’s script time.js, found here in the GitHub repository, which illustrates the excellent book Reactive Systems in Java by Clément Escoffier and Ken Finnigan. Spring Boot Implementation To compare the metrics presented above for the two implementations, you need to clone and run the two projects. Here are the steps required to experience the Spring Boot implementation: Shell $ git clone https://github.com/nicolasduminil/Comparing-Resident-Size- Set-Between-Spring-Boot-and-Quarkus.git metrics $ cd metrics $ git checkout spring-boot $ mvn package $ java -jar target/metrics.jar Here you start by cloning the GIT repository, and once this operation is finished, you go into the project’s root directory and do a Maven build. Then you start the Spring Boot application by running the über JAR created by the spring-boot-maven-plugin. Now you can test the application via its exposed Swagger UI interface by going here. Please take a moment to use the feature that tries it out that Swagger UI offers. The order of operations is as follows: First, the POST endpoint is to create a press release. Please use the editor to modify the JSON payload proposed by default. While doing this, you should leave the field pressReleaseId having a value of “0” as this is the primary key that will be generated by the insert operation. Below, you can see an example of how to customize this payload: JSON { "pressReleaseId": 0, "name": "AWS Lambda", "author": "Nicolas DUMINIL", "publisher": "ENI" } Next, a GET /all is followed by a GET /id to check that the previous operation has successfully created a press release. A PUT to modify the current press release A DELETE /id to clean-up Note: Since the ID is automatically generated by a sequence, as explained, the first record will have the value of “1.” You can use this value in GET /id and DELETE /id requests. Notice that the press release name must be unique. Now, once you have experienced your microservice, let’s see its associated RSS. Proceed as follows: Shell $ ps aux | grep metrics nicolas 31598 3.5 1.8 13035944 598940 pts/1 Sl+ 19:03 0:21 java -jar target/metrics.jar nicolas 31771 0.0 0.0 9040 660 pts/2 S+ 19:13 0:00 grep --color=auto metrics $ ps -o pid,rss,command -p 31598 PID RSS COMMAND 31598 639380 java -jar target/metrics.ja Here, we get the PID of our microservice by looking up its name, and once we have it, we can display its associated RSS. Notice that the command ps -o above will display the PID, the RSS, and the starting command associated with the process, which PID is passed as the -p argument. And as you may see, the RSS for our process is 624 MB (639380 KB). If you’re hesitating about how to calculate this value, you can use the following command: Shell $ echo 639380/1024 | bc 624 As for the TFR, all you need to do is to run the script time.js, as follows: Shell node time.js "java -jar target/metrics.jar" "http://localhost:8080/" 173 ms To resume, our Spring Boot microservice has a RSS of 624 MB and a TFR of 173 ms. Quarkus Implementation We need to perform these same operations to experience our Quarkus microservice. Here are the required operations: Shell $ git checkout quarkus $ mvn package quarkus:dev Once our Quarkus microservice has started, you may use the Swager UI interface here. And if you’re too tired to use the graphical interface, then you may use the curl scripts provided in the repository ( post.sh, get.sh, etc.) as shown below: Shell java -jar target/quarkus-ap/quarkus-run.jar & ./post.sh ./get.sh ./get-1.sh 1 ./update.sh ... Now, let’s see how we do concerning our RSS and TFR: Shell $ ps aux | grep quarkus-run nicolas 24776 20.2 0.6 13808088 205004 pts/3 Sl+ 16:27 0:04 java -jar target/quarkus-app/quarkus-run.jar nicolas 24840 0.0 0.0 9040 728 pts/5 S+ 16:28 0:00 grep --color=auto quarkus-run $ ps -o pid,rss,command -p 24776 PID RSS COMMAND 24776 175480 java -jar target/quarkus-app/quarkus-run.jar $ echo 175480/1024 | bc 168 $ node time.js "java -jar target/quarkus-app/quarkus-run.jar" "http://localhost:8081/q/swagger-ui" 121 ms As you can see, our Quarkus microservice uses an RSS of 168MB, i.e., almost 500MB less than the 624MB with Spring Boot. Also, the TFR is slightly inferior (121ms vs. 173ms). Conclusion Our exercise has compared the RSS and TFR metrics for the two microservices executed with the HotSpot JVM (Oracle JDK 17). Spring Boot and Quarkus support the compilation into native executables through GraalVM. It would have been interesting to compare these same metrics of the native replica of the two microservices, and if we didn’t do it here, that’s because Spring Boot heavily relies on Java introspection and, consequently, it’s significantly more difficult to generate Spring Boot native microservices than Quarkus ones. But stay tuned; it will come soon. The source code may be found here. The GIT repository has a master branch and two specific ones, labeled spring-boot and, respectively, quarkus. Enjoy!
Ethereum has experienced dazzling growth in recent years. According to YCharts, the programmable blockchain now has approximately 220 million unique addresses. Linked to the increase in users is an explosion in the number of dApps. Global companies and startups across finance, sales, HR, accounting, supply chain, and manufacturing are using dApps to streamline processes and onboard new customers. Multiple frameworks exist that simplify the dApp development process for Web2 developers, who want to participate in Web3. This post examines four of the most popular. But first, what is a dApp? What Is dApp? A dApp, or decentralized application, is serverless software that runs on a decentralized network and uses a programmable blockchain for security, transparency, and immutability. A dApp combines smart contracts with a frontend user interface (HTML5, React, Angular). DApps can be used in a variety of industries and services, from social media to supply-chain management, payment tracking, complaint resolution, and all manner of accounting and (decentralized) financial services. How Is a dApp Different From an App? To the end client, a dApp shouldn’t feel any different compared to a traditional app. The differences are beneath the hood. Firstly, unlike a conventional app that has its backend code running on centralized servers, such as AWS or Azure, dApps run on a decentralized peer-to-peer network (blockchain), such as Cardano, Algorand, Polkadot, Solana, or Tezos. However, for this article, we will focus on the most popular network—Ethereum. When designing your decentralized app, building for the Ethereum blockchain starts with selecting the right framework for your needs. dApp Advantages Increased privacy and censorship: Users don’t need to provide an identity to interact with a dApp. This protects user data. Better security: A conventional app runs on centralized servers that are more vulnerable to tampering and data breaches. More interoperability: Traditional apps are mostly isolated, siloed software. dApps give interoperability across the same—and increasingly other—blockchain technology. Trustless: Smart contracts execute in predictable, pre-programmed ways, removing the need for intermediaries. How Do dApps Work With APIs? dApps use APIs to interact and access the functionality of other dApps—to retrieve financial, HR, or accounts data, for example. They can also open their own APIs to the wider ecosystem of Ethereum dApps. Additionally, dApps use APIs to send transactions and interact with smart contracts on Ethereum. Common APIs for Interacting With Ethereum JSON-RPC API: A popular API used to send transactions, read data, and interact with smart contracts. Web3.js: A JavaScript library that provides a user-friendly API for interacting with Ethereum. Web3.js is used to send transactions, read data and interact with smart contracts. Additional functionality includes event handling and contract abstraction. Infura.API: Provides hosted Ethereum nodes so developers can interact with Ethereum without running their own. The Best Frameworks for Developing Ethereum dApps Solidity, the programming language of Ethereum, owes much to JavaScript and C++, as such, Web2 developers should experience a shallow learning curve. However, there are numerous frameworks for developing decentralized apps that make the process for developers more straightforward. Picking the right one will go a long way to determining your success. Here are four of the best frameworks: Source: Truffle Truffle Truffle is a popular development and testing framework for dApps, for first time and experienced Ethereum developers. As well as containing a Web3.js library, Truffle is simple, user friendly and, with over 56K GitHub users, trusted. To install Truffle, you need to have Node, npm, and Python. You can install Truffle via npm with the command npm install -g truffle. Truffle Pros User-friendly interface with a comprehensive suite of developer tools, including smart contract development, testing, and debugging. Write tests in Solidity, JavaScript, and TypeScript and use Drizzle frontend libraries for dApp UI. Layer 2 support develops on EVM and JSON-RPC compatible blockchains such as Optimism, Polygon, Arbitrum and Avalanche. Truffle Cons Steep learning curve and a potential complex testing and debugging environment for first time dApp developers. Reliance on JavaScript is a limitation for experienced Ethereum developers. Truffle Use Cases Building and deploying smart contracts on the Ethereum blockchain. Developing and testing smart contracts locally before deploying them to the blockchain. Automating contract testing and deployment. Managing and interacting with multiple development networks and test nets. Creating and managing digital assets, such as tokens. Building decentralized autonomous organizations (DAOs). Source: Hardhat Hardhat Hardhat allows developers to build, test, and deploy smart contracts and dApps using a variety of tools and libraries. With over 114K users on GitHub and an active Discord community, Hardhat is a hugely popular framework for dApp developers. Much of its popularity can be attributed to its rich list of features, flexibility, and the Hardhat Ethereum Virtual Machine for testing and debugging smart contracts. Hardhat Pros Intuitive debugging and testing environment. Developers get stack traces, console.log, and explicit error messages when transactions fail. Test and deploy dApps via JavaScript, Rust, and TypeScript integration. Active community and trusted by some of the biggest names in Web3—Yearn, Uniswap, Decentraland, and Chainlink. Hardhat Cons Steep learning curve and limited documentation compared to Truffle. Limited support for frontend frameworks for dApp UI design. Designed more for experienced Web3 dApp developers. Hardhat Use Cases Developing and testing smart contracts on a local development network. Automating smart contract testing and deployment. Debugging and troubleshooting smart contract issues. Simulating and testing different network conditions, such as high network latency or low gas prices. Creating and managing multiple development networks for different stages of the development process. Interacting with smart contracts through a user-friendly command line interface (CLI). Source: Embark Embark Similar to Truffle, Embark provides tools and libraries (Web3.js, IPFS, EmbarkJS, and Embark-testrpc) for developing, launching, and maintaining dApps. Additional features of Embark include automatic contract deployment and a user interface for integration with other APIs. Embark is a sound choice for first time Ethereum dApp developers. Embark Pros User-friendly interface. Comes with Cockpit—web-based tools to facilitate the development and debugging of dApps. Multiple libraries, storage, and integration with IPFS, Whisper, and Swarm. Respected debugging and testing environment. Extensive plug-in customization options for full dApp development. Embark Cons Steep learning curve. Reliance on JavaScript. Limited GitHub community and not as popular in Web3 as other frameworks, such as Truffle. Embark Use Cases Building and deploying smart contracts on the Ethereum blockchain. Building frontend user interfaces for dApps, using JavaScript frameworks such as AngularJS and ReactJS. Developing and testing smart contracts locally before deploying them to the blockchain. Integrating dApps with Web3 wallets and other blockchain-related tools. Automating deployment and management of smart contracts and dApps. Source: OpenZeppelin OpenZeppelin OpenZeppelin is a popular dApp framework with some of the biggest companies in Web3 (Decentraland, Aave, ENS, andThe Sandbox). Its smart contract templates and rich reserve of libraries (Network.js, Hotloader) are tried and tested. The OpenZeppelin starter kits make the framework an ideal starting place for first-time Ethereum dApp developers. OpenZepplin Pros OpenZeppelin starter kits are a great way to build your first dApp—reuse community vetted code, upgrade, and test smart contracts and create UI. Widely used open source framework with an active GitHub community and documentation. Extensive and trusted audit service—smart contracts will conform to established standards. OpenZepplin Cons Reliance on Solidity. Steep learning curve. Needs to be used in conjunction with other frameworks, such as Truffle and Embark, for the complete dApp development process. OpenZepplin Use Cases Building decentralized applications on Ethereum. Creating and managing digital assets such as ERC-721, ERC-1155, and ERC-20 tokens. Implementing smart contract security best practices. Building decentralized autonomous organizations. Creating and managing digital identities on the blockchain. dApp Frameworks Summary When it comes to choosing which dApp framework is best for a first-time Ethereum developer, understanding the fundamentals of what a dApp is are critical. It’s vital to consider documentation, how active the community (Reddit, GitHub, Discord) is, and how geared the particular framework is to the needs of your decentralized app. That said, most frameworks offer similar tools, so getting familiar with one might be more beneficial than experimenting with two or three.
After being voted as the best programming language in the year 2018, Python still continues rising up the charts and currently ranks as the third best programming language just after Java and C, as per the index published by Tiobe. With the increasing use of this language, the popularity of test automation frameworks based on Python is increasing as well. Obviously, developers and testers will get a little bit confused when it comes to choosing the best framework for their project. While choosing one, you should judge a lot of things, the script quality of the framework, test case simplicity and the technique to run the modules and find out their weaknesses. This is my attempt to help you compare the top five Python frameworks for test automation in 2019, and their advantages and disadvantages over the other frameworks. So you could choose the ideal Python framework for test automation according to your needs. Robot Framework Used mostly for development that is acceptance test-driven as well as for acceptance testing, the Robot Framework is one of the top Python test frameworks. Although it is developed using Python, it can also run on IronPython, which is .net-based and on Java-based Jython. Robot as a Python framework is compatible across all platforms—Windows, MacOS, or Linux. Prerequisites First of all, you will be able to use Robot Framework (RF), only when you have Python 2.7.14 or any version above it installed. Although, Python 3.6.4 is also used, code snippets provided in the official blog of RF will make sure the appropriate notes are added, consisting of all the changes required. You will also need to install “pip” or Python package manager. Finally, a development framework is a must to download. A popular framework among developers is the PyCharm Community Edition. However, since code snippets are not IDE-dependent, you can use any IDE, which you have worked on earlier. Advantages and Disadvantages of Robot Let’s take a look at the advantages and disadvantages of Robot as a test automation framework over other Python frameworks: Pros Using a keyword-driven-test approach, it makes the automation process simpler by helping the testers easily create readable test cases. Test data syntax can be used easily. Consisting of generic tools and test libraries, it has a vast ecosystem where individual elements can be used in separate projects. The framework is highly extensible since it has many APIs. The Robot framework helps you run parallel tests via a Selenium Grid; however, this feature is not built in. Cons The Robot framework although is tricky when it comes to creating customized HTML reports. However, you could still present xUnit formatted short reports by using the Robot framework. Another flaw of the Robot framework is the inadequacy of parallel testing. Is Robot the Top Python Test Framework for You? If you are a beginner in the automation domain and have less experience in development, using Robot as a top Python test framework is easier to use than Pytest or Pyunit, since it has rich built libraries and involves using an easier test-oriented DSL. However, if you want to develop a complex automation framework, it is better to switch to Pytest or any other framework involving Python code. Pytest Used for all kinds of software testing, Pytest is another top Python test framework for test automation. Being open source and easy to learn, the tool can be used by QA teams, development teams, individual practice groups, and in open source projects. Because of its useful features, like “assert rewriting,” most projects on the internet, including big shots like Dropbox and Mozilla, have switched from unittest (Pyunit) to Pytest. Let’s take a deep dive and find out what’s so special about this Python framework. Prerequisites Apart from a working knowledge in Python, Pytest does not need anything complex. All you need is a working desktop that has: A command line interface Python package manager IDE for development Advantages and Disadvantages of Pytest Pros In the Python testing community, before the arrival of Pytest, developers included their tests inside large classes. However, a revolution was brought by Pytest since it made it possible to write test suites in a very compact manner than before. Other testing tools require the developer, or tester, to use a debugger or check the logs and detect where a certain value is coming from. Pytest helps you write test cases in a way that gives you the ability to store all values inside the test cases and inform you which value failed and which value is asserted. The tests are easier to write and understand since the boilerplate code is not needed that much. Fixtures are functions you can use by adding an argument to your test function. Their job is to return values. In Pytest, you can make them modular by using one fixture from another. Using multiple fixtures helps you cover all the parameter combinations without rewriting test cases. Developers of Pytest released some useful plugins that make the framework extensible. For example, pytest-xdist can be used to execute parallel testing without using a different test runner. Unit tests can also be parameterized without duplicating any code. Provides developers with certain special routines that make test case writing simpler and less prone to errors. The code also becomes shorter and easily understandable. Cons The fact that special routines are used by Pytest means you have to compromise with compatibility. You will be able to conveniently write test cases but won’t be able to use those test cases with any other testing framework. Is Pytest the Top Python Test Framework for You? Well, you have to start by learning a full-fledged language, but once you get the hang of it, you will get all the features like static code analysis, support for multiple IDE, and, most importantly, writing effective test cases. For writing functional test cases and developing a complex framework, it is better than unittest but its advantage is somewhat similar to the Robot framework if your aim is to develop a simple framework. UnitTest (PyUnit) Unittest, or PyUnit, is the standard test automation framework for unit testing that comes with Python. It’s highly inspired by JUnit. The assertion methods and all the cleanup and setup routines are provided by the base class TestCase. The name of each and every method in the subclass of TestCase starts with “test.” This allows them to run as test cases. You can use the load methods and TestSuite class to the group and load the tests. Together, you can use them to build customized test runners. Like Selenium testing with JUnit, unittest also has the ability to use unittest-sml-reporting and generate XML reports. Prerequisites There are no such prerequisites since unittest comes by default with Python. To use it, you will need standard knowledge of the Python framework and if you want to install additional modules, you will need pip installed along with an IDE for development. Advantages and Disadvantages of PyUnit Pros Being part of the standard library of Python, there are several advantages of using Unittest: The developers are not required to install any additional module since it comes with the box. Unittest is xUnit’s derivative and its working principle is similar to other xUnit frameworks. People who do not have a strong background in Python generally find it comfortable to work. You can run individual test cases in a simpler manner. All you need to do is specify the names on the terminal. The output is concise as well, making the framework flexible when it comes to executing test cases. The test reports are generated within milliseconds. Cons Usually, snake_case is used for naming Python codes. But, since this framework is inspired a lot from Junit, the traditional camelCase naming method persists. This can be quite confusing. The intent of the test code sometimes become unclear, since it supports abstraction too much. A huge amount of boilerplate code is required. Is PyUnit the Top Python Test Framework for You? As per my personal opinion and the opinion of other Python developers, Pytest introduced certain idioms, which allowed testers to write better automation code in a very compact manner. Although unittest comes as a default test automation framework, the fact that its working principle and naming conventions are a bit different than standard Python codes, and its requirement of too many boilerplate codes, make it a not so preferred Python test automation framework. Behave We are all aware of behavior driven development, the latest agile-based software development methodology that encourages developers, business participants, and quality analysts to collaborate among each other. Behave is another one of the top Python test frameworks that allows the team to execute BDD testing without any complications. The nature of this framework is quite similar to SpecFlow and Cucumber for automation testing. Test cases are written in a simple readable language and later stuck to the code during execution. The behavior is designed by the behavior specs and the steps are then reused by other test scenarios. Prerequisites Anyone with basic knowledge in Python should be able to use Behave. Let’s take a look at the prerequisites: Before installing Behave, you have to install any version of Python above 2.7.14. Python package manager, or pip, is required to work with Behave. A development environment is the last and most important thing you need. You can use Pycharm, which is preferred by most developers, or any other IDE of your choice. Advantages and Disadvantages of Behave Like all other behavior in driven test frameworks, the opinion regarding Behave’s advantage varies from person to person. Let’s take a look at the common pros and cons of using Behave: Pros System behavior is expressed by semi-formal language and a domain vocabulary that keeps the behavior consistent in the organization. Dev teams who are working on different modules with similar features are properly coordinated. Building blocks are always ready for executing all kinds of test cases. Reasoning and thinking are featured in details, resulting in better product specs. Stakeholders or managers have a better clarity regarding the output of QAs and devs because of the similar format of the specs. Cons The only disadvantage is that it works well only for black box testing. Is Behave the Top Python Test Framework for You? Well, as we said, Behave (Python framework) works best only for black box testing. Web testing is a great example since use cases can be described in plain language. However, for integration testing or unit testing, Behave is not a good choice since the verbosity will only cause complications for complex test scenarios. Developers, as well as testers, recommend pytest-bdd. It is an alternative to Behave since it uses all that is good in Pytest and implements it for testing a behavior driven scenario. Lettuce Lettuce is another simple and easy to use behavior driven automation tool based on Cucumber and Python. The main objective of Lettuce is to focus on the common tasks of behavior driven development, making the process simpler and entertaining. Prerequisites You will need, at minimum, Python 2.7.14 installed along with an IDE. You can use Pycharm or any other IDE of your choice. Also, for running tests, you will be required to install the Python package manager. Advantages and Disadvantages of Lettuce Pros Well, just like any other BDD testing framework, Lettuce enables developers to create more than one scenario and describe the features in the simple natural language. Dev and QA teams are properly coordinated since the specs are of similar format. For black box testing, Lettuce is quite useful for running behavior driven tests cases. Cons There is only one disadvantage of using Lettuce as a Python framework. For successful execution of behavior driven tests, communication is necessary between dev teams, QA, and stakeholders. Absence or communication gap will make the process ambiguous and questions can be raised from any team. Is Lettuce the Top Python Test Framework for You? According to developers and automation testers, Cucumber is more useful when it comes to executing BDD tests. However, if we are talking about Python developers and QA, there is no better replacement than pytest-bdd. All the great features of Pytest, like compactness and easy to understand code, are implemented in this framework combined with the verbosity of behavior driven testing. Wrapping Up! In the above article, we have discussed the top five Python frameworks for test automation in 2019, based on different testing procedures. While Pytest, Robot framework, and unittest are meant for functional and unit testing, Lettuce and Behave are best for behavior driven testing only. From the features stated, we can conclude for functional testing, Pytest is the best. But if you are new to Python-based automation testing, the Robot framework is a great tool to get started. Although the features are limited, it will enable you to get ahead on the track easily. For Python-based BDD testing, Lettuce and Behave are equally good, but if you already have experience with Pytest, it’s better to use pytest-bdd. I hope my article helps you make the right choice out of the top Python test frameworks for your Python web automation needs. Happy testing!
Frameworks have become a fundamental part of modern web development. They help developers build applications faster, reduce the amount of code required, and streamline the development process. However, with so many frameworks available, it can be challenging to choose the right one for your project. In this article, we will provide a beginner's guide to choosing the right framework for your project, covering key factors to consider and popular frameworks that you might want to explore. Factors to Consider When Choosing a Framework When choosing a framework for your project, there are several factors to consider. Here are some of the most important ones: Project Type The type of project you're working on can significantly impact the choice of framework. Some frameworks are designed for specific types of projects, such as data-intensive applications, single-page applications (SPAs), or e-commerce sites. Consider the project's complexity, functionality, and purpose to determine which framework will best suit your needs. Developer Skill Set It's essential to consider the skill set of your development team when selecting a framework. Choosing a framework that aligns with your team's expertise can help you develop the project more efficiently and with fewer errors. Consider your team's programming language proficiency and their experience with frameworks and related technologies. Community Support Frameworks with large and active communities are typically more reliable and easier to work with. A robust community provides access to extensive documentation, support, and an ecosystem of plugins and libraries. Make sure to choose a framework that has a dedicated community behind it to ensure ongoing support and development. Scalability Your framework should be able to scale with your application as it grows. The ability to handle increased traffic, data and functionality is crucial for ensuring that your application can continue to meet user needs over time. Consider the framework's scalability, including its ability to handle large databases, concurrency, and distributed architecture. Performance Performance is a critical factor to consider when choosing a framework. A framework that is slow or inefficient can slow down the application and negatively impact the user experience. Therefore, consider the framework's performance metrics, including its load time, response time, and memory usage, to ensure it performs well under anticipated conditions. Considering these factors, you can evaluate different frameworks and choose the one that best suits your project's requirements. However, keep in mind that no framework is perfect, and there may be trade-offs between different options. Therefore, it's important to weigh each factor against the others to make an informed decision that will support your project's long-term success. Popular Frameworks to Consider When it comes to popular web development frameworks, there are many options to choose from. Here's an overview of five of the most popular frameworks and their key features and benefits: React React is a JavaScript library for building user interfaces. It's widely used for developing single-page applications and is known for its ability to handle complex UI interactions. Some of the key features and benefits of React include the following: Virtual DOM: React uses a virtual DOM to render changes to the UI more efficiently, resulting in better performance and faster updates. Component-Based Architecture: React's component-based architecture makes it easy to reuse UI elements across the application, improving code organization and maintenance. Large Community: React has a massive community of developers and a vast ecosystem of tools, libraries, and resources. Angular Angular is a popular framework for building dynamic web applications. It's known for its declarative syntax and strong typing, making it an excellent choice for large, complex projects. Some of the key features and benefits of Angular include the following: Two-Way Data Binding: Angular's two-way data binding makes it easy to synchronize data between the UI and the application's data model. Dependency Injection: Angular's dependency injection system helps manage application complexity by simplifying the creation and management of objects and services. Built-In Testing: Angular comes with built-in testing capabilities, making it easier to test and maintain your application. Vue.js Vue.js is a progressive JavaScript framework for building user interfaces. It's lightweight, easy to learn, and flexible, making it an excellent choice for small to medium-sized projects. Some of the key features and benefits of Vue.js include the following: Reactive Data Binding: Vue.js uses reactive data binding to keep the UI in sync with the application's data, resulting in a more responsive and efficient UI. Component-Based Architecture: Vue.js uses a component-based architecture that makes it easy to reuse code across the application, improving code organization and maintenance. Small Size: Vue.js is a lightweight framework that can be added to an existing project without adding too much overhead. Django Django is a high-level Python web framework temphasizingrapid development and clean, pragmatic design. It's known for its built-in administrative interface and robust security features. Some of the key features and benefits of Django include: Object-Relational Mapping: Django's object-relational mapping (ORM) makes it easy to interact with databases and manage data models. Built-In Admin Interface: Django comes with a built-in administrative interface, making it easy to manage application content and data. Robust Security: Django includes several built-in security features, including protection against common web application security risks. Ruby on Rails Ruby on Rails is a popular open-source web framework for building dynamic, database-driven web applications. It's known for its convention-over-configuration approach and emphasis on developer productivity. Some of the key features and benefits of Ruby on Rails include: Convention Over Configuration: Ruby on Rails follows a convention-over-configuration approach, reducing the need for developers to write boilerplate code and improving productivity. Modular Design: Ruby on Rails is designed to be modular, making it easy to add new functionality and manage application complexity. Strong Community: Ruby on Rails has a large and active community of developers and a wealth of resources and plugins to help streamline development. Choosing the right framework for your project depends on several factors, including project requirements, team expertise, and development goals. By understanding the features and benefits of these popular frameworks, you can make an informed decision that supports your project's long-term success. How to Choose the Right Framework for Your Project Choosing the right framework for your project can be a daunting task, especially if you're new to web development. To help you make an informed decision, it's essential to evaluate the factors listed in section II against the features of each framework listed in section III. Project Requirements Consider the specific requirements of your project, such as the type of application you're building, the expected traffic volume, and the need for scalability. For example, if you're building a large-scale application that requires high scalability, frameworks like Angular or Ruby on Rails may be a good choice. On the other hand, for smaller projects, lightweight frameworks like Vue.js or React might be a better fit. Developer Skill Set Consider the skills and expertise of your development team. If your team has experience with a particular language or framework, it might be more efficient to stick with what they know. However, if you're looking to learn a new framework or language, choosing a popular framework with a strong community like React or Angular could provide valuable support and resources. Community Support Consider the size and activity of the community surrounding each framework. Frameworks with large communities, like React or Ruby on Rails, often have a wealth of resources, plugins, and support available, making development more efficient and less time-consuming. Scalability Consider the scalability of the framework. Some frameworks, like Angular, are built with scalability in mind and are designed to handle large, complex applications. Others, like Vue.js, may be better suited for smaller projects. Performance Consider the performance of the framework. Frameworks like React and Vue.js are known for their fast rendering and minimal overhead, making them a good choice for applications that require high performance. When weighing these factors, it's important to prioritize them based on the specific needs of your project. For example, if scalability is a top priority, you might want to focus on frameworks like Angular or Ruby on Rails. On the other hand, if you're looking for a lightweight framework that's easy to learn, Vue.js or React might be a better fit. Ultimately, the right framework for your project will depend on your specific needs and goals. However, by evaluating these factors and weighing them against the features and benefits of each framework, you can make an informed decision that supports your project's success. Conclusion Choosing the right framework for your project can be challenging, but it's essential to consider the specific requirements of your project before making a decision. Factors like project type, developer skill set, community support, scalability, and performance are critical to consider. Once you have identified your requirements, you can explore popular frameworks like React, Angular, Vue.js, Django, and Ruby on Rails. Then, with a little research and careful consideration, you can find the perfect framework for your project.
Frontend frameworks are an essential tool for web development because they provide a structured and organized approach to building the user interface of a web application. They help developers create consistent and efficient layouts, styles, and interactions, making developing and maintaining a web application easier over time. It allows your web apps to interact with APIs in the same way as any other program (on desktop OS, mobile device, or elsewhere). Moreover, front-end frameworks can improve the user experience as they keep the common parts of the page intact (like navigation, etc.) and load whatever data the user requests instead of flashing and reloading with every click. In this article, you’ll learn about the most popular frontend frameworks and determine which is best suited for your website or web app. Alternatively, choosing the right front-end framework will help you save time and money. 7 Most Popular Front-End Frameworks The most popular frontend frameworks include React, Angular, and Vue.js, with React being the most widely used at 42.62%. 1) React Jordan Walke developed ReactJS as an open-source frontend JavaScript library for creating structured user interfaces in web apps and websites. React allows developers to design extensive web applications that can update data without the need for a page reload. The primary objective of React is to provide a fast, scalable, and straightforward solution. Since its release in May 2013, React has dominated the front-end development arena. According to reports, 75.4% of web development companies and agencies specialize in React, making it one of the most widely adopted frameworks. React's popularity stems from its simplicity and versatility, which many firms consider to be the future of front-end development. It is used by around 10,499,785 active websites. Many major market players are adopting React development to grow their user base. Examples of React websites include GitHub, Facebook, Airbnb, Instagram, Salesforce, BBC, and Reddit, among others. These leading organizations utilizing React are a clear indication of its growing popularity and its position as a preferred frontend framework. Benefits of React Performance and Speed — React enhances an application’s performance with features like virtual DOM. It helps in improving the speed of web applications by removing the heavy framework codes found in bootstrapping libraries like JQuery. React’s performance and speed are due to the Virtual DOM (Document Object Model). Developers can use it to design faster and more up-to-date applications. This is one of the topmost advantages of using React for the Front end. SEO-Friendly — Another advantage of React is its ability to deal with common problems with search engines. Mainly, these issues are unable to read JavaScript-heavy projects by search engines. It can operate on the server, render the virtual DOM, and return it to the browser as a regular webpage. The effective use of SEO improves the website and app’s ranking on Google search. Getting more users with organic traffic is the most important thing for any business looking for growth opportunities. React allows for simple SEO integration, which is a huge plus for any company. React is one of the most useful tools for building SEO-friendly web applications. Flexible — One of the most-liked benefits of React is flexibility. React code is very simple; it aids in maintaining the flexibility of web or mobile applications. Its flexibility saves a lot of time and money on app development. The major goal of this library is to make the app development process as simple as possible. As a result, React development has delivered notable results in web development. Strong Community Support — One of the most compelling reasons to use React for front-end development is its strong community support. React is continuously improving as an open-source library, thanks to a large community of developers who are helping people all over the world master the technology in various ways. Reusable Components — One of the key advantages of React is the ability to reuse components. Developers save time because they don’t have to write many codes for the same functionalities. Besides, any modifications made to one section of the application will have no effect on other portions of the application. Limitations of Using React Initial learning can be difficult for developers to understand the concepts of JSX. React develops the UI part of the application. To get complete development tools, other technologies integration is required. The high speed of components upgrade makes it difficult to maintain proper documentation. 2) Angular Angular, a front-end JavaScript framework is an open-source tool that enables developers to create interactive website components. Its main objective is to aid in the development of single-page applications, prioritizing code quality and testability. It is highly regarded as the "superhero" among JavaScript frameworks due to its exceptional performance, with over 1,016,104 live websites utilizing Angular. Tech-giant Google is responsible for Angular's development, and major websites such as Paypal, Udemy, Snapchat, Amazon, Netflix, and Gmail rely on it. Angular provides abundant opportunities to create new and innovative projects regularly. Angular is an excellent option for enterprise development, with a strong emphasis on code quality and testability, both of which are critical components of web development. Benefits of Angular Two-Way Binding — This framework enables modeling and view synchronization in real time. As a result, it is simple for developers to make modifications during the development process. Any changes to the data get reflected in the view. Two-way binding makes programming easier and eliminates the need for a testability controller. Angular developers can easily and quickly develop a variety of applications. POJO Model — The Plain Old JavaScript Objects (POJO) Model is used by Angular to make the code structure scalable and independent. This way, we avoid having to introduce complex functions or methods to the program. It also eliminates the need for third-party frameworks or plugins. Apps built with Angular load quickly and give outstanding user accessibility; the model allows us to keep our codes clean, making the framework goal-oriented. Security — RESTFUL APIs are utilized to interact with servers in Angular for web app development. This would safeguard your web application from malicious attacks. As a result, Angular development will provide you with complete peace of mind. Single Page Applications (SPA) — The concept of SPA is used in almost all modern applications. As SPA loads a single HTML page and updates only a part of the page with each mouse click. During the procedure, the page does not reload or transfer control to another page. This guarantees good performance and faster page loading. Great MVC — MVC architecture also assists in the development of apps that are simple to use, adaptable, and dynamic in nature. Additionally, Angular gets closer to the MVVM architecture (Model-View-View-Model), building a stable platform for application development. Limitations of Using Angular A wide variety of intricate built-in features make Angular complex to learn and implement. The possible lag in dynamic applications can hinder the satisfactory performance of the framework. New developers for small-scale web application development can find it difficult to implement. 3) Vue.JS Vue.JS is a JavaScript framework designed for building modern application user interfaces with minimal resource requirements. Currently, there are 1,940,742 active websites utilizing Vue.JS, including major sites like Louis Vuitton, Adobe, BMW, Upwork, Alibaba, Gitlab, and Xiaomi. Vue.JS is primarily focused on the view layer, enabling easy integration into existing projects, and is ideal for building single-page applications. Its popularity stems from several factors, including its ability to re-render without user input, its support for creating reusable and robust components, and its composable nature, allowing for the addition of components as needed. With Vue.JS, developers have access to a comprehensive set of tools that simplify the development process. The framework is also highly adaptable, lightweight, and modular, featuring smart state management and routing options. Additionally, Vue.JS enables rapid development with the help of numerous plugins that offer cost-effective solutions to common application problems. Overall, Vue.JS is a versatile and powerful framework that can facilitate the fast and efficient development of high-quality applications. Benefits of Vue.JS Component-Based Architecture — Vue.JS is a component-based framework; the entire code for the frontend application can be divided into separate components. The components consisting of templates, logic, and styles are bound together to form a web app. Vue.JS components are lightweight, reusable, and simple to test. Lightweight — Vue.JS is only 18-21kb in size. It is up to 4x less than a minified jQuery. It reduces load time and helps in optimizing search engines and performance. Easy Integration — Vue.JS supports many third-party libraries and components. This makes it easy for developers to integrate Vue.JS into their existing projects. This saves a significant amount of time for companies who are attempting to stay on top of industry developments. Progressive — Vue.JS framework is precisely progressive. It is gradually adopted in small steps and adds more markup to the HTML code. Consequently, it changes as per the needs of developers and does not require rewriting an existing application. Vue.JS is a basic script tag that you can insert into your HTML code. It gradually expands as per your needs until it can manage the entire layer. Detailed Documentation — Vue.JS has well-defined documentation that allows you to easily comprehend the required method and develop your application. Additionally, it provides one of the best API references in the business. Vue.JS documentation is regularly updated. Good documentation is essential when using a new framework. Detailed documentation makes the technology easy to use, and you’ll be able to fix bugs effectively. Limitations of Using Vue.JS Vue is still in its growing stage to have a large community. It does not provide a comparative variety of features as compared to frameworks like Angular or React. Built-in documentation in the Chinese language creates a significant language barrier for people out of China. 4) Svelte Svelte is a novel technology for building web applications that comprise components, tools, and guidelines for constructing your website's architecture using JavaScript. One of the distinguishing features of Svelte is that it does not rely on virtual DOM, setting it apart from other front-end frameworks. This characteristic enhances coding efficiency right from the start, resulting in a lighter, more user-friendly website or application. Rich Harris created Svelte in 2016, and it has since gained a devoted following, with 71.4% of users appreciating its remarkable front-end development capabilities. Benefits of Svelte Easy to understand components — Svelte is a clear and neat framework with no unnecessary additions. It has components that make the coding and designing process much easier. Out-of-the-box global state management — Svelte doesn’t need some complicated third-party state management tools; rather, it simply defines a variable as a writeable/ readable store and uses that in all .svelte files preceded by a $ sign. Default style setting — Svelte styles are extended by default. Here, the svelte-class name is attached to your styles to not leak and influence the style of other components. This significantly speeds up the entire design process. Built-in effects and animations — Animation usually requires an external dependency to handle it. However, Svelte provides some pre-packed powerful effect modules like motion, transition, animation, and easing effects. Built-in Accessibility — Svelte displays an “A11y: element should have an alt attribute” reminder whenever you forget to put the alt attribute on a tag. Limitations of Using Svelte Using special syntax instead of directly using onClick, like in React, can be frustrating. No support for reference updates and array mutations. Svelte doesn’t support a wide range of plugins and integrations required for heavy production apps. 5) Next.JS In 2016, Vercel CEO Guillermo Raunch created Next.JS, an open-source JavaScript framework that allows for the development of highly user-friendly and fast websites. This frontend framework is known for its clarity and can be used to create hybrid apps through Automatic Static Optimization, which combines dynamic and static attributes. Next.JS renders both the server side and client side through Universal Apps, making it a great tool for building single-page applications. Next.JS is also highly regarded for its improved search engine optimization (SEO) benefits, which is a boon for marketers. Popular websites such as Hashnode, AT&T, TikTok, and Twitch use Next.JS for their front-end development. Benefits of Next.JS Better SEO — Opting for SSR instead of client-rendered JavaScript helps in making your website visible considerably for search engines. This provides a better competitive edge for your business. Enhanced performance — Ideally, users value a website that loads faster without consuming their valuable time. Next.JS enhances the loading speed and helps to keep your website visitors engaged with better UX. Easy upgrades — The upgrade takes lesser time and is without any complex procedures. This convenience makes it encouraging to take the development experience to the next level. Automated code splitting — Next.JS has a code split on each page. This becomes a great advantage because even after growing the application with more and more pages, the bundle size doesn’t increase. Image optimization — The powerful native API automatically optimizes images with its built-in components. This not only improves developers’ convenience but also refines the user experience of your website. Limitations of Using Next.JS A limited set of adaptable plugins makes it challenging to manage the application. It requires integrating state management tools like MobX or Redux. Next.JS lacks built-in frontend pages and thus requires creating the entire front end diligently. 6) jQuery Introduced in 2006, jQuery remains a popular frontend framework for website development despite its early establishment. Its longevity has given rise to a sizable community for obtaining solutions. Considered one of the best front-end JavaScript frameworks, jQuery is small, simple, feature-rich, and easy to use. It simplifies complicated tasks such as AJAX and DOM manipulation by wrapping them in a single line of code. The jQuery library is packed with brilliant features, including HTML/DOM manipulation, CSS manipulation, HTML event methods, effects and animations, AJAX, and other utilities. Furthermore, there are plugins available for nearly any task. Well-known companies such as Google, Microsoft, IBM, and Netflix, along with 41 million other websites, utilize jQuery. Benefits of jQuery Popularity — It is incredibly famous, with a large community of users and considerable contributors participating as developers and campaigners. Cross-browser support — jQuery is compatible with popular web browsers, including CSS3 selectors and XML Path Language syntax too. Animation Function — CSS properties allow animating elements and even let you adjust the animation duration with transition mode. HTML modifications — It helps in the easier selection of DOM elements to transverse and modify the content for generating custom settings. Lightweight — The minified size of the library is about 19 KB in size. Limitations of Using jQuery Relatively slow working speed Obsolete APIs of the document object model Not convenient to use it for large-scale production 7) Backbone.JS In 2010, Jeremy Ashkenas created Backbone.JS, an open-source JavaScript frontend framework. Its main purpose is to provide structure to web applications through key-value binding and custom events for models. Additionally, Backbone.JS includes a Router that's useful in developing single-page applications. Backbone.JS is particularly suited for creating client-rich applications that consume REST APIs. It simplifies the process by retrieving all the necessary codes (HTML, CSS, and JavaScript) with a single page load, resulting in a smooth and enjoyable user experience. GitHub hosts Backbone.JS, and it offers an online suite, tutorials, and a list of real-world projects that employ it. Some of the companies that use Backbone.JS include Uber, Pinterest, Reddit, and Walmart. Benefits of Backbone.JS Event-driven communication — Backbone.JS alleviates code cluttering that is, either way, difficult to read. The events are built on top of regular DOM events, which makes the mechanism quite extensible and versatile. Maintainability via Conventions — Backbone.JS maintains clean code in spite of having multiple people coordinating on a code. Here, conventions introduce a common coding style that mandates no need for an extensive set of coding standards. Attune with back-end — Backbone.JS provides great support to REST APIs. The correctly designed APIs are configured by the framework for direct access to read, write, and delete operations via GET, POST, and DELETE. Simplicity and Flexibility — Backbone.JS requires only a few minutes to get started, even while using high-level additional libraries like Chaplin. Vast Ecosystem — With large community support, Backbone.JS provides a lot of plugins and extensions. It also has cogent documentation with solutions for most of the problems. Limitations of using Backbone.JS Easy smaller updates to DOM for large data structures can lead to poor UX. Unit testing with Backbone.JS is quite a complicated challenge. Lack of controller building block. Conclusion Ultimately, the best front-end framework for a project will depend on the specific needs and goals of the project, as well as the preferences and experience of the development team. It is important to carefully evaluate the available options and choose a framework that will best support the project’s needs. When selecting a front-end framework for your web development project, it is important to consider a variety of characteristics. These include ensuring that the framework is secure, focused on delivering user-driven outcomes, capable of improving performance, optimized for navigation, capable of retaining visitors, and effectively communicates the business intent. Additionally, there may be other important characteristics to keep in mind as well.
Customers have consistently posed the question of how to extract maximum value from the data residing in their SAP and other enterprise applications. They aim to optimize their business processes across different areas, make informed decisions, and leverage the wealth of data they have accumulated over the years. After all, data is the new oil. Lets Dig Deeper To conduct their core operations, businesses rely on critical functions such as finance, procurement, and supply chain. Making data-driven decisions is crucial, and business line leaders are continuously seeking innovative ways to obtain predictive insights from data stored in their SAP and other enterprise systems. While hosting large SAP systems in the cloud has become easier through technological innovation, many enterprises still struggle to derive value from the data in their SAP and other applications. At Google Cloud, we welcome customer and partner feedback on how we can address these challenges and believe that feedback is a gift, regardless of its form. About Cortex Framework Google Cloud launched the Cortex Framework in October of 2021, which enables customers to leverage their SAP and other applications data and innovate analytics and business processes. Here are the specifics of what the Cortex Framework entails and how it can provide value to customers. The Google Cloud Cortex Framework is a collection of services that helps you build, deploy, and manage advanced analytics solutions using SAP and other applications data on the Google Cloud Platform. The primary objective is to assist customers in expediting the framework's implementation process, allowing them to experiment with it quickly without having to spend weeks establishing data connections and setting up data pipelines. By following the straightforward instructions provided in the git repository readme, customers can deploy the data foundation with the required Google Cloud services, which usually take a few minutes to complete. Customers currently using Looker can also set up pre-constructed Looker dashboards for frequently used analytical scenarios. Value for Every Enterprise The Google Cortex Framework simplifies the integration process through pre-built connectors for common applications and systems. Real-time Insights: The Google Cortex Framework enables organizations to gain real-time insights into their data. By connecting their systems, businesses can create a unified view of their data, allowing them to make more informed decisions and identify trends and patterns that may not have been visible before. Begin your data cloud journey with less complexity, risk, and cost, and expedite business insights and outcomes with the aid of reference architecture patterns, pre-configured deployment content, and integration services. Digital Transformation: The Google Cortex Framework can support digital transformation initiatives by enabling organizations to create a unified view of their data. This can help businesses identify new opportunities, streamline processes, and improve customer experiences. Connect data with less risk, complexity, and costs. Reduce the time, effort, and cost of implementations and achieve desired business outcomes rapidly with proven deployment templates and reference patterns. Accelerate business insights and outcomes. Kickstart insights and business value with easy-to-leverage, scenario-driven packaged analytics solution content, including data models and sample dashboards. Use Cases for Google Cortex Framework Google Cloud customers have the opportunity to leverage the available analytics accelerators to jumpstart their Cortex journey. The list of available accelerators includes: Salesforce Leads Capture and Conversion Opportunity Trends and Pipeline Sales Activities and Engagement Case Overview and Trends Case Management and Resolution Accounts with Cases Accounts Payable Accounts Payable Vendor Spend Analysis Vendor Performance Accounts Receivable Doubtful receivables Days sales outstanding Overdue receivables Accounts receivable Order to Cash Order fulfillment Order status snapshot Order details Sales performance Billing and pricing Industry Solutions Cortex Demand Sensing for SAP CPG Alert potential impacts on-demand plan Forecast outside statistics range Unexpected weather alert Non-seasonal trend alert Promotional differences alert Partner Solutions, Cross Industry Inventory Optimization Supply Network Risk AI Demand Forecasting Assortment Recommendation Product Fulfillment Optimization Many more… Cortex Framework Technical Construct Throughout the Cortex Data Foundation process, you will experience several Google Cloud services being utilized. A brief explanation of each service can help you understand its individual functions. Google BigQuery — Google BigQuery is a cloud-based data warehousing and business intelligence solution provided by Google Cloud. It allows users to analyze massive datasets using SQL-like queries without the need for managing any infrastructure or servers. Cloud Build — Cloud Build is a service that executes your builds on Google Cloud. Cloud Build can import source code from a variety of repositories or cloud storage spaces, execute a build to your specifications, and produce artifacts such as Docker containers or Java archives. Looker — Looker is a business intelligence and data analytics platform that enables organizations to gather, analyze, and share insights from data. It allows users to create customized data visualizations, explore data sets, and share findings with team members. Looker also provides advanced data modeling capabilities, allowing users to create data models and define relationships between different data sources. Cloud Storage — Google Cloud Storage is a cloud-based object storage service offered by Google Cloud. It allows users to store and retrieve unstructured data objects such as photos, videos, and documents in a secure and scalable manner. Cloud Composer — Google Cloud Composer is a fully-managed workflow orchestration service on Google Cloud Platform (GCP) that enables users to author, schedule, and monitor workflows that span across clouds and on-premises data centers. Conclusion The Cortex Framework for SAP is a robust framework that helps businesses streamline data integrations and facilitate advanced analytics-driven decision-making. It offers a unified view of data from both SAP and non-SAP systems, which enables organizations to streamline operations, automate business processes, and obtain real-time insights into their SAP and other applications data. The platform is highly adaptable, allowing businesses to tailor it to their unique requirements. Call-to-Action Are you familiar with the Cortex Framework, or have you already deployed it? If not, here is an automated deployment guide you can follow. I would appreciate any feedback or opinions you have on what you liked or didn't like. Feel free to connect me if you have any further questions. If you find this write-up helpful, please consider sharing it with others. DISCLAIMER: The opinions and viewpoints are solely mine in this article and do not reflect my employer's official position or views. This article should not be considered an official endorsement or statement from my employer.
Application developers, as their name implies, like to develop applications––they ultimately care very little about frontend vs. backend and just want to deliver value to users. Being an application developer myself, and very much like other application developers, one of the things that constantly drive my decision-making when selecting tools and frameworks is the fact that I’m also quite lazy. My main objective is to be able to ship applications with as little effort as possible, and my pet peeve is silly repetitive, mechanical tasks that make me die a little inside every time I need to perform them. For example, I don’t like to remember to align things that don’t automatically align themselves, as one common example of a repetitive task that is completely superfluous. I guess my trademark is that when I encounter challenges, I will always look for ways to automate a solution. (Like the app I once built in the 90s to send a romantic text message to my girlfriend once a day––to overcome my romantic shortcomings). I’ve been building tools and frameworks to increase developer productivity for most of my professional career. This all started in 2006 when I identified a need for modernizing applications created using a low-code generator to C#.NET. I decided to not only create a fully automated migration solution but, more importantly, create a C# class library that would enable an equivalent speed of development that was previously made possible by using the low-code tool. This was a very high bar, as developers who are used to working in low code are also often the type that don’t like the details or the bits and bytes of the internals. A developer happy to use low-code tooling is essentially only looking to write code that gets a specific task done. Being able to replicate this in a coding framework needed to provide as seamless and simple of an experience as they had until now––but with code. Hundreds of organizations have used Firefly’s migration solution, from fortune 500s and governments to small software houses. The C# library provided is still in use today, enabling “low-code level,” highly productive application development combined with the flexibility of code. The ability to efficiently ship full applications with a simple library, to me, felt like something that had to be portable and replicated to the modern web. The wheels began to turn. What Brought Us Here Like many other web developers, when Node.js came out, I was excited about the promise of the backend to the frontend that came with it, that finally, we don’t have to learn two languages to build a full stack application. Just the sheer mental switch between languages––for me, it was C# on the backend and then Javascript on the frontend, and this always came with its toll of friction and context switch that could even be considered debilitating to my dev workflow. Even with the possibility Node.js presented of enabling Javascript on both ends, still, not many developers chose to do so. All of the best practices and learning resources continued to recommend using two separate approaches for the backend and front and a complete separation of tools, libraries, and frameworks with very little sharing of code and patterns for the frontend and backend. This modus operandi of having two separate languages, each with its own syntax and logic, creates the need for a lot of repetitive boilerplates, such as code to pull the data from the database (for every single application entity), code to expose entity CRUD operations as an API, with four, five or even six different routes per entity, methods for these routes, and these all would again get duplicated and reused hundreds of times, and each time further complicated. You get the idea. And this is just on the backend. Now, on the frontend, you have reverse code for this; you have code that takes these JSON responses and rebuilds objects out of these for you to be able to use them on the frontend. Just trying to get data from the database to the users, but, in the meantime, you need code to read the database, serialize the JSON, and send it over a route, only to have to deserialize and query it on the frontend, just to get it in front of the user. This is all mechanical code that practically does nothing. Where eventually, all of this is repeatable. Wait, there’s more. Every API route needs to be able to fetch data, provide some server-side paging, sorting, and filtering, delete, insert, and update; all of these very generic actions are repeated over and over by all developers building full-stack applications all the time in millions of lines of code. Now let’s talk about concerns that cross over from the frontend to the backend that get duplicated. Up until a couple of years ago, the frontend and backend were, at best, sharing types, but there’s so much more to types than strings or integers. Commons questions like: How do you serialize these from JSON and then to JSON? How do you validate them? Today, validations on the frontend and backend are operations that are completely separate. Which begs the question: WHY? Why should I have to remember (as a lazy developer, mind you) to have to perform two separate validations on the frontend and the backend? Duplicate Boilerplate Code There’s also a cultural aspect with this dichotomy between frontend and backend code, where there needs to be such impeccable communication and alignment between the developers that is almost an impossible feat. At the end of the day, all those places are places of friction where things can go wrong, with two completely different developers maintaining the code. Enter Remult Remember when I said that when I encounter a challenge, my first course of action is to try and automate it away? I couldn’t fathom how, in 2018, it still is not viable to be able to get the same code to run on the frontend and the backend. I started toying with this idea to see if I could truly make this possible and improve my productivity (and hopefully for other developers, too)––from validations to typing, through authentication and authorization, all of the typical code that’s constantly duplicated. Remult Backstory Remult started as a side project without a name and with a completely different (albeit noble) purpose. My wife volunteered at a food bank, and as a result, I, too, was volunteered to participate in distributing food parcels to the needy. One day, as I was driving to distribute the parcels, holding a paper with a list of addresses, I found myself getting lost in places you don’t want to get lost, and I knew I had to build an app to help volunteers navigate efficiently. I knew I could solve a lot of friction in the process of delivering food parcels to the needy through code––which is what I do best, and I wanted to focus on building the actual application and its capabilities, and not the pieces that hold it together. So I built an application for inventory and distribution of our local food bank in Even Yehuda, an application they could use to generate distribution lists for volunteer couriers and for the couriers to navigate to and report back on delivery. I wrote the app and, at the same time, the framework as well, the very framework I wanted to have when building web applications. One that would focus on the data flow from the backend database to the frontend framework (the framework of your choice––whether Angular, React, or Vue––it shouldn’t matter). Instead of having to go through the entire process described above of serializing objects for every HTTP call on the frontend and then reversing the entire process back into JSON from the backend to the frontend––this framework made it possible to query on the frontend, using objects, and then automated the entire process from the frontend to the backend and back again. I finally had the framework I dreamed of that eliminates the need to write all of this boilerplate, repetitive, duct tape code over and over again. With its growth and use, a colleague and I worked on the framework, invested in its ability to scale and its stability, improved its API that underwent several iterations, and added many features. The application built upon this framework was quickly adopted by other food banks around Israel, which often encountered similar challenges with parcel delivery. Our application, after its first year, managed to help distribute 17,000 parcels from food banks around Israel. We were quite proud of this achievement––we started feeling like our framework could withstand the test of scale, but we had no idea what was to come next. What COVID Taught Us About Scale and Security Then COVID hit––and lockdowns cut people in need off from the entire world. Suddenly, the need to distribute food to the elderly and disabled skyrocketed. The demand grew from 17,000 parcels annually to 17,000 parcels a day. The app was then contributed for free to municipalities, NGOs, and even the IDF’s Home Front to enable better inventory, allocation, and distribution of parcels around Israel. Once the application was adopted by the IDF, it also underwent a battery of security testing––cyber and penetration testing, which leveled up its security significantly. The backend-to-frontend framework, and the application built upon, which was supposed to be just an experiment, withstood the scale of half a million parcel distributions in 2020 alone and since then has maintained a similar number and is only growing. During COVID, it was adopted by multiple countries around the globe––from Australia to the EU, USA, and South Africa––to respond to similar needs during the pandemic. This is the backbone upon which Remult was built and battle-tested, running on a $16-a-month Heroku server. Once the pandemic was behind us, my co-creator and I realized we learned a lot. We understood the framework was robust and could scale, was aligned with security best practices, and delivered the promise of democratizing the ability to build full-stack applications without all the known friction. We wanted to share this with the world. So we open-sourced the framework to enable other lazy developers to be able to invest their energy in writing excellent applications that deliver value to users and not on repeatable, mechanical code that actually can be automated and shared by the backend and frontend. Conclusion In this article, you were introduced to Remult, an open-source frontend-to-backend framework, its backstory, and what we learned along the way. Let us know what you’d like to see next, and feel free to contribute to the project. In our next article, we’ll do a roundup of tools in the ecosystem looking to solve similar challenges through different approaches and unpack where Remult fits in and what it’s optimized for.
In today’s fast-paced world of software development, we have new technologies and languages for development coming on very frequently. With this, comes several testing and automation tools and frameworks in the related market. Choosing the right set of tools and frameworks becomes an absolute necessity because it impacts the accuracy and TTM (Time to Market). JavaScript is one of the widely used programming languages for web automation testing. It also supports a number of Selenium test automation frameworks for web UI testing. Of all the available ones, the Jasmine framework turns out to be the best-suited, as it provides a stable and functional architecture. It is easy to get started with the Jasmine framework and implement test scenarios with the same. In this tutorial of Selenium automation testing with Jasmine, we look into the nitty-gritty of Jasmine from an automation testing standpoint. We will also learn how to set it up, followed by a sample code writing, and execution. Let’s get started! Introduction to Jasmine Framework Jasmine Framework is an open-source JavaScript testing framework. It is a behavior-driven (BDD), development-inspired framework that is independent of any other frameworks. It is used for unit testing of synchronous and asynchronous JavaScript test scenarios. In addition to its outstanding support for JS, it provides extensive support for Python, Ruby, and other JavaScript-based languages. Furthermore, it is available for different versions like Standalone, Node.js, etc. An additional benefit of using Jasmine is that it is an independent framework with minimal (to no) dependency on language, browser, and platform. The Jasmine framework does not require a DOM and is very easy to set up. Also, it provides an immaculate and easy to read syntax like the example below: describe("A suite is just a function", function() { var a; it("and so is a spec", function() { a = true; expect(a).toBe(true); }); }); Why Use Jasmine Framework as a Testing Framework for JavaScript Tests? Having understood what Jasmine Framework is, let us look at the key advantages of using JavaScript Selenium automation testing for Web UI testing: Easy to set up and easy to write tests. Very fast as it has almost zero overhead and no external dependencies for Jasmine core. It comes with out-of-the-box support to fulfill all the test needs. Can run the browser and Node.js tests with the same framework. An extensive and active community and regularly updated documentation for support and development. Support for usage of spies for test doubles implementation in the framework. It even supports testing of frontend code using the Jasmine-jQuery extension. It also supports test-driven development in addition to behavior-driven development. Unlike other JavaScript testing frameworks, the Jasmine framework has built-in assertions. It comes with an inbuilt test runner, which can be used to run browser tests. Provides a rich number of built-in matchers that can be used to match expectations and add asserts to the test cases. Some examples are: toEqual toBe toBeTruthy Advantages of Using Jasmine Framework With Selenium Jasmine and Selenium are popularly used for JavaScript automation testing and web UI automation testing respectively. When working on a JavaScript-based web UI project, it is better to combine the forces to take the advantage of them: Jasmine framework and Selenium automation testing complement each other in being open-source, easy to implement, and scale. Their capacity to work with almost all browsers and platforms is another added advantage. By using a Selenium Grid, Jasmine framework tests can be executed more quickly through parallel execution. You can refer to our earlier article on the “Importance of Parallel Testing in Selenium” to get a detailed understanding about the advantages offered by parallel test execution. Getting Started With the Jasmine Framework Having gathered some knowledge around the what and why of the Jasmine framework in JavaScript, let us now dig deeper and get our hands dirty with the implementation. In this section of the Selenium Jasmineframework tutorial, we will learn about the workflow of Jasmine and understand the basics of writing test scenarios. Let us assume we need to test a file Test.js using the Jasmine framework. SpecRunner.html would be the output file that will run all test cases from spec.js taking Lib as an input and then show the results in the browser. Lib: Consists of built-in JavaScript files that help test varied functions and other JS files within the project. SpecRunner.html: A usual HTML file that will render the output of the test run in the browser. test.js: This file comprises the actual functionalities/code under test, which is to be tested with the help of the spec.js and lib files. spec.js: Also referenced as the test case file, this contains all the testcases in a prescribed format for the file to be tested. Here are the basic building blocks of the Jasmine framework tests: Suite block: Suite forms the basic building block of the Jasmine framework. One suite is composed of test cases or specs written to test a particular file and is made up of two blocks: the describe() block and it() block. describe(): This is used to group related test cases written under it(). There is only one describe() at the top level, unless the test suite is a nested one. In which case, it takes a string parameter to name the collection of test cases in that particular describe() block. it()—contains specs/test cases: This is used to define the specs or test cases inside the describe() block. Like a describe(), it takes similar parameters—one string for name and one function that is the test case we want to execute. A spec without any assertions is of no use. Each spec in the Jasmine framework consists of at least one assertion, which is referred to as expectation here. If all expectations pass in a spec, it is called a passing spec. On the other hand, if one or more expectations fails in a spec, it is called a failing spec. Note: Since it() and describe() blocks are JavaScript functions, all the basic variable and scope rules apply to them as per JS code. Also, they can contain any valid executable code. This means variables at the describing() level are accessible to all and it() level within the test suite. Expectations or Matchers Expectations or matchers are a way to implement assertions in the Jasmine framework. This is done with the help of the expect function, which takes the actual value produced by the test case as output. It is then chained with a matcher function that takes expected results for that test case and then evaluates them to give a boolean result. The returned value is true if the expectation matches, else it is false. The Jasmine framework also provides the utility to check for negative assertions by adding not before the matcher for a required expect function. All the expect functions come under the it() block, and each it() block can have one or more expect() blocks. The Jasmine framework provides a wide range of in-built matchers and lets you extend matchers via custom matchers: describe("This is a describe block for expectations", function() { it("this is a positive matcher", function() { expect(true).toBe(true); }); it("this is a negative matcher", function() { expect(false).not.toBe(true); }); }); Here is a small example to understand the usage and implementation of the describe(), it(), and expect() blocks. We will be testing a file named Addition.js having a corresponding spec file with test cases as AdditionSpec.js: function Addition() = { initialValue:0, add:function (num) { this.initialValue += num; return this.initialValue; }, addAny:function () { var sum = this.initialValue; for(var i = 0; i < arguments.length; i++) { sum += arguments[i]; } this.initialValue = sum; Return this.initialValue; }, }; describe("to verify Addition.js file",function() { //test case: 1 it("Should have initial value", function () { expect(Addition.initialValue).toEqual(0); }); //test case: 2 it("should add numbers",function() { expect(Addition.add(5)).toEqual(5); expect(Addition.add(5)).toEqual(10); }); //test case :3 it("Should add any number of numbers",function () { expect(Addition.addAny(1,2,3)).toEqual(6); }); }); The Jasmine framework also provides support for nested suites utilizing the nested describe() blocks. Here is an example of a spec file with nesting for the same Addition.js: describe("to verify Addition.js file using nested suites",function() { // Starting of first suite block describe("Retaining values ",function () { //test case:1 it ("Should have initial value", function () { expect(Addition.currentVal).toEqual(0); }); }); //end of first suite block //second suite block describe("Adding single number ",function () { //test case:2 it("should add numbers",function() { expect(Addition.add(5)).toEqual(5); expect(Addition.add(5)).toEqual(10); }); }); //end of second suite block //third suite block describe("Adding Different Numbers",function () { //test case:3 it("Should add any number of numbers",function() { expect(Addition.addAny(1,2,3)).toEqual(6); }); }); //end of third suite block }); Using Standalone Jasmine Framework Distribution for Selenium Automation Testing To get started with the Jasmine framework, follow the below mentioned steps to complete the system setup. Step 1 Download the latest version of Jasmine from the official website. Step 2 Download the standalone zip for the selected version from this page. Step 3 Create a new directory in your system and then add a sub directory to it. Step 4 Move the downloaded standalone zip inside this sub directory and unzip it here. Once unzipped, your directory structure should look something like this. Step 5 To verify the setup, load the SpecRunner.html in your web browser. If you see an output like below, it means you have completed the setup for the Jasmine framework on your system. Let’s see how to modify this to run our test case for the Addition.js using AdditionSpec.js and Nested_AdditionSpec.js. Firstly, we will remove all the existing files from the src and spec folder and add the files for our example, which we have understood already. After doing this, the folder structure would look something like this. Having updated the files, we need one more step to execute our specs, which is to update references to files under the spec and src folder as per our changes in SpecRunner.html. For this, open the SpecRunner.html and it will look like this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Jasmine Spec Runner v3.7.1</title> <link rel="shortcut icon" type="image/png" href="lib/jasmine-3.7.1/jasmine_favicon.png"> <link rel="stylesheet" href="lib/jasmine-3.7.1/jasmine.css"> <script src="lib/jasmine-3.7.1/jasmine.js"></script> <script data-fr-src="lib/jasmine-3.7.1/jasmine-html.js"></script> <script data-fr-src="lib/jasmine-3.7.1/boot.js"></script> <!-- include source files here... --> <script data-fr-src="src/Player.js"></script> <script data-fr-src="src/Song.js"></script> <!-- include spec files here... --> <script data-fr-src="spec/SpecHelper.js"></script> <script data-fr-src="spec/PlayerSpec.js"></script> </head> <body> </body> </html> Update the file name in the src and spec sections and save it. Now, you are ready to load the SpecRunner.html again to see the results. Setting Up the Jasmine Framework Environment Using npm To get started with Selenium automation testing using the Jasmine framework in JavaScript, we need to have some prerequisite setup in our system: Step 1 Make sure the latest JavaScript version is installed on the system. Also, check for Node.js and npm on your system and upgrade to the newest version if required: brew install node npm install npm@latest -g Step 2 Navigate to the directory where you want to create your test case, execute it, and install the Jasmine framework by triggering the npm command: npm install -g jasmine Step 3 Once this is done, we will install Chrome Driver and Selenium WebDriver in the same directory to execute the Jasmine framework Selenium test cases on the local Selenium Grid: npm install --save chromedriver npm install --save selenium-webdriver Step 4 Once all this is done, we are good to initialize our Jasmine framework project using the init command: jasmine init You should be able to see a spec folder, which will be further used for adding test case files. For this Selenium Jasmine framework JavaScript tutorial, we will be using the following .js file: // Require modules used in the logic below const {Builder, By, Key, until} = require('selenium-webdriver'); // You can use a remote Selenium Hub, but we are not doing that here require('chromedriver'); const driver = new Builder() .forBrowser('chrome') .build(); // Setting variables for our testcase const baseUrl = 'https://accounts.lambdatest.com/login' // function to check for login elements and do login var loginToLamdbatest = async function() { let loginButton = By.xpath('//button'); // navigate to the login page await driver.get(baseUrl); // wait for login page to be loaded await driver.wait(until.elementLocated(loginButton), 10 * 1000); console.log('Login screen loaded.') } //to set jasmine default timeout jasmine.DEFAULT_TIMEOUT_INTERVAL = 20 * 1000; // Start to write the first test case describe("Selenium test case for login page", function() { it("verify page elements", async function() { console.log('<----- Starting to execute test case ----->'); //to do login await loginToLamdbatest(); var welcomeMessage = By.xpath('//*[@class="form_title"]'); //verify welcome message on login page expect(await driver.findElement(welcomeMessage).getText()).toBe('Welcome Back !'); //to quit the web driver at end of test case execution await driver.quit(); console.log('<----- Test case execution completed ----->'); }); }); In this example file, we have automated a scenario to navigate to the LambdaTest login page and then verify the welcome message on the page. We have used a local Selenium WebDriver and running the tests on the Chrome browser. To execute the test case, use the following command if you are at the same directory level as the file.: jasmine exampleSeleniumSpec.js Once triggered, you will see a Chrome browser tab open up on your system and get redirected to a given page, and after successful verification, the browser is closed, and the terminal shows logs like below: ⇒ jasmine example-spec.js Randomized with seed 07075 Started <----- Starting to execute test case -----> Login screen loaded. <----- Test case execution completed -----> . 1 spec, 0 failures Finished in 7.882 seconds Randomized with seed 07075 (jasmine --random=true --seed=07075) Using Jasmine to Run Selenium Tests on Selenium Grid Running tests on a local Selenium Grid is not a scalable and reliable approach. You would need to invest significantly in building the test infrastructure if the tests have to be run across a number of browsers, platforms, and device combinations. This is where cloud testing can be useful as it offers the much-needed benefits of scalability, reliability, and parallel test execution. We will run the Jasmine framework tests on Selenium Grid Cloud on LambdaTest. You will need to have your LambdaTest username and access token handy to continue with the execution, details are available in the LambdaTest profile section. Set the following environment variables on your machine: For Mac/Linux export LT_USERNAME="YOUR_USERNAME" export LT_ACCESS_KEY="YOUR ACCESS KEY" For Windows set LT_USERNAME="YOUR_USERNAME" set LT_ACCESS_KEY="YOUR ACCESS KEY" Once this is done, we modify the spec file to have a remote web driver configuration for the LambdaTest Hub to execute test cases on the grid. For this, we will be adding the required browser capabilities for execution on the LambdaTest Grid and use a remote web driver on their grid. Modified exampleSeleniumSpec.js as per our requirements would look like this: // Require modules used in the logic below selenium = require('selenium-webdriver'); const {Builder, By, Key, until} = require('selenium-webdriver'); // Setting variables for our testcase const baseUrl = 'https://accounts.lambdatest.com/login' const username= process.env.LT_USERNAME || "<Your_lambdatest_username>" const accessKey= process.env.LT_ACCESS_KEY || "<Your_lambdatest_accessKey>" var remoteHub = 'https://' + username + ':' + accessKey + '@hub.lambdatest.com/wd/hub'; const caps = { 'build': 'Jasmine-selenium-javascript', 'browserName': 'chrome', 'version':'73.0', 'platform': 'Windows 10', 'video': true, 'network': true, 'console': true, 'visual': true }; const driver = new selenium.Builder(). usingServer(remoteHub). withCapabilities(caps). build(); // function to check for login elements and do login var loginToLamdbatest = async function() { let loginButton = By.xpath('//button'); // navigate to the login page await driver.get(baseUrl); // wait for login page to be loaded await driver.wait(until.elementLocated(loginButton), 10 * 1000); console.log('Login screen loaded.') } //to set jasmine default timeout jasmine.DEFAULT_TIMEOUT_INTERVAL = 20 * 1000; jasmine.getEnv().defaultTimeoutInterval = 60000; // Start to write the first test case describe("Selenium test case for login page", function() { it("verify page elements", async function() { console.log('<----- Starting to execute test case ----->'); //to do login await loginToLamdbatest(); var welcomeMessage = By.xpath('//*[@class="form_title"]'); //verify welcome message on login page expect(await driver.findElement(welcomeMessage).getText()).toBe('Welcome Back !'); //to quit the web driver at end of test cae execution await driver.quit(); console.log('<----- Test case execution completed ----->'); }); }); This would also have a similar command to execute and would give the same output as follows on the terminal: ⇒ jasmine lambdatest.js Randomized with seed 11843 Started <----- Starting to execute test case -----> Login screen loaded. <----- Test case execution completed -----> . 1 spec, 0 failures Finished in 15.777 seconds Randomized with seed 11843 (jasmine --random=true --seed=11843) You can now navigate the LambdaTest dashboard for the user account and view the execution results and logs on various tabs. Under “Recent Tests” on the left side, you can see the latest execution on the Dashboard tab. To analyze the complete timeline for your different test case runs, we can navigate to the “Automation” Tab. In the “Automation” tab, go to the “Automation Logs” section to view the entire execution logs and video of our test case. This helps in debugging the issues by analyzing the run. You can also navigate to other tabs and per the requirement to add/view data for the execution. With this, we have completed our Jasmine framework JavaScript Selenium tutorial to understand the setup and execution with Jasmine framework on the local and LambdaTest Grid cloud. It’s a Wrap So, in this Jasmine framework tutorial with Selenium, we learned about the whats and whys of Jasmine and Selenium, how they make a good combination for automation web UI-based code using JavaScript, and all advantages it provides. Having done the setup and understanding the test case basics, we have successfully executed our test case on local and Selenium Grid with the help of LambdaTest. So, get started and write your first Selenium automation testing code with Jasmine and JavaScript. Happy Testing!
Justin Albano
Software Engineer,
IBM
Thomas Hansen
CTO,
AINIRO.IO
Hiren Dhaduk
CTO,
Simform
Tetiana Stoyko
CTO, Co-Founder,
Incora Software Development