Skip to content

**DO NOT SUBMIT** Testing GSE gen content #6523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 178 additions & 0 deletions src/content/gse/chapter_chapter_1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
---
title: "Chapter 1: Anatomy of a Dart program"
description: "Learn about `main` function, `pubspec.yaml`, `analysis_options.yaml`"
---

# Chapter 1: Anatomy of a Dart program
Learn about `main` function, `pubspec.yaml`, `analysis_options.yaml`

[Video Placeholder]

In this lesson, you'll get your first look at a Dart program. We'll cover the basic structure of a Dart project, including the `main` function (the entry point of your program) and the important configuration files: `pubspec.yaml` and `analysis_options.yaml`. By the end of this lesson, you'll be able to create, run, and understand the basic components of a Dart application.

## Background / Key Concepts
* **`main` Function:** Every Dart program needs a `main` function. This is where your program starts executing. Think of it as the "ignition switch" for your app.
* **`pubspec.yaml`:** This file is the heart of your Dart project. It defines the project's name, version, dependencies (other packages your project needs), and other important metadata. It's like the manifest for your app.
* **`analysis_options.yaml`:** This file configures the Dart analyzer, a tool that helps you find potential problems in your code, enforce coding style, and improve code quality. It's like having a code reviewer built into your development environment.
* **Packages:** In Dart, code is organized into packages. A package is a reusable unit of code that can be shared across multiple projects.

## Set up

No setup is required for this chapter. We'll start from scratch by creating a new Dart project.

## Tasks

In this lesson, we'll create a new Dart project, explore its structure, and run the default application.

### Create a new Dart project

1. Open your terminal or command prompt.

2. Navigate to the directory where you want to create your project.

3. Run the following command:

```bash
dart create wikipedia
```

This command uses the `dart create` tool to generate a basic Dart project named "wikipedia". This command scaffolds a CLI (Command Line Interface) application. It sets up the basic directory structure and files you need to get started.

You should see output similar to this:

```bash
Creating project 'wikipedia'...
Running pub get in wikipedia...
Wrote wikipedia/analysis_options.yaml.
Wrote wikipedia/bin/wikipedia.dart.
Wrote wikipedia/lib/wikipedia.dart.
Wrote wikipedia/test/wikipedia_test.dart.
Wrote wikipedia/pubspec.yaml.
Wrote wikipedia/README.md.

All done!
```

4. Navigate into the newly created `wikipedia` directory:

```bash
cd wikipedia
```

### Explore the project structure

The `dart create` command has generated the following directory structure:

```dart
wikipedia/
├── analysis_options.yaml
├── bin
│ └── wikipedia.dart
├── lib
│ └── wikipedia.dart
├── pubspec.yaml
├── README.md
└── test
└── wikipedia_test.dart
```

Let's break down each file and directory:

* **`analysis_options.yaml`:** We already discussed this file. This is where you configure the Dart analyzer. Open it and you'll see it includes `package:lints/recommended.yaml`. This enables a set of recommended "lints" (rules) that help you write better code.
* **`bin/`:** This directory contains the executable code for your application. In this case, `bin/wikipedia.dart` is the main entry point.
* **`lib/`:** This directory contains the library code for your application. This is where you'll put reusable code that can be shared across different parts of your application, or even across multiple projects. `lib/wikipedia.dart` is where our `calculate` function lives.
* **`pubspec.yaml`:** We also discussed this file. This declares metadata and dependancies for the project.
* **`README.md`:** This file contains a description of your project. It's good practice to keep this file updated with information about your application.
* **`test/`:** This directory contains the tests for your application. Writing tests is crucial for ensuring that your code works as expected.

### Examine the `pubspec.yaml` file

Open the `pubspec.yaml` file in your code editor. You should see something like this:

```yaml
name: wikipedia
description: A sample command-line application.
version: 1.0.0
# repository: https://github.com/my_org/my_repo

environment:
sdk: ^3.7.0

# Add regular dependencies here.
dependencies:
# path: ^1.8.0

dev_dependencies:
lints: ^2.0.0
test: ^1.16.0
```

* **`name`:** The name of your project.
* **`description`:** A short description of your project.
* **`version`:** The version number of your project.
* **`environment`:** Specifies the Dart SDK version that your project requires.
* **`dependencies`:** Lists the packages that your project depends on. Notice the comment `# path: ^1.8.0`. If your project required a dependancy on the `path` package, you would uncomment this line.
* **`dev_dependencies`:** Lists the packages that are only needed during development, such as testing frameworks and linters.

### Run the default application

1. From the root directory of your project (`wikipedia`), run the following command:

```bash
dart run bin/wikipedia.dart
```

This command tells Dart to execute the `bin/wikipedia.dart` file.

2. You should see the following output:

```bash
Hello world: 42!
```

Congratulations! You've successfully run your first Dart program!

### Analyze the code

Let's take a closer look at the code that generated this output. Open `bin/wikipedia.dart` in your code editor. You should see something like this:

```dart
import 'package:wikipedia/wikipedia.dart' as wikipedia;

void main(List<String> arguments) {
print('Hello world: ${wikipedia.calculate()}!');
}
```

* **`import 'package:wikipedia/wikipedia.dart' as wikipedia;`:** This line imports the code from `lib/wikipedia.dart`. The `as wikipedia` part gives the imported code a namespace, so you can refer to it as `wikipedia`.
* **`void main(List<String> arguments) { ... }`:** This is the `main` function. It's the entry point of your program. The `List<String> arguments` part allows you to pass command-line arguments to your program (we'll cover this later).
* **`print('Hello world: ${wikipedia.calculate()}!');`:** This line prints the text "Hello world: " followed by the result of calling the `calculate()` function (defined in `lib/wikipedia.dart`), followed by an exclamation point. The `${}` syntax is used for string interpolation, which allows you to embed the result of an expression directly into a string.

Now, open `lib/wikipedia.dart`. You should see something like this:

```dart
int calculate() {
return 6 * 7;
}
```

This code defines a simple function called `calculate()` that returns the product of 6 and 7 (which is 42).

[Pop out placeholder: Try changing the value returned by the `calculate()` function and rerun the program. Observe the change in the output.]

## Review

In this lesson, you learned about the basic structure of a Dart project, including the `main` function, the `pubspec.yaml` and `analysis_options.yaml` files, and how to run a Dart program. You also got a glimpse of how code is organized into libraries and how to import code from other libraries.

**Quiz Question:**

Which file defines the dependencies of a Dart project?

* [Option A] `analysis_options.yaml`
* [Option B] `pubspec.yaml`
* [Option C] `README.md`
* [Option D] `bin/wikipedia.dart`

## Next lesson

In the next lesson, we'll dive deeper into Dart syntax and start building a more interactive command-line application. You'll learn how to read user input, use control flow statements, work with collections, and more!
147 changes: 147 additions & 0 deletions src/content/gse/chapter_chapter_10.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
---
title: "Chapter 10: Testing"
description: "Learn about `package:test`, `group`, `test`, `expect`, and matchers."
---

# Chapter 10: Testing

Learn about `package:test`, `group`, `test`, `expect`, and matchers.

[Video Placeholder]

In this lesson, we'll introduce you to the world of testing in Dart. Testing is a crucial part of software development, ensuring that your code behaves as expected and remains reliable over time. We'll be using the `package:test`, a powerful and flexible testing framework for Dart. You'll learn how to write unit tests, group related tests, use `expect` to assert that values match your expectations, and leverage matchers for more complex assertions. By the end of this lesson, you'll be able to write effective tests for your Dart code and ensure its robustness.

## Background / Key Concepts
* **`package:test`:** A Dart package that provides a framework for writing and running tests. It includes features for organizing tests, making assertions, and reporting results.
* **Unit Tests:** Tests that focus on verifying the behavior of individual units of code, such as functions, methods, or classes.
* **`group()`:** A function from `package:test` that allows you to group related tests together, providing a clear structure for your test suite.
* **`test()`:** A function from `package:test` that defines an individual test case. Each test case should focus on verifying a specific aspect of your code's behavior.
* **`expect()`:** A function from `package:test` that asserts that a value matches your expectations. It takes two arguments: the actual value and the expected value (or a matcher).
* **Matchers:** Objects that define a set of criteria for matching values. `package:test` provides a variety of built-in matchers for common assertions, such as equality, inequality, string matching, and collection matching.

## Set up
Make sure you have completed Chapter 9 and have a working Dart project set up with the `cli`, `command_runner`, and `wikipedia` packages.

## Tasks
In this lesson, we'll add tests for the `Summary`, `TitleSet`, `Article`, and `SearchResults` classes in the `wikipedia` package. We'll use `group`, `test`, `expect`, and various matchers from the `package:test` to verify that the JSON deserialization methods in these classes are working correctly.

### Update `wikipedia/pubspec.yaml`

1. Ensure that the `test` dependancy is present in the `dev_dependencies` section of the `wikipedia/pubspec.yaml` file.
```yaml
dev_dependencies:
lints: ^5.0.0
test: ^1.24.0
```
If you had to update this file, run `dart pub get` from the `wikipedia` directory.

### Add Tests to `model_test.dart`
1. Open `wikipedia/test/model_test.dart` in your code editor.

2. Replace the existing code with the following:

```dart
import 'dart:convert';
import 'dart:io';

import 'package:test/test.dart';
import 'package:wikipedia/src/model/article.dart';
import 'package:wikipedia/src/model/search_results.dart';
import 'package:wikipedia/src/model/summary.dart';

const String dartLangSummaryJson = './test/test_data/dart_lang_summary.json';
const String catExtractJson = './test/test_data/cat_extract.json';
const String openSearchResponse = './test/test_data/open_search_response.json';

// [Step 10 update] adds all tests
void main() {
group('deserialize example JSON responses from wikipedia API', () {
test('deserialize Dart Programming Language page summary example data from '
'json file into a Summary object', () async {
final String pageSummaryInput =
await File(dartLangSummaryJson).readAsString();
final Map<String, Object?> pageSummaryMap =
jsonDecode(pageSummaryInput) as Map<String, Object?>;
final Summary summary = Summary.fromJson(pageSummaryMap);
expect(summary.titles.canonical, 'Dart_(programming_language)');
});

test('deserialize Cat article example data from json file into '
'an Article object', () async {
final String articleJson = await File(catExtractJson).readAsString();
final List<Object?> articleAsMap = jsonDecode(articleJson);
final List<Article> article = Article.listFromJson(
articleAsMap as Map<String, Object?>,
);
expect(article.first.title.toLowerCase(), 'cat');
});

test('deserialize Open Search results example data from json file '
'into an SearchResults object', () async {
final String resultsString =
await File(openSearchResponse).readAsString();
final List<Object?> resultsAsList =
jsonDecode(resultsString) as List<Object?>;
final SearchResults results = SearchResults.fromJson(resultsAsList);
expect(results.results.length, greaterThan(1));
});
});
}
```

3. **Explanation:**

* **`import 'package:test/test.dart';`:** Imports the `package:test` library, providing access to the testing framework.
* **`group('deserialize example JSON responses from wikipedia API', () { ... });`:** Defines a group of tests related to deserializing JSON responses from the Wikipedia API. This helps organize the tests and provides a clear description of their purpose.
* **`test('deserialize Dart Programming Language page summary example data from ...', () async { ... });`:** Defines a test case for deserializing the Dart Programming Language page summary data. Each test case contains the following steps:
* **`final String pageSummaryInput = await File(dartLangSummaryJson).readAsString();`:** Reads the contents of the JSON file into a string.
* **`final Map<String, Object?> pageSummaryMap = jsonDecode(pageSummaryInput) as Map<String, Object?>;`:** Decodes the JSON string into a `Map<String, Object?>`.
* **`final Summary summary = Summary.fromJson(pageSummaryMap);`:** Deserializes the JSON data into a `Summary` object using the `Summary.fromJson` method.
* **`expect(summary.titles.canonical, 'Dart_(programming_language)');`:** Asserts that the `canonical` property of the `titles` object in the `Summary` object is equal to `'Dart_(programming_language)'`. This verifies that the JSON data was correctly deserialized.
* **`expect(article.first.title.toLowerCase(), 'cat');`:** Asserts that the article title is "cat" (case-insensitive)
* **`expect(results.results.length, greaterThan(1));`:** Asserts that the search results contains more than one result

### Run the Tests
1. Open your terminal or command prompt.

2. Navigate to the root directory of the `wikipedia` package.

3. Run the following command:

```bash
dart test test/model_test.dart
```

This command tells Dart to execute the tests defined in the `wikipedia/test/model_test.dart` file.

You should see output similar to this:

```bash
00:02 +3: All tests passed!
```

This indicates that all three tests passed successfully.

[Pop out placeholder: Experiment with different matchers. For example, try using `expect(summary.pageid, isA<int>())` to assert that the `pageid` property is an integer.]

## Review

In this lesson, you learned how to:

* Use the `package:test` to write unit tests in Dart.
* Use the `group` function to organize related tests into logical groups.
* Use the `test` function to define individual test cases.
* Use the `expect` function to assert that values match your expectations.
* Use various matchers from `package:test` to perform more complex assertions.

**Quiz Question:**

What is the purpose of the `expect` function in `package:test`?
* [Option A] To define a group of related tests.
* [Option B] To define an individual test case.
* [Option C] To assert that a value matches your expectations.
* [Option D] To import a package.

## Next lesson

In the next lesson, we'll implement the Wikipedia API calls and integrate them into our command-line application. We'll learn how to make HTTP requests, handle responses, and parse the data into our data model classes.
Loading